fields.tsx 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. import isEqual from 'lodash/isEqual';
  2. import {RELEASE_ADOPTION_STAGES} from 'sentry/constants';
  3. import {MetricsType, Organization, SelectValue} from 'sentry/types';
  4. import {assert} from 'sentry/types/utils';
  5. import {METRIC_TO_COLUMN_TYPE} from '../metrics/fields';
  6. export type Sort = {
  7. field: string;
  8. kind: 'asc' | 'desc';
  9. };
  10. // Contains the URL field value & the related table column width.
  11. // Can be parsed into a Column using explodeField()
  12. export type Field = {
  13. field: string;
  14. // When an alias is defined for a field, it will be shown as a column name in the table visualization.
  15. alias?: string;
  16. width?: number;
  17. };
  18. export type ColumnType =
  19. | 'boolean'
  20. | 'date'
  21. | 'duration'
  22. | 'integer'
  23. | 'number'
  24. | 'percentage'
  25. | 'string';
  26. export type ColumnValueType = ColumnType | 'never'; // Matches to nothing
  27. export type ParsedFunction = {
  28. arguments: string[];
  29. name: string;
  30. };
  31. type ValidateColumnValueFunction = ({name: string, dataType: ColumnType}) => boolean;
  32. export type ValidateColumnTypes =
  33. | ColumnType[]
  34. | MetricsType[]
  35. | ValidateColumnValueFunction;
  36. export type AggregateParameter =
  37. | {
  38. columnTypes: Readonly<ValidateColumnTypes>;
  39. kind: 'column';
  40. required: boolean;
  41. defaultValue?: string;
  42. }
  43. | {
  44. dataType: ColumnType;
  45. kind: 'value';
  46. required: boolean;
  47. defaultValue?: string;
  48. placeholder?: string;
  49. }
  50. | {
  51. dataType: string;
  52. kind: 'dropdown';
  53. options: SelectValue<string>[];
  54. required: boolean;
  55. defaultValue?: string;
  56. placeholder?: string;
  57. };
  58. export type AggregationRefinement = string | undefined;
  59. // The parsed result of a Field.
  60. // Functions and Fields are handled as subtypes to enable other
  61. // code to work more simply.
  62. // This type can be converted into a Field.field using generateFieldAsString()
  63. // When an alias is defined for a field, it will be shown as a column name in the table visualization.
  64. export type QueryFieldValue =
  65. | {
  66. field: string;
  67. kind: 'field';
  68. alias?: string;
  69. }
  70. | {
  71. field: string;
  72. kind: 'calculatedField';
  73. alias?: string;
  74. }
  75. | {
  76. field: string;
  77. kind: 'equation';
  78. alias?: string;
  79. }
  80. | {
  81. function: [AggregationKey, string, AggregationRefinement, AggregationRefinement];
  82. kind: 'function';
  83. alias?: string;
  84. };
  85. // Column is just an alias of a Query value
  86. export type Column = QueryFieldValue;
  87. export type Alignments = 'left' | 'right';
  88. const CONDITIONS_ARGUMENTS: SelectValue<string>[] = [
  89. {
  90. label: 'is equal to',
  91. value: 'equals',
  92. },
  93. {
  94. label: 'is not equal to',
  95. value: 'notEquals',
  96. },
  97. {
  98. label: 'is less than',
  99. value: 'less',
  100. },
  101. {
  102. label: 'is greater than',
  103. value: 'greater',
  104. },
  105. {
  106. label: 'is less than or equal to',
  107. value: 'lessOrEquals',
  108. },
  109. {
  110. label: 'is greater than or equal to',
  111. value: 'greaterOrEquals',
  112. },
  113. ];
  114. // Refer to src/sentry/search/events/fields.py
  115. // Try to keep functions logically sorted, ie. all the count functions are grouped together
  116. export const AGGREGATIONS = {
  117. count: {
  118. parameters: [],
  119. outputType: 'number',
  120. isSortable: true,
  121. multiPlotType: 'area',
  122. },
  123. count_unique: {
  124. parameters: [
  125. {
  126. kind: 'column',
  127. columnTypes: ['string', 'integer', 'number', 'duration', 'date', 'boolean'],
  128. defaultValue: 'user',
  129. required: true,
  130. },
  131. ],
  132. outputType: 'number',
  133. isSortable: true,
  134. multiPlotType: 'line',
  135. },
  136. count_miserable: {
  137. getFieldOverrides({parameter}: DefaultValueInputs) {
  138. if (parameter.kind === 'column') {
  139. return {defaultValue: 'user'};
  140. }
  141. return {
  142. defaultValue: parameter.defaultValue,
  143. };
  144. },
  145. parameters: [
  146. {
  147. kind: 'column',
  148. columnTypes: validateAllowedColumns(['user']),
  149. defaultValue: 'user',
  150. required: true,
  151. },
  152. {
  153. kind: 'value',
  154. dataType: 'number',
  155. defaultValue: '300',
  156. required: true,
  157. },
  158. ],
  159. outputType: 'number',
  160. isSortable: true,
  161. multiPlotType: 'area',
  162. },
  163. count_if: {
  164. parameters: [
  165. {
  166. kind: 'column',
  167. columnTypes: validateDenyListColumns(
  168. ['string', 'duration'],
  169. ['id', 'issue', 'user.display']
  170. ),
  171. defaultValue: 'transaction.duration',
  172. required: true,
  173. },
  174. {
  175. kind: 'dropdown',
  176. options: CONDITIONS_ARGUMENTS,
  177. dataType: 'string',
  178. defaultValue: CONDITIONS_ARGUMENTS[0].value,
  179. required: true,
  180. },
  181. {
  182. kind: 'value',
  183. dataType: 'string',
  184. defaultValue: '300',
  185. required: true,
  186. },
  187. ],
  188. outputType: 'number',
  189. isSortable: true,
  190. multiPlotType: 'area',
  191. },
  192. eps: {
  193. parameters: [],
  194. outputType: 'number',
  195. isSortable: true,
  196. multiPlotType: 'area',
  197. },
  198. epm: {
  199. parameters: [],
  200. outputType: 'number',
  201. isSortable: true,
  202. multiPlotType: 'area',
  203. },
  204. failure_count: {
  205. parameters: [],
  206. outputType: 'number',
  207. isSortable: true,
  208. multiPlotType: 'line',
  209. },
  210. min: {
  211. parameters: [
  212. {
  213. kind: 'column',
  214. columnTypes: validateForNumericAggregate([
  215. 'integer',
  216. 'number',
  217. 'duration',
  218. 'date',
  219. 'percentage',
  220. ]),
  221. defaultValue: 'transaction.duration',
  222. required: true,
  223. },
  224. ],
  225. outputType: null,
  226. isSortable: true,
  227. multiPlotType: 'line',
  228. },
  229. max: {
  230. parameters: [
  231. {
  232. kind: 'column',
  233. columnTypes: validateForNumericAggregate([
  234. 'integer',
  235. 'number',
  236. 'duration',
  237. 'date',
  238. 'percentage',
  239. ]),
  240. defaultValue: 'transaction.duration',
  241. required: true,
  242. },
  243. ],
  244. outputType: null,
  245. isSortable: true,
  246. multiPlotType: 'line',
  247. },
  248. sum: {
  249. parameters: [
  250. {
  251. kind: 'column',
  252. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  253. required: true,
  254. defaultValue: 'transaction.duration',
  255. },
  256. ],
  257. outputType: null,
  258. isSortable: true,
  259. multiPlotType: 'area',
  260. },
  261. any: {
  262. parameters: [
  263. {
  264. kind: 'column',
  265. columnTypes: ['string', 'integer', 'number', 'duration', 'date', 'boolean'],
  266. required: true,
  267. defaultValue: 'transaction.duration',
  268. },
  269. ],
  270. outputType: null,
  271. isSortable: true,
  272. },
  273. p50: {
  274. parameters: [
  275. {
  276. kind: 'column',
  277. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  278. defaultValue: 'transaction.duration',
  279. required: false,
  280. },
  281. ],
  282. outputType: null,
  283. isSortable: true,
  284. multiPlotType: 'line',
  285. },
  286. p75: {
  287. parameters: [
  288. {
  289. kind: 'column',
  290. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  291. defaultValue: 'transaction.duration',
  292. required: false,
  293. },
  294. ],
  295. outputType: null,
  296. isSortable: true,
  297. multiPlotType: 'line',
  298. },
  299. p95: {
  300. parameters: [
  301. {
  302. kind: 'column',
  303. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  304. defaultValue: 'transaction.duration',
  305. required: false,
  306. },
  307. ],
  308. outputType: null,
  309. type: [],
  310. isSortable: true,
  311. multiPlotType: 'line',
  312. },
  313. p99: {
  314. parameters: [
  315. {
  316. kind: 'column',
  317. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  318. defaultValue: 'transaction.duration',
  319. required: false,
  320. },
  321. ],
  322. outputType: null,
  323. isSortable: true,
  324. multiPlotType: 'line',
  325. },
  326. p100: {
  327. parameters: [
  328. {
  329. kind: 'column',
  330. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  331. defaultValue: 'transaction.duration',
  332. required: false,
  333. },
  334. ],
  335. outputType: null,
  336. isSortable: true,
  337. multiPlotType: 'line',
  338. },
  339. percentile: {
  340. parameters: [
  341. {
  342. kind: 'column',
  343. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  344. defaultValue: 'transaction.duration',
  345. required: true,
  346. },
  347. {
  348. kind: 'value',
  349. dataType: 'number',
  350. defaultValue: '0.5',
  351. required: true,
  352. },
  353. ],
  354. outputType: null,
  355. isSortable: true,
  356. multiPlotType: 'line',
  357. },
  358. avg: {
  359. parameters: [
  360. {
  361. kind: 'column',
  362. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  363. defaultValue: 'transaction.duration',
  364. required: true,
  365. },
  366. ],
  367. outputType: null,
  368. isSortable: true,
  369. multiPlotType: 'line',
  370. },
  371. apdex: {
  372. parameters: [
  373. {
  374. kind: 'value',
  375. dataType: 'number',
  376. defaultValue: '300',
  377. required: true,
  378. },
  379. ],
  380. outputType: 'number',
  381. isSortable: true,
  382. multiPlotType: 'line',
  383. },
  384. user_misery: {
  385. parameters: [
  386. {
  387. kind: 'value',
  388. dataType: 'number',
  389. defaultValue: '300',
  390. required: true,
  391. },
  392. ],
  393. outputType: 'number',
  394. isSortable: true,
  395. multiPlotType: 'line',
  396. },
  397. failure_rate: {
  398. parameters: [],
  399. outputType: 'percentage',
  400. isSortable: true,
  401. multiPlotType: 'line',
  402. },
  403. last_seen: {
  404. parameters: [],
  405. outputType: 'date',
  406. isSortable: true,
  407. },
  408. } as const;
  409. // TPM and TPS are aliases that are only used in Performance
  410. export const ALIASES = {
  411. tpm: 'epm',
  412. tps: 'eps',
  413. };
  414. assert(AGGREGATIONS as Readonly<{[key in keyof typeof AGGREGATIONS]: Aggregation}>);
  415. export type AggregationKey = keyof typeof AGGREGATIONS | keyof typeof ALIASES | '';
  416. export type AggregationOutputType = Extract<
  417. ColumnType,
  418. 'number' | 'integer' | 'date' | 'duration' | 'percentage' | 'string'
  419. >;
  420. export type PlotType = 'bar' | 'line' | 'area';
  421. type DefaultValueInputs = {
  422. parameter: AggregateParameter;
  423. };
  424. export type Aggregation = {
  425. /**
  426. * Can this function be used in a sort result
  427. */
  428. isSortable: boolean;
  429. /**
  430. * The output type. Null means to inherit from the field.
  431. */
  432. outputType: AggregationOutputType | null;
  433. /**
  434. * List of parameters for the function.
  435. */
  436. parameters: Readonly<AggregateParameter[]>;
  437. getFieldOverrides?: (
  438. data: DefaultValueInputs
  439. ) => Partial<Omit<AggregateParameter, 'kind'>>;
  440. /**
  441. * How this function should be plotted when shown in a multiseries result (top5)
  442. * Optional because some functions cannot be plotted (strings/dates)
  443. */
  444. multiPlotType?: PlotType;
  445. };
  446. enum FieldKey {
  447. CULPRIT = 'culprit',
  448. DEVICE_ARCH = 'device.arch',
  449. DEVICE_BATTERY_LEVEL = 'device.battery_level',
  450. DEVICE_BRAND = 'device.brand',
  451. DEVICE_CHARGING = 'device.charging',
  452. DEVICE_LOCALE = 'device.locale',
  453. DEVICE_NAME = 'device.name',
  454. DEVICE_ONLINE = 'device.online',
  455. DEVICE_ORIENTATION = 'device.orientation',
  456. DEVICE_SIMULATOR = 'device.simulator',
  457. DEVICE_UUID = 'device.uuid',
  458. DIST = 'dist',
  459. ENVIRONMENT = 'environment',
  460. ERROR_HANDLED = 'error.handled',
  461. ERROR_UNHANDLED = 'error.unhandled',
  462. ERROR_MECHANISM = 'error.mechanism',
  463. ERROR_TYPE = 'error.type',
  464. ERROR_VALUE = 'error.value',
  465. EVENT_TYPE = 'event.type',
  466. GEO_CITY = 'geo.city',
  467. GEO_COUNTRY_CODE = 'geo.country_code',
  468. GEO_REGION = 'geo.region',
  469. HTTP_METHOD = 'http.method',
  470. HTTP_REFERER = 'http.referer',
  471. HTTP_URL = 'http.url',
  472. ID = 'id',
  473. ISSUE = 'issue',
  474. LOCATION = 'location',
  475. MESSAGE = 'message',
  476. OS_BUILD = 'os.build',
  477. OS_KERNEL_VERSION = 'os.kernel_version',
  478. PLATFORM_NAME = 'platform.name',
  479. PROJECT = 'project',
  480. RELEASE = 'release',
  481. SDK_NAME = 'sdk.name',
  482. SDK_VERSION = 'sdk.version',
  483. STACK_ABS_PATH = 'stack.abs_path',
  484. STACK_COLNO = 'stack.colno',
  485. STACK_FILENAME = 'stack.filename',
  486. STACK_FUNCTION = 'stack.function',
  487. STACK_IN_APP = 'stack.in_app',
  488. STACK_LINENO = 'stack.lineno',
  489. STACK_MODULE = 'stack.module',
  490. STACK_PACKAGE = 'stack.package',
  491. STACK_STACK_LEVEL = 'stack.stack_level',
  492. TIMESTAMP = 'timestamp',
  493. TIMESTAMP_TO_HOUR = 'timestamp.to_hour',
  494. TIMESTAMP_TO_DAY = 'timestamp.to_day',
  495. TITLE = 'title',
  496. TRACE = 'trace',
  497. TRACE_PARENT_SPAN = 'trace.parent_span',
  498. TRACE_SPAN = 'trace.span',
  499. TRANSACTION = 'transaction',
  500. TRANSACTION_DURATION = 'transaction.duration',
  501. TRANSACTION_OP = 'transaction.op',
  502. TRANSACTION_STATUS = 'transaction.status',
  503. USER_EMAIL = 'user.email',
  504. USER_ID = 'user.id',
  505. USER_IP = 'user.ip',
  506. USER_USERNAME = 'user.username',
  507. USER_DISPLAY = 'user.display',
  508. }
  509. /**
  510. * Refer to src/sentry/snuba/events.py, search for Columns
  511. */
  512. export const FIELDS: Readonly<Record<FieldKey, ColumnType>> = {
  513. [FieldKey.ID]: 'string',
  514. // issue.id and project.id are omitted on purpose.
  515. // Customers should use `issue` and `project` instead.
  516. [FieldKey.TIMESTAMP]: 'date',
  517. // time is omitted on purpose.
  518. // Customers should use `timestamp` or `timestamp.to_hour`.
  519. [FieldKey.TIMESTAMP_TO_HOUR]: 'date',
  520. [FieldKey.TIMESTAMP_TO_DAY]: 'date',
  521. [FieldKey.CULPRIT]: 'string',
  522. [FieldKey.LOCATION]: 'string',
  523. [FieldKey.MESSAGE]: 'string',
  524. [FieldKey.PLATFORM_NAME]: 'string',
  525. [FieldKey.ENVIRONMENT]: 'string',
  526. [FieldKey.RELEASE]: 'string',
  527. [FieldKey.DIST]: 'string',
  528. [FieldKey.TITLE]: 'string',
  529. [FieldKey.EVENT_TYPE]: 'string',
  530. // tags.key and tags.value are omitted on purpose as well.
  531. [FieldKey.TRANSACTION]: 'string',
  532. [FieldKey.USER_ID]: 'string',
  533. [FieldKey.USER_EMAIL]: 'string',
  534. [FieldKey.USER_USERNAME]: 'string',
  535. [FieldKey.USER_IP]: 'string',
  536. [FieldKey.SDK_NAME]: 'string',
  537. [FieldKey.SDK_VERSION]: 'string',
  538. [FieldKey.HTTP_METHOD]: 'string',
  539. [FieldKey.HTTP_REFERER]: 'string',
  540. [FieldKey.HTTP_URL]: 'string',
  541. [FieldKey.OS_BUILD]: 'string',
  542. [FieldKey.OS_KERNEL_VERSION]: 'string',
  543. [FieldKey.DEVICE_NAME]: 'string',
  544. [FieldKey.DEVICE_BRAND]: 'string',
  545. [FieldKey.DEVICE_LOCALE]: 'string',
  546. [FieldKey.DEVICE_UUID]: 'string',
  547. [FieldKey.DEVICE_ARCH]: 'string',
  548. [FieldKey.DEVICE_BATTERY_LEVEL]: 'number',
  549. [FieldKey.DEVICE_ORIENTATION]: 'string',
  550. [FieldKey.DEVICE_SIMULATOR]: 'boolean',
  551. [FieldKey.DEVICE_ONLINE]: 'boolean',
  552. [FieldKey.DEVICE_CHARGING]: 'boolean',
  553. [FieldKey.GEO_COUNTRY_CODE]: 'string',
  554. [FieldKey.GEO_REGION]: 'string',
  555. [FieldKey.GEO_CITY]: 'string',
  556. [FieldKey.ERROR_TYPE]: 'string',
  557. [FieldKey.ERROR_VALUE]: 'string',
  558. [FieldKey.ERROR_MECHANISM]: 'string',
  559. [FieldKey.ERROR_HANDLED]: 'boolean',
  560. [FieldKey.ERROR_UNHANDLED]: 'boolean',
  561. [FieldKey.STACK_ABS_PATH]: 'string',
  562. [FieldKey.STACK_FILENAME]: 'string',
  563. [FieldKey.STACK_PACKAGE]: 'string',
  564. [FieldKey.STACK_MODULE]: 'string',
  565. [FieldKey.STACK_FUNCTION]: 'string',
  566. [FieldKey.STACK_IN_APP]: 'boolean',
  567. [FieldKey.STACK_COLNO]: 'number',
  568. [FieldKey.STACK_LINENO]: 'number',
  569. [FieldKey.STACK_STACK_LEVEL]: 'number',
  570. // contexts.key and contexts.value omitted on purpose.
  571. // Transaction event fields.
  572. [FieldKey.TRANSACTION_DURATION]: 'duration',
  573. [FieldKey.TRANSACTION_OP]: 'string',
  574. [FieldKey.TRANSACTION_STATUS]: 'string',
  575. [FieldKey.TRACE]: 'string',
  576. [FieldKey.TRACE_SPAN]: 'string',
  577. [FieldKey.TRACE_PARENT_SPAN]: 'string',
  578. // Field alises defined in src/sentry/api/event_search.py
  579. [FieldKey.PROJECT]: 'string',
  580. [FieldKey.ISSUE]: 'string',
  581. [FieldKey.USER_DISPLAY]: 'string',
  582. };
  583. export const DEPRECATED_FIELDS: string[] = [FieldKey.CULPRIT];
  584. export type FieldTag = {
  585. key: FieldKey;
  586. name: FieldKey;
  587. };
  588. export const FIELD_TAGS = Object.freeze(
  589. Object.fromEntries(Object.keys(FIELDS).map(item => [item, {key: item, name: item}]))
  590. );
  591. export const SEMVER_TAGS = {
  592. 'release.version': {
  593. key: 'release.version',
  594. name: 'release.version',
  595. },
  596. 'release.build': {
  597. key: 'release.build',
  598. name: 'release.build',
  599. },
  600. 'release.package': {
  601. key: 'release.package',
  602. name: 'release.package',
  603. },
  604. 'release.stage': {
  605. key: 'release.stage',
  606. name: 'release.stage',
  607. predefined: true,
  608. values: RELEASE_ADOPTION_STAGES,
  609. },
  610. };
  611. /**
  612. * Some tag keys should never be formatted as `tag[...]`
  613. * when used as a filter because they are predefined.
  614. */
  615. const EXCLUDED_TAG_KEYS = new Set(['release']);
  616. export function formatTagKey(key: string): string {
  617. // Some tags may be normalized from context, but not all of them are.
  618. // This supports a user making a custom tag with the same name as one
  619. // that comes from context as all of these are also tags.
  620. if (key in FIELD_TAGS && !EXCLUDED_TAG_KEYS.has(key)) {
  621. return `tags[${key}]`;
  622. }
  623. return key;
  624. }
  625. // Allows for a less strict field key definition in cases we are returning custom strings as fields
  626. export type LooseFieldKey = FieldKey | string | '';
  627. export enum WebVital {
  628. FP = 'measurements.fp',
  629. FCP = 'measurements.fcp',
  630. LCP = 'measurements.lcp',
  631. FID = 'measurements.fid',
  632. CLS = 'measurements.cls',
  633. TTFB = 'measurements.ttfb',
  634. RequestTime = 'measurements.ttfb.requesttime',
  635. }
  636. export enum MobileVital {
  637. AppStartCold = 'measurements.app_start_cold',
  638. AppStartWarm = 'measurements.app_start_warm',
  639. FramesTotal = 'measurements.frames_total',
  640. FramesSlow = 'measurements.frames_slow',
  641. FramesFrozen = 'measurements.frames_frozen',
  642. FramesSlowRate = 'measurements.frames_slow_rate',
  643. FramesFrozenRate = 'measurements.frames_frozen_rate',
  644. StallCount = 'measurements.stall_count',
  645. StallTotalTime = 'measurements.stall_total_time',
  646. StallLongestTime = 'measurements.stall_longest_time',
  647. StallPercentage = 'measurements.stall_percentage',
  648. }
  649. const MEASUREMENTS: Readonly<Record<WebVital | MobileVital, ColumnType>> = {
  650. [WebVital.FP]: 'duration',
  651. [WebVital.FCP]: 'duration',
  652. [WebVital.LCP]: 'duration',
  653. [WebVital.FID]: 'duration',
  654. [WebVital.CLS]: 'number',
  655. [WebVital.TTFB]: 'duration',
  656. [WebVital.RequestTime]: 'duration',
  657. [MobileVital.AppStartCold]: 'duration',
  658. [MobileVital.AppStartWarm]: 'duration',
  659. [MobileVital.FramesTotal]: 'integer',
  660. [MobileVital.FramesSlow]: 'integer',
  661. [MobileVital.FramesFrozen]: 'integer',
  662. [MobileVital.FramesSlowRate]: 'percentage',
  663. [MobileVital.FramesFrozenRate]: 'percentage',
  664. [MobileVital.StallCount]: 'integer',
  665. [MobileVital.StallTotalTime]: 'duration',
  666. [MobileVital.StallLongestTime]: 'duration',
  667. [MobileVital.StallPercentage]: 'percentage',
  668. };
  669. export function isSpanOperationBreakdownField(field: string) {
  670. return field.startsWith('spans.');
  671. }
  672. export const SPAN_OP_RELATIVE_BREAKDOWN_FIELD = 'span_ops_breakdown.relative';
  673. export function isRelativeSpanOperationBreakdownField(field: string) {
  674. return field === SPAN_OP_RELATIVE_BREAKDOWN_FIELD;
  675. }
  676. export const SPAN_OP_BREAKDOWN_FIELDS = [
  677. 'spans.http',
  678. 'spans.db',
  679. 'spans.browser',
  680. 'spans.resource',
  681. ];
  682. // This list contains fields/functions that are available with performance-view feature.
  683. export const TRACING_FIELDS = [
  684. 'avg',
  685. 'sum',
  686. 'transaction.duration',
  687. 'transaction.op',
  688. 'transaction.status',
  689. 'p50',
  690. 'p75',
  691. 'p95',
  692. 'p99',
  693. 'p100',
  694. 'percentile',
  695. 'failure_rate',
  696. 'apdex',
  697. 'count_miserable',
  698. 'user_misery',
  699. 'eps',
  700. 'epm',
  701. 'team_key_transaction',
  702. ...Object.keys(MEASUREMENTS),
  703. ...SPAN_OP_BREAKDOWN_FIELDS,
  704. SPAN_OP_RELATIVE_BREAKDOWN_FIELD,
  705. ];
  706. export const MEASUREMENT_PATTERN = /^measurements\.([a-zA-Z0-9-_.]+)$/;
  707. export const SPAN_OP_BREAKDOWN_PATTERN = /^spans\.([a-zA-Z0-9-_.]+)$/;
  708. export function isMeasurement(field: string): boolean {
  709. const results = field.match(MEASUREMENT_PATTERN);
  710. return !!results;
  711. }
  712. export function measurementType(field: string) {
  713. if (MEASUREMENTS.hasOwnProperty(field)) {
  714. return MEASUREMENTS[field];
  715. }
  716. return 'number';
  717. }
  718. export function getMeasurementSlug(field: string): string | null {
  719. const results = field.match(MEASUREMENT_PATTERN);
  720. if (results && results.length >= 2) {
  721. return results[1];
  722. }
  723. return null;
  724. }
  725. const AGGREGATE_PATTERN = /^(\w+)\((.*)?\)$/;
  726. // Identical to AGGREGATE_PATTERN, but without the $ for newline, or ^ for start of line
  727. const AGGREGATE_BASE = /(\w+)\((.*)?\)/g;
  728. export function getAggregateArg(field: string): string | null {
  729. // only returns the first argument if field is an aggregate
  730. const result = parseFunction(field);
  731. if (result && result.arguments.length > 0) {
  732. return result.arguments[0];
  733. }
  734. return null;
  735. }
  736. export function parseFunction(field: string): ParsedFunction | null {
  737. const results = field.match(AGGREGATE_PATTERN);
  738. if (results && results.length === 3) {
  739. return {
  740. name: results[1],
  741. arguments: parseArguments(results[1], results[2]),
  742. };
  743. }
  744. return null;
  745. }
  746. export function parseArguments(functionText: string, columnText: string): string[] {
  747. // Some functions take a quoted string for their arguments that may contain commas
  748. // This function attempts to be identical with the similarly named parse_arguments
  749. // found in src/sentry/search/events/fields.py
  750. if (
  751. (functionText !== 'to_other' && functionText !== 'count_if') ||
  752. columnText.length === 0
  753. ) {
  754. return columnText ? columnText.split(',').map(result => result.trim()) : [];
  755. }
  756. const args: string[] = [];
  757. let quoted = false;
  758. let escaped = false;
  759. let i: number = 0;
  760. let j: number = 0;
  761. while (j < columnText.length) {
  762. if (i === j && columnText[j] === '"') {
  763. // when we see a quote at the beginning of
  764. // an argument, then this is a quoted string
  765. quoted = true;
  766. } else if (i === j && columnText[j] === ' ') {
  767. // argument has leading spaces, skip over them
  768. i += 1;
  769. } else if (quoted && !escaped && columnText[j] === '\\') {
  770. // when we see a slash inside a quoted string,
  771. // the next character is an escape character
  772. escaped = true;
  773. } else if (quoted && !escaped && columnText[j] === '"') {
  774. // when we see a non-escaped quote while inside
  775. // of a quoted string, we should end it
  776. quoted = false;
  777. } else if (quoted && escaped) {
  778. // when we are inside a quoted string and have
  779. // begun an escape character, we should end it
  780. escaped = false;
  781. } else if (quoted && columnText[j] === ',') {
  782. // when we are inside a quoted string and see
  783. // a comma, it should not be considered an
  784. // argument separator
  785. } else if (columnText[j] === ',') {
  786. // when we see a comma outside of a quoted string
  787. // it is an argument separator
  788. args.push(columnText.substring(i, j).trim());
  789. i = j + 1;
  790. }
  791. j += 1;
  792. }
  793. if (i !== j) {
  794. // add in the last argument if any
  795. args.push(columnText.substring(i).trim());
  796. }
  797. return args;
  798. }
  799. // `|` is an invalid field character, so it is used to determine whether a field is an equation or not
  800. const EQUATION_PREFIX = 'equation|';
  801. const EQUATION_ALIAS_PATTERN = /^equation\[(\d+)\]$/;
  802. export const CALCULATED_FIELD_PREFIX = 'calculated|';
  803. export function isEquation(field: string): boolean {
  804. return field.startsWith(EQUATION_PREFIX);
  805. }
  806. export function isEquationAlias(field: string): boolean {
  807. return EQUATION_ALIAS_PATTERN.test(field);
  808. }
  809. export function maybeEquationAlias(field: string): boolean {
  810. return field.includes(EQUATION_PREFIX);
  811. }
  812. export function stripEquationPrefix(field: string): string {
  813. return field.replace(EQUATION_PREFIX, '');
  814. }
  815. export function getEquationAliasIndex(field: string): number {
  816. const results = field.match(EQUATION_ALIAS_PATTERN);
  817. if (results && results.length === 2) {
  818. return parseInt(results[1], 10);
  819. }
  820. return -1;
  821. }
  822. export function getEquation(field: string): string {
  823. return field.slice(EQUATION_PREFIX.length);
  824. }
  825. export function isAggregateEquation(field: string): boolean {
  826. const results = field.match(AGGREGATE_BASE);
  827. return isEquation(field) && results !== null && results.length > 0;
  828. }
  829. export function isLegalEquationColumn(column: Column): boolean {
  830. // Any isn't allowed in arithmetic
  831. if (column.kind === 'function' && column.function[0] === 'any') {
  832. return false;
  833. }
  834. const columnType = getColumnType(column);
  835. return columnType === 'number' || columnType === 'integer' || columnType === 'duration';
  836. }
  837. export function generateAggregateFields(
  838. organization: Organization,
  839. eventFields: readonly Field[] | Field[],
  840. excludeFields: readonly string[] = []
  841. ): Field[] {
  842. const functions = Object.keys(AGGREGATIONS);
  843. const fields = Object.values(eventFields).map(field => field.field);
  844. functions.forEach(func => {
  845. const parameters = AGGREGATIONS[func].parameters.map(param => {
  846. const overrides = AGGREGATIONS[func].getFieldOverrides;
  847. if (typeof overrides === 'undefined') {
  848. return param;
  849. }
  850. return {
  851. ...param,
  852. ...overrides({parameter: param, organization}),
  853. };
  854. });
  855. if (parameters.every(param => typeof param.defaultValue !== 'undefined')) {
  856. const newField = `${func}(${parameters
  857. .map(param => param.defaultValue)
  858. .join(',')})`;
  859. if (fields.indexOf(newField) === -1 && excludeFields.indexOf(newField) === -1) {
  860. fields.push(newField);
  861. }
  862. }
  863. });
  864. return fields.map(field => ({field})) as Field[];
  865. }
  866. export function isDerivedMetric(field: string): boolean {
  867. return field.startsWith(CALCULATED_FIELD_PREFIX);
  868. }
  869. export function stripDerivedMetricsPrefix(field: string): string {
  870. return field.replace(CALCULATED_FIELD_PREFIX, '');
  871. }
  872. export function explodeFieldString(field: string, alias?: string): Column {
  873. if (isEquation(field)) {
  874. return {kind: 'equation', field: getEquation(field), alias};
  875. }
  876. if (isDerivedMetric(field)) {
  877. return {kind: 'calculatedField', field: stripDerivedMetricsPrefix(field)};
  878. }
  879. const results = parseFunction(field);
  880. if (results) {
  881. return {
  882. kind: 'function',
  883. function: [
  884. results.name as AggregationKey,
  885. results.arguments[0] ?? '',
  886. results.arguments[1] as AggregationRefinement,
  887. results.arguments[2] as AggregationRefinement,
  888. ],
  889. alias,
  890. };
  891. }
  892. return {kind: 'field', field, alias};
  893. }
  894. export function generateFieldAsString(value: QueryFieldValue): string {
  895. if (value.kind === 'field') {
  896. return value.field;
  897. }
  898. if (value.kind === 'calculatedField') {
  899. return `${CALCULATED_FIELD_PREFIX}${value.field}`;
  900. }
  901. if (value.kind === 'equation') {
  902. return `${EQUATION_PREFIX}${value.field}`;
  903. }
  904. const aggregation = value.function[0];
  905. const parameters = value.function.slice(1).filter(i => i);
  906. return `${aggregation}(${parameters.join(',')})`;
  907. }
  908. export function explodeField(field: Field): Column {
  909. return explodeFieldString(field.field, field.alias);
  910. }
  911. /**
  912. * Get the alias that the API results will have for a given aggregate function name
  913. */
  914. export function getAggregateAlias(field: string): string {
  915. const result = parseFunction(field);
  916. if (!result) {
  917. return field;
  918. }
  919. let alias = result.name;
  920. if (result.arguments.length > 0) {
  921. alias += '_' + result.arguments.join('_');
  922. }
  923. return alias.replace(/[^\w]/g, '_').replace(/^_+/g, '').replace(/_+$/, '');
  924. }
  925. /**
  926. * Check if a field name looks like an aggregate function or known aggregate alias.
  927. */
  928. export function isAggregateField(field: string): boolean {
  929. return parseFunction(field) !== null;
  930. }
  931. export function isAggregateFieldOrEquation(field: string): boolean {
  932. return isAggregateField(field) || isAggregateEquation(field) || isNumericMetrics(field);
  933. }
  934. /**
  935. * Temporary hardcoded hack to enable testing derived metrics.
  936. * Can be removed after we get rid of getAggregateFields
  937. */
  938. export function isNumericMetrics(field: string): boolean {
  939. return [
  940. 'session.crash_free_rate',
  941. 'session.crashed',
  942. 'session.errored_preaggregated',
  943. 'session.errored_set',
  944. 'session.init',
  945. ].includes(field);
  946. }
  947. export function getAggregateFields(fields: string[]): string[] {
  948. return fields.filter(
  949. field =>
  950. isAggregateField(field) || isAggregateEquation(field) || isNumericMetrics(field)
  951. );
  952. }
  953. export function getColumnsAndAggregates(fields: string[]): {
  954. aggregates: string[];
  955. columns: string[];
  956. } {
  957. const aggregates = getAggregateFields(fields);
  958. const columns = fields.filter(field => !!!aggregates.includes(field));
  959. return {columns, aggregates};
  960. }
  961. export function getColumnsAndAggregatesAsStrings(fields: QueryFieldValue[]): {
  962. aggregates: string[];
  963. columns: string[];
  964. fieldAliases: string[];
  965. } {
  966. // TODO(dam): distinguish between metrics, derived metrics and tags
  967. const aggregateFields: string[] = [];
  968. const nonAggregateFields: string[] = [];
  969. const fieldAliases: string[] = [];
  970. for (const field of fields) {
  971. const fieldString = generateFieldAsString(field);
  972. if (field.kind === 'function' || field.kind === 'calculatedField') {
  973. aggregateFields.push(fieldString);
  974. } else if (field.kind === 'equation') {
  975. if (isAggregateEquation(fieldString)) {
  976. aggregateFields.push(fieldString);
  977. } else {
  978. nonAggregateFields.push(fieldString);
  979. }
  980. } else {
  981. nonAggregateFields.push(fieldString);
  982. }
  983. fieldAliases.push(field.alias ?? '');
  984. }
  985. return {aggregates: aggregateFields, columns: nonAggregateFields, fieldAliases};
  986. }
  987. /**
  988. * Convert a function string into type it will output.
  989. * This is useful when you need to format values in tooltips,
  990. * or in series markers.
  991. */
  992. export function aggregateOutputType(field: string): AggregationOutputType {
  993. const result = parseFunction(field);
  994. if (!result) {
  995. return 'number';
  996. }
  997. const outputType = aggregateFunctionOutputType(result.name, result.arguments[0]);
  998. if (outputType === null) {
  999. return 'number';
  1000. }
  1001. return outputType;
  1002. }
  1003. /**
  1004. * Converts a function string and its first argument into its output type.
  1005. * - If the function has a fixed output type, that will be the result.
  1006. * - If the function does not define an output type, the output type will be equal to
  1007. * the type of its first argument.
  1008. * - If the function has an optional first argument, and it was not defined, make sure
  1009. * to use the default argument as the first argument.
  1010. * - If the type could not be determined, return null.
  1011. */
  1012. export function aggregateFunctionOutputType(
  1013. funcName: string,
  1014. firstArg: string | undefined
  1015. ): AggregationOutputType | null {
  1016. const aggregate = AGGREGATIONS[ALIASES[funcName] || funcName];
  1017. // Attempt to use the function's outputType.
  1018. if (aggregate?.outputType) {
  1019. return aggregate.outputType;
  1020. }
  1021. // If the first argument is undefined and it is not required,
  1022. // then we attempt to get the default value.
  1023. if (!firstArg && aggregate?.parameters?.[0]) {
  1024. if (aggregate.parameters[0].required === false) {
  1025. firstArg = aggregate.parameters[0].defaultValue;
  1026. }
  1027. }
  1028. if (firstArg && METRIC_TO_COLUMN_TYPE.hasOwnProperty(firstArg)) {
  1029. return METRIC_TO_COLUMN_TYPE[firstArg];
  1030. }
  1031. // If the function is an inherit type it will have a field as
  1032. // the first parameter and we can use that to get the type.
  1033. if (firstArg && FIELDS.hasOwnProperty(firstArg)) {
  1034. return FIELDS[firstArg];
  1035. }
  1036. if (firstArg && isMeasurement(firstArg)) {
  1037. return measurementType(firstArg);
  1038. }
  1039. if (firstArg && isSpanOperationBreakdownField(firstArg)) {
  1040. return 'duration';
  1041. }
  1042. return null;
  1043. }
  1044. /**
  1045. * Get the multi-series chart type for an aggregate function.
  1046. */
  1047. export function aggregateMultiPlotType(field: string): PlotType {
  1048. if (isEquation(field)) {
  1049. return 'line';
  1050. }
  1051. const result = parseFunction(field);
  1052. // Handle invalid data.
  1053. if (!result) {
  1054. return 'area';
  1055. }
  1056. if (!AGGREGATIONS.hasOwnProperty(result.name)) {
  1057. return 'area';
  1058. }
  1059. return AGGREGATIONS[result.name].multiPlotType;
  1060. }
  1061. function validateForNumericAggregate(
  1062. validColumnTypes: ColumnType[]
  1063. ): ValidateColumnValueFunction {
  1064. return function ({name, dataType}: {dataType: ColumnType; name: string}): boolean {
  1065. // these built-in columns cannot be applied to numeric aggregates such as percentile(...)
  1066. if (
  1067. [
  1068. FieldKey.DEVICE_BATTERY_LEVEL,
  1069. FieldKey.STACK_COLNO,
  1070. FieldKey.STACK_LINENO,
  1071. FieldKey.STACK_STACK_LEVEL,
  1072. ].includes(name as FieldKey)
  1073. ) {
  1074. return false;
  1075. }
  1076. return validColumnTypes.includes(dataType);
  1077. };
  1078. }
  1079. function validateDenyListColumns(
  1080. validColumnTypes: ColumnType[],
  1081. deniedColumns: string[]
  1082. ): ValidateColumnValueFunction {
  1083. return function ({name, dataType}: {dataType: ColumnType; name: string}): boolean {
  1084. return validColumnTypes.includes(dataType) && !deniedColumns.includes(name);
  1085. };
  1086. }
  1087. function validateAllowedColumns(validColumns: string[]): ValidateColumnValueFunction {
  1088. return function ({name}): boolean {
  1089. return validColumns.includes(name);
  1090. };
  1091. }
  1092. const alignedTypes: ColumnValueType[] = ['number', 'duration', 'integer', 'percentage'];
  1093. export function fieldAlignment(
  1094. columnName: string,
  1095. columnType?: undefined | ColumnValueType,
  1096. metadata?: Record<string, ColumnValueType>
  1097. ): Alignments {
  1098. let align: Alignments = 'left';
  1099. if (columnType) {
  1100. align = alignedTypes.includes(columnType) ? 'right' : 'left';
  1101. }
  1102. if (columnType === undefined || columnType === 'never') {
  1103. // fallback to align the column based on the table metadata
  1104. const maybeType = metadata ? metadata[getAggregateAlias(columnName)] : undefined;
  1105. if (maybeType !== undefined && alignedTypes.includes(maybeType)) {
  1106. align = 'right';
  1107. }
  1108. }
  1109. return align;
  1110. }
  1111. /**
  1112. * Match on types that are legal to show on a timeseries chart.
  1113. */
  1114. export function isLegalYAxisType(match: ColumnType | MetricsType) {
  1115. return ['number', 'integer', 'duration', 'percentage'].includes(match);
  1116. }
  1117. export function getSpanOperationName(field: string): string | null {
  1118. const results = field.match(SPAN_OP_BREAKDOWN_PATTERN);
  1119. if (results && results.length >= 2) {
  1120. return results[1];
  1121. }
  1122. return null;
  1123. }
  1124. export function getColumnType(column: Column): ColumnType {
  1125. if (column.kind === 'function') {
  1126. const outputType = aggregateFunctionOutputType(
  1127. column.function[0],
  1128. column.function[1]
  1129. );
  1130. if (outputType !== null) {
  1131. return outputType;
  1132. }
  1133. } else if (column.kind === 'field') {
  1134. if (FIELDS.hasOwnProperty(column.field)) {
  1135. return FIELDS[column.field];
  1136. }
  1137. if (isMeasurement(column.field)) {
  1138. return measurementType(column.field);
  1139. }
  1140. if (isSpanOperationBreakdownField(column.field)) {
  1141. return 'duration';
  1142. }
  1143. }
  1144. return 'string';
  1145. }
  1146. export function hasDuplicate(columnList: Column[], column: Column): boolean {
  1147. if (column.kind !== 'function' && column.kind !== 'field') {
  1148. return false;
  1149. }
  1150. return columnList.filter(newColumn => isEqual(newColumn, column)).length > 1;
  1151. }