fields.tsx 33 KB

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