fields.tsx 33 KB

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