fields.tsx 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  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. const results = field.match(MEASUREMENT_PATTERN);
  597. return !!results;
  598. }
  599. export function measurementType(field: string): MeasurementType {
  600. if (MEASUREMENT_FIELDS.hasOwnProperty(field)) {
  601. return MEASUREMENT_FIELDS[field].valueType as MeasurementType;
  602. }
  603. return FieldValueType.NUMBER;
  604. }
  605. export function getMeasurementSlug(field: string): string | null {
  606. const results = field.match(MEASUREMENT_PATTERN);
  607. if (results && results.length >= 2) {
  608. return results[1];
  609. }
  610. return null;
  611. }
  612. const AGGREGATE_PATTERN = /^(\w+)\((.*)?\)$/;
  613. // Identical to AGGREGATE_PATTERN, but without the $ for newline, or ^ for start of line
  614. const AGGREGATE_BASE = /(\w+)\((.*)?\)/g;
  615. export function getAggregateArg(field: string): string | null {
  616. // only returns the first argument if field is an aggregate
  617. const result = parseFunction(field);
  618. if (result && result.arguments.length > 0) {
  619. return result.arguments[0];
  620. }
  621. return null;
  622. }
  623. export function parseFunction(field: string): ParsedFunction | null {
  624. const results = field.match(AGGREGATE_PATTERN);
  625. if (results && results.length === 3) {
  626. return {
  627. name: results[1],
  628. arguments: parseArguments(results[1], results[2]),
  629. };
  630. }
  631. return null;
  632. }
  633. export function parseArguments(functionText: string, columnText: string): string[] {
  634. // Some functions take a quoted string for their arguments that may contain commas
  635. // This function attempts to be identical with the similarly named parse_arguments
  636. // found in src/sentry/search/events/fields.py
  637. if (
  638. (functionText !== 'to_other' &&
  639. functionText !== 'count_if' &&
  640. functionText !== 'spans_histogram') ||
  641. columnText?.length === 0
  642. ) {
  643. return columnText ? columnText.split(',').map(result => result.trim()) : [];
  644. }
  645. const args: string[] = [];
  646. let quoted = false;
  647. let escaped = false;
  648. let i: number = 0;
  649. let j: number = 0;
  650. while (j < columnText.length) {
  651. if (i === j && columnText[j] === '"') {
  652. // when we see a quote at the beginning of
  653. // an argument, then this is a quoted string
  654. quoted = true;
  655. } else if (i === j && columnText[j] === ' ') {
  656. // argument has leading spaces, skip over them
  657. i += 1;
  658. } else if (quoted && !escaped && columnText[j] === '\\') {
  659. // when we see a slash inside a quoted string,
  660. // the next character is an escape character
  661. escaped = true;
  662. } else if (quoted && !escaped && columnText[j] === '"') {
  663. // when we see a non-escaped quote while inside
  664. // of a quoted string, we should end it
  665. quoted = false;
  666. } else if (quoted && escaped) {
  667. // when we are inside a quoted string and have
  668. // begun an escape character, we should end it
  669. escaped = false;
  670. } else if (quoted && columnText[j] === ',') {
  671. // when we are inside a quoted string and see
  672. // a comma, it should not be considered an
  673. // argument separator
  674. } else if (columnText[j] === ',') {
  675. // when we see a comma outside of a quoted string
  676. // it is an argument separator
  677. args.push(columnText.substring(i, j).trim());
  678. i = j + 1;
  679. }
  680. j += 1;
  681. }
  682. if (i !== j) {
  683. // add in the last argument if any
  684. args.push(columnText.substring(i).trim());
  685. }
  686. return args;
  687. }
  688. // `|` is an invalid field character, so it is used to determine whether a field is an equation or not
  689. export const EQUATION_PREFIX = 'equation|';
  690. const EQUATION_ALIAS_PATTERN = /^equation\[(\d+)\]$/;
  691. export const CALCULATED_FIELD_PREFIX = 'calculated|';
  692. export function isEquation(field: string): boolean {
  693. return field.startsWith(EQUATION_PREFIX);
  694. }
  695. export function isEquationAlias(field: string): boolean {
  696. return EQUATION_ALIAS_PATTERN.test(field);
  697. }
  698. export function maybeEquationAlias(field: string): boolean {
  699. return field.includes(EQUATION_PREFIX);
  700. }
  701. export function stripEquationPrefix(field: string): string {
  702. return field.replace(EQUATION_PREFIX, '');
  703. }
  704. export function getEquationAliasIndex(field: string): number {
  705. const results = field.match(EQUATION_ALIAS_PATTERN);
  706. if (results && results.length === 2) {
  707. return parseInt(results[1], 10);
  708. }
  709. return -1;
  710. }
  711. export function getEquation(field: string): string {
  712. return field.slice(EQUATION_PREFIX.length);
  713. }
  714. export function isAggregateEquation(field: string): boolean {
  715. const results = field.match(AGGREGATE_BASE);
  716. return isEquation(field) && results !== null && results.length > 0;
  717. }
  718. export function isLegalEquationColumn(column: Column): boolean {
  719. // Any isn't allowed in arithmetic
  720. if (column.kind === 'function' && column.function[0] === 'any') {
  721. return false;
  722. }
  723. const columnType = getColumnType(column);
  724. return columnType === 'number' || columnType === 'integer' || columnType === 'duration';
  725. }
  726. export function generateAggregateFields(
  727. organization: Organization,
  728. eventFields: readonly Field[] | Field[],
  729. excludeFields: readonly string[] = []
  730. ): Field[] {
  731. const functions = Object.keys(AGGREGATIONS);
  732. const fields = Object.values(eventFields).map(field => field.field);
  733. functions.forEach(func => {
  734. const parameters = AGGREGATIONS[func].parameters.map(param => {
  735. const overrides = AGGREGATIONS[func].getFieldOverrides;
  736. if (typeof overrides === 'undefined') {
  737. return param;
  738. }
  739. return {
  740. ...param,
  741. ...overrides({parameter: param, organization}),
  742. };
  743. });
  744. if (parameters.every(param => typeof param.defaultValue !== 'undefined')) {
  745. const newField = `${func}(${parameters
  746. .map(param => param.defaultValue)
  747. .join(',')})`;
  748. if (fields.indexOf(newField) === -1 && excludeFields.indexOf(newField) === -1) {
  749. fields.push(newField);
  750. }
  751. }
  752. });
  753. return fields.map(field => ({field})) as Field[];
  754. }
  755. export function isDerivedMetric(field: string): boolean {
  756. return field.startsWith(CALCULATED_FIELD_PREFIX);
  757. }
  758. export function stripDerivedMetricsPrefix(field: string): string {
  759. return field.replace(CALCULATED_FIELD_PREFIX, '');
  760. }
  761. export function explodeFieldString(field: string, alias?: string): Column {
  762. if (isEquation(field)) {
  763. return {kind: 'equation', field: getEquation(field), alias};
  764. }
  765. if (isDerivedMetric(field)) {
  766. return {kind: 'calculatedField', field: stripDerivedMetricsPrefix(field), alias};
  767. }
  768. const results = parseFunction(field);
  769. if (results) {
  770. return {
  771. kind: 'function',
  772. function: [
  773. results.name as AggregationKey,
  774. results.arguments[0] ?? '',
  775. results.arguments[1] as AggregationRefinement,
  776. results.arguments[2] as AggregationRefinement,
  777. ],
  778. alias,
  779. };
  780. }
  781. return {kind: 'field', field, alias};
  782. }
  783. export function generateFieldAsString(value: QueryFieldValue): string {
  784. if (value.kind === 'field') {
  785. return value.field;
  786. }
  787. if (value.kind === 'calculatedField') {
  788. return `${CALCULATED_FIELD_PREFIX}${value.field}`;
  789. }
  790. if (value.kind === 'equation') {
  791. return `${EQUATION_PREFIX}${value.field.trim()}`;
  792. }
  793. const aggregation = value.function[0];
  794. const parameters = value.function.slice(1).filter(i => i);
  795. return `${aggregation}(${parameters.join(',')})`;
  796. }
  797. export function explodeField(field: Field): Column {
  798. return explodeFieldString(field.field, field.alias);
  799. }
  800. /**
  801. * Get the alias that the API results will have for a given aggregate function name
  802. */
  803. export function getAggregateAlias(field: string): string {
  804. const result = parseFunction(field);
  805. if (!result) {
  806. return field;
  807. }
  808. let alias = result.name;
  809. if (result.arguments.length > 0) {
  810. alias += '_' + result.arguments.join('_');
  811. }
  812. return alias.replace(/[^\w]/g, '_').replace(/^_+/g, '').replace(/_+$/, '');
  813. }
  814. /**
  815. * Check if a field name looks like an aggregate function or known aggregate alias.
  816. */
  817. export function isAggregateField(field: string): boolean {
  818. return parseFunction(field) !== null;
  819. }
  820. export function isAggregateFieldOrEquation(field: string): boolean {
  821. return isAggregateField(field) || isAggregateEquation(field) || isNumericMetrics(field);
  822. }
  823. /**
  824. * Temporary hardcoded hack to enable testing derived metrics.
  825. * Can be removed after we get rid of getAggregateFields
  826. */
  827. export function isNumericMetrics(field: string): boolean {
  828. return [
  829. 'session.crash_free_rate',
  830. 'session.crashed',
  831. 'session.errored_preaggregated',
  832. 'session.errored_set',
  833. 'session.init',
  834. ].includes(field);
  835. }
  836. export function getAggregateFields(fields: string[]): string[] {
  837. return fields.filter(
  838. field =>
  839. isAggregateField(field) || isAggregateEquation(field) || isNumericMetrics(field)
  840. );
  841. }
  842. export function getColumnsAndAggregates(fields: string[]): {
  843. aggregates: string[];
  844. columns: string[];
  845. } {
  846. const aggregates = getAggregateFields(fields);
  847. const columns = fields.filter(field => !aggregates.includes(field));
  848. return {columns, aggregates};
  849. }
  850. export function getColumnsAndAggregatesAsStrings(fields: QueryFieldValue[]): {
  851. aggregates: string[];
  852. columns: string[];
  853. fieldAliases: string[];
  854. } {
  855. // TODO(dam): distinguish between metrics, derived metrics and tags
  856. const aggregateFields: string[] = [];
  857. const nonAggregateFields: string[] = [];
  858. const fieldAliases: string[] = [];
  859. for (const field of fields) {
  860. const fieldString = generateFieldAsString(field);
  861. if (field.kind === 'function' || field.kind === 'calculatedField') {
  862. aggregateFields.push(fieldString);
  863. } else if (field.kind === 'equation') {
  864. if (isAggregateEquation(fieldString)) {
  865. aggregateFields.push(fieldString);
  866. } else {
  867. nonAggregateFields.push(fieldString);
  868. }
  869. } else {
  870. nonAggregateFields.push(fieldString);
  871. }
  872. fieldAliases.push(field.alias ?? '');
  873. }
  874. return {aggregates: aggregateFields, columns: nonAggregateFields, fieldAliases};
  875. }
  876. /**
  877. * Convert a function string into type it will output.
  878. * This is useful when you need to format values in tooltips,
  879. * or in series markers.
  880. */
  881. export function aggregateOutputType(field: string | undefined): AggregationOutputType {
  882. if (!field) {
  883. return 'number';
  884. }
  885. const result = parseFunction(field);
  886. if (!result) {
  887. return 'number';
  888. }
  889. const outputType = aggregateFunctionOutputType(result.name, result.arguments[0]);
  890. if (outputType === null) {
  891. return 'number';
  892. }
  893. return outputType;
  894. }
  895. /**
  896. * Converts a function string and its first argument into its output type.
  897. * - If the function has a fixed output type, that will be the result.
  898. * - If the function does not define an output type, the output type will be equal to
  899. * the type of its first argument.
  900. * - If the function has an optional first argument, and it was not defined, make sure
  901. * to use the default argument as the first argument.
  902. * - If the type could not be determined, return null.
  903. */
  904. export function aggregateFunctionOutputType(
  905. funcName: string,
  906. firstArg: string | undefined
  907. ): AggregationOutputType | null {
  908. const aggregate =
  909. AGGREGATIONS[ALIASES[funcName] || funcName] ?? SESSIONS_OPERATIONS[funcName];
  910. // Attempt to use the function's outputType.
  911. if (aggregate?.outputType) {
  912. return aggregate.outputType;
  913. }
  914. // If the first argument is undefined and it is not required,
  915. // then we attempt to get the default value.
  916. if (!firstArg && aggregate?.parameters?.[0]) {
  917. if (aggregate.parameters[0].required === false) {
  918. firstArg = aggregate.parameters[0].defaultValue;
  919. }
  920. }
  921. if (firstArg && SESSIONS_FIELDS.hasOwnProperty(firstArg)) {
  922. return SESSIONS_FIELDS[firstArg].type as AggregationOutputType;
  923. }
  924. // If the function is an inherit type it will have a field as
  925. // the first parameter and we can use that to get the type.
  926. const fieldDef = getFieldDefinition(firstArg ?? '');
  927. if (fieldDef !== null) {
  928. return fieldDef.valueType as AggregationOutputType;
  929. }
  930. if (firstArg && isMeasurement(firstArg)) {
  931. return measurementType(firstArg);
  932. }
  933. if (firstArg && isSpanOperationBreakdownField(firstArg)) {
  934. return 'duration';
  935. }
  936. return null;
  937. }
  938. export function errorsAndTransactionsAggregateFunctionOutputType(
  939. funcName: string,
  940. firstArg: string | undefined
  941. ): AggregationOutputType | null {
  942. const aggregate = AGGREGATIONS[ALIASES[funcName] || funcName];
  943. // Attempt to use the function's outputType.
  944. if (aggregate?.outputType) {
  945. return aggregate.outputType;
  946. }
  947. // If the first argument is undefined and it is not required,
  948. // then we attempt to get the default value.
  949. if (!firstArg && aggregate?.parameters?.[0]) {
  950. if (aggregate.parameters[0].required === false) {
  951. firstArg = aggregate.parameters[0].defaultValue;
  952. }
  953. }
  954. // If the function is an inherit type it will have a field as
  955. // the first parameter and we can use that to get the type.
  956. const fieldDef = getFieldDefinition(firstArg ?? '');
  957. if (fieldDef !== null) {
  958. return fieldDef.valueType as AggregationOutputType;
  959. }
  960. if (firstArg && isMeasurement(firstArg)) {
  961. return measurementType(firstArg);
  962. }
  963. if (firstArg && isSpanOperationBreakdownField(firstArg)) {
  964. return 'duration';
  965. }
  966. return null;
  967. }
  968. export function sessionsAggregateFunctionOutputType(
  969. funcName: string,
  970. firstArg: string | undefined
  971. ): AggregationOutputType | null {
  972. const aggregate = SESSIONS_OPERATIONS[funcName];
  973. // Attempt to use the function's outputType.
  974. if (aggregate?.outputType) {
  975. return aggregate.outputType;
  976. }
  977. // If the first argument is undefined and it is not required,
  978. // then we attempt to get the default value.
  979. if (!firstArg && aggregate?.parameters?.[0]) {
  980. if (aggregate.parameters[0].required === false) {
  981. firstArg = aggregate.parameters[0].defaultValue;
  982. }
  983. }
  984. if (firstArg && SESSIONS_FIELDS.hasOwnProperty(firstArg)) {
  985. return SESSIONS_FIELDS[firstArg].type as AggregationOutputType;
  986. }
  987. return null;
  988. }
  989. /**
  990. * Get the multi-series chart type for an aggregate function.
  991. */
  992. export function aggregateMultiPlotType(field: string): PlotType {
  993. if (isEquation(field)) {
  994. return 'line';
  995. }
  996. const result = parseFunction(field);
  997. // Handle invalid data.
  998. if (!result) {
  999. return 'area';
  1000. }
  1001. if (!AGGREGATIONS.hasOwnProperty(result.name)) {
  1002. return 'area';
  1003. }
  1004. return AGGREGATIONS[result.name].multiPlotType;
  1005. }
  1006. function validateForNumericAggregate(
  1007. validColumnTypes: ColumnType[]
  1008. ): ValidateColumnValueFunction {
  1009. return function ({name, dataType}: {dataType: ColumnType; name: string}): boolean {
  1010. // these built-in columns cannot be applied to numeric aggregates such as percentile(...)
  1011. if (
  1012. [
  1013. FieldKey.DEVICE_BATTERY_LEVEL,
  1014. FieldKey.STACK_COLNO,
  1015. FieldKey.STACK_LINENO,
  1016. FieldKey.STACK_STACK_LEVEL,
  1017. ].includes(name as FieldKey)
  1018. ) {
  1019. return false;
  1020. }
  1021. return validColumnTypes.includes(dataType);
  1022. };
  1023. }
  1024. function validateDenyListColumns(
  1025. validColumnTypes: ColumnType[],
  1026. deniedColumns: string[]
  1027. ): ValidateColumnValueFunction {
  1028. return function ({name, dataType}: {dataType: ColumnType; name: string}): boolean {
  1029. return validColumnTypes.includes(dataType) && !deniedColumns.includes(name);
  1030. };
  1031. }
  1032. function validateAllowedColumns(validColumns: string[]): ValidateColumnValueFunction {
  1033. return function ({name}): boolean {
  1034. return validColumns.includes(name);
  1035. };
  1036. }
  1037. const alignedTypes: ColumnValueType[] = ['number', 'duration', 'integer', 'percentage'];
  1038. export function fieldAlignment(
  1039. columnName: string,
  1040. columnType?: undefined | ColumnValueType,
  1041. metadata?: Record<string, ColumnValueType>
  1042. ): Alignments {
  1043. let align: Alignments = 'left';
  1044. if (columnType) {
  1045. align = alignedTypes.includes(columnType) ? 'right' : 'left';
  1046. }
  1047. if (columnType === undefined || columnType === 'never') {
  1048. // fallback to align the column based on the table metadata
  1049. const maybeType = metadata ? metadata[getAggregateAlias(columnName)] : undefined;
  1050. if (maybeType !== undefined && alignedTypes.includes(maybeType)) {
  1051. align = 'right';
  1052. }
  1053. }
  1054. return align;
  1055. }
  1056. /**
  1057. * Match on types that are legal to show on a timeseries chart.
  1058. */
  1059. export function isLegalYAxisType(match: ColumnType | MetricsType) {
  1060. return ['number', 'integer', 'duration', 'percentage'].includes(match);
  1061. }
  1062. export function getSpanOperationName(field: string): string | null {
  1063. const results = field.match(SPAN_OP_BREAKDOWN_PATTERN);
  1064. if (results && results.length >= 2) {
  1065. return results[1];
  1066. }
  1067. return null;
  1068. }
  1069. export function getColumnType(column: Column): ColumnType {
  1070. if (column.kind === 'function') {
  1071. const outputType = aggregateFunctionOutputType(
  1072. column.function[0],
  1073. column.function[1]
  1074. );
  1075. if (outputType !== null) {
  1076. return outputType;
  1077. }
  1078. } else if (column.kind === 'field') {
  1079. const fieldDef = getFieldDefinition(column.field);
  1080. if (fieldDef !== null) {
  1081. return fieldDef.valueType as ColumnType;
  1082. }
  1083. if (isMeasurement(column.field)) {
  1084. return measurementType(column.field);
  1085. }
  1086. if (isSpanOperationBreakdownField(column.field)) {
  1087. return 'duration';
  1088. }
  1089. }
  1090. return 'string';
  1091. }
  1092. export function hasDuplicate(columnList: Column[], column: Column): boolean {
  1093. if (column.kind !== 'function' && column.kind !== 'field') {
  1094. return false;
  1095. }
  1096. return columnList.filter(newColumn => isEqual(newColumn, column)).length > 1;
  1097. }