fields.tsx 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  1. import isEqual from 'lodash/isEqual';
  2. import type {FilterKeySection} from 'sentry/components/searchQueryBuilder/types';
  3. import {RELEASE_ADOPTION_STAGES} from 'sentry/constants';
  4. import type {SelectValue} from 'sentry/types/core';
  5. import type {MetricType} from 'sentry/types/metrics';
  6. import type {Organization} from 'sentry/types/organization';
  7. import {assert} from 'sentry/types/utils';
  8. import {isMRIField} from 'sentry/utils/metrics/mri';
  9. import {
  10. SESSIONS_FIELDS,
  11. SESSIONS_OPERATIONS,
  12. } from 'sentry/views/dashboards/widgetBuilder/releaseWidget/fields';
  13. import {STARFISH_FIELDS} from 'sentry/views/insights/common/utils/constants';
  14. import {STARFISH_AGGREGATION_FIELDS} from 'sentry/views/insights/constants';
  15. import {
  16. AGGREGATION_FIELDS,
  17. AggregationKey,
  18. DISCOVER_FIELDS,
  19. FieldKey,
  20. FieldValueType,
  21. getFieldDefinition,
  22. MEASUREMENT_FIELDS,
  23. MobileVital,
  24. SpanOpBreakdown,
  25. WebVital,
  26. } from '../fields';
  27. import {CONDITIONS_ARGUMENTS, DiscoverDatasets, WEB_VITALS_QUALITY} from './types';
  28. export type Sort = {
  29. field: string;
  30. kind: 'asc' | 'desc';
  31. };
  32. // Contains the URL field value & the related table column width.
  33. // Can be parsed into a Column using explodeField()
  34. export type Field = {
  35. field: string;
  36. // When an alias is defined for a field, it will be shown as a column name in the table visualization.
  37. alias?: string;
  38. width?: number;
  39. };
  40. // 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.
  41. export type ColumnType = `${Exclude<FieldValueType, FieldValueType.NEVER>}`;
  42. export type ColumnValueType = ColumnType | `${FieldValueType.NEVER}`;
  43. export type ParsedFunction = {
  44. arguments: string[];
  45. name: string;
  46. };
  47. type ValidateColumnValueFunction = (data: {
  48. dataType: ColumnType;
  49. name: string;
  50. }) => boolean;
  51. export type ValidateColumnTypes =
  52. | ColumnType[]
  53. | MetricType[]
  54. | ValidateColumnValueFunction;
  55. export type AggregateParameter =
  56. | {
  57. columnTypes: Readonly<ValidateColumnTypes>;
  58. kind: 'column';
  59. required: boolean;
  60. defaultValue?: string;
  61. }
  62. | {
  63. dataType: ColumnType;
  64. kind: 'value';
  65. required: boolean;
  66. defaultValue?: string;
  67. placeholder?: string;
  68. }
  69. | {
  70. dataType: string;
  71. kind: 'dropdown';
  72. options: SelectValue<string>[];
  73. required: boolean;
  74. defaultValue?: string;
  75. placeholder?: string;
  76. };
  77. export type AggregationRefinement = string | undefined;
  78. // The parsed result of a Field.
  79. // Functions and Fields are handled as subtypes to enable other
  80. // code to work more simply.
  81. // This type can be converted into a Field.field using generateFieldAsString()
  82. // When an alias is defined for a field, it will be shown as a column name in the table visualization.
  83. export type QueryFieldValue =
  84. | {
  85. field: string;
  86. kind: 'field';
  87. alias?: string;
  88. }
  89. | {
  90. field: string;
  91. kind: 'calculatedField';
  92. alias?: string;
  93. }
  94. | {
  95. field: string;
  96. kind: 'equation';
  97. alias?: string;
  98. }
  99. | {
  100. function: [
  101. AggregationKeyWithAlias,
  102. string,
  103. AggregationRefinement,
  104. AggregationRefinement,
  105. ];
  106. kind: 'function';
  107. alias?: string;
  108. };
  109. // Column is just an alias of a Query value
  110. export type Column = QueryFieldValue;
  111. export type Alignments = 'left' | 'right';
  112. export type CountUnit = 'count';
  113. export type PercentageUnit = 'percentage';
  114. export type PercentChangeUnit = 'percent_change';
  115. export enum CurrencyUnit {
  116. USD = 'usd',
  117. }
  118. export enum DurationUnit {
  119. NANOSECOND = 'nanosecond',
  120. MICROSECOND = 'microsecond',
  121. MILLISECOND = 'millisecond',
  122. SECOND = 'second',
  123. MINUTE = 'minute',
  124. HOUR = 'hour',
  125. DAY = 'day',
  126. WEEK = 'week',
  127. MONTH = 'month',
  128. YEAR = 'year',
  129. }
  130. export enum SizeUnit {
  131. BIT = 'bit',
  132. BYTE = 'byte',
  133. KIBIBYTE = 'kibibyte',
  134. KILOBYTE = 'kilobyte',
  135. MEBIBYTE = 'mebibyte',
  136. MEGABYTE = 'megabyte',
  137. GIBIBYTE = 'gibibyte',
  138. GIGABYTE = 'gigabyte',
  139. TEBIBYTE = 'tebibyte',
  140. TERABYTE = 'terabyte',
  141. PEBIBYTE = 'pebibyte',
  142. PETABYTE = 'petabyte',
  143. EXBIBYTE = 'exbibyte',
  144. EXABYTE = 'exabyte',
  145. }
  146. export enum RateUnit {
  147. PER_SECOND = '1/second',
  148. PER_MINUTE = '1/minute',
  149. PER_HOUR = '1/hour',
  150. }
  151. // Rates normalized to /second unit
  152. export const RATE_UNIT_MULTIPLIERS = {
  153. [RateUnit.PER_SECOND]: 1,
  154. [RateUnit.PER_MINUTE]: 1 / 60,
  155. [RateUnit.PER_HOUR]: 1 / (60 * 60),
  156. };
  157. export const RATE_UNIT_LABELS = {
  158. [RateUnit.PER_SECOND]: '/s',
  159. [RateUnit.PER_MINUTE]: '/min',
  160. [RateUnit.PER_HOUR]: '/hr',
  161. };
  162. export const RATE_UNIT_TITLE = {
  163. [RateUnit.PER_SECOND]: 'Per Second',
  164. [RateUnit.PER_MINUTE]: 'Per Minute',
  165. [RateUnit.PER_HOUR]: 'Per Hour',
  166. };
  167. const getDocsAndOutputType = (key: AggregationKey) => {
  168. return {
  169. documentation: AGGREGATION_FIELDS[key].desc,
  170. outputType: AGGREGATION_FIELDS[key].valueType as AggregationOutputType,
  171. };
  172. };
  173. // Refer to src/sentry/search/events/fields.py
  174. // Try to keep functions logically sorted, ie. all the count functions are grouped together
  175. // When dealing with errors or transactions datasets, use getAggregations() instead because
  176. // there are dataset-specific overrides
  177. export const AGGREGATIONS = {
  178. [AggregationKey.COUNT]: {
  179. ...getDocsAndOutputType(AggregationKey.COUNT),
  180. parameters: [],
  181. isSortable: true,
  182. multiPlotType: 'area',
  183. },
  184. [AggregationKey.COUNT_UNIQUE]: {
  185. ...getDocsAndOutputType(AggregationKey.COUNT_UNIQUE),
  186. parameters: [
  187. {
  188. kind: 'column',
  189. columnTypes: ['string', 'integer', 'number', 'duration', 'date', 'boolean'],
  190. defaultValue: 'user',
  191. required: true,
  192. },
  193. ],
  194. isSortable: true,
  195. multiPlotType: 'area',
  196. },
  197. [AggregationKey.COUNT_MISERABLE]: {
  198. ...getDocsAndOutputType(AggregationKey.COUNT_MISERABLE),
  199. getFieldOverrides({parameter}: DefaultValueInputs) {
  200. if (parameter.kind === 'column') {
  201. return {defaultValue: 'user'};
  202. }
  203. return {
  204. defaultValue: parameter.defaultValue,
  205. };
  206. },
  207. parameters: [
  208. {
  209. kind: 'column',
  210. columnTypes: validateAllowedColumns(['user']),
  211. defaultValue: 'user',
  212. required: true,
  213. },
  214. {
  215. kind: 'value',
  216. dataType: 'number',
  217. defaultValue: '300',
  218. required: true,
  219. },
  220. ],
  221. isSortable: true,
  222. multiPlotType: 'area',
  223. },
  224. [AggregationKey.COUNT_IF]: {
  225. ...getDocsAndOutputType(AggregationKey.COUNT_IF),
  226. parameters: [
  227. {
  228. kind: 'column',
  229. columnTypes: validateDenyListColumns(
  230. ['string', 'duration', 'number'],
  231. ['id', 'issue', 'user.display']
  232. ),
  233. defaultValue: 'transaction.duration',
  234. required: true,
  235. },
  236. {
  237. kind: 'dropdown',
  238. options: CONDITIONS_ARGUMENTS,
  239. dataType: 'string',
  240. defaultValue: CONDITIONS_ARGUMENTS[0].value,
  241. required: true,
  242. },
  243. {
  244. kind: 'value',
  245. dataType: 'string',
  246. defaultValue: '300',
  247. required: true,
  248. },
  249. ],
  250. isSortable: true,
  251. multiPlotType: 'area',
  252. },
  253. [AggregationKey.COUNT_WEB_VITALS]: {
  254. ...getDocsAndOutputType(AggregationKey.COUNT_WEB_VITALS),
  255. parameters: [
  256. {
  257. kind: 'column',
  258. columnTypes: validateAllowedColumns([
  259. WebVital.LCP,
  260. WebVital.FP,
  261. WebVital.FCP,
  262. WebVital.FID,
  263. WebVital.CLS,
  264. ]),
  265. defaultValue: WebVital.LCP,
  266. required: true,
  267. },
  268. {
  269. kind: 'dropdown',
  270. options: WEB_VITALS_QUALITY,
  271. dataType: 'string',
  272. defaultValue: WEB_VITALS_QUALITY[0].value,
  273. required: true,
  274. },
  275. ],
  276. isSortable: true,
  277. multiPlotType: 'area',
  278. },
  279. [AggregationKey.EPS]: {
  280. ...getDocsAndOutputType(AggregationKey.EPS),
  281. parameters: [],
  282. isSortable: true,
  283. multiPlotType: 'area',
  284. },
  285. [AggregationKey.EPM]: {
  286. ...getDocsAndOutputType(AggregationKey.EPM),
  287. parameters: [],
  288. isSortable: true,
  289. multiPlotType: 'area',
  290. },
  291. [AggregationKey.FAILURE_COUNT]: {
  292. ...getDocsAndOutputType(AggregationKey.FAILURE_COUNT),
  293. parameters: [],
  294. isSortable: true,
  295. multiPlotType: 'line',
  296. },
  297. [AggregationKey.MIN]: {
  298. ...getDocsAndOutputType(AggregationKey.MIN),
  299. parameters: [
  300. {
  301. kind: 'column',
  302. columnTypes: validateForNumericAggregate([
  303. 'integer',
  304. 'number',
  305. 'duration',
  306. 'date',
  307. 'percentage',
  308. ]),
  309. defaultValue: 'transaction.duration',
  310. required: true,
  311. },
  312. ],
  313. isSortable: true,
  314. multiPlotType: 'line',
  315. },
  316. [AggregationKey.MAX]: {
  317. ...getDocsAndOutputType(AggregationKey.MAX),
  318. parameters: [
  319. {
  320. kind: 'column',
  321. columnTypes: validateForNumericAggregate([
  322. 'integer',
  323. 'number',
  324. 'duration',
  325. 'date',
  326. 'percentage',
  327. ]),
  328. defaultValue: 'transaction.duration',
  329. required: true,
  330. },
  331. ],
  332. isSortable: true,
  333. multiPlotType: 'line',
  334. },
  335. [AggregationKey.SUM]: {
  336. ...getDocsAndOutputType(AggregationKey.SUM),
  337. parameters: [
  338. {
  339. kind: 'column',
  340. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  341. required: true,
  342. defaultValue: 'transaction.duration',
  343. },
  344. ],
  345. isSortable: true,
  346. multiPlotType: 'area',
  347. },
  348. [AggregationKey.ANY]: {
  349. ...getDocsAndOutputType(AggregationKey.ANY),
  350. parameters: [
  351. {
  352. kind: 'column',
  353. columnTypes: ['string', 'integer', 'number', 'duration', 'date', 'boolean'],
  354. required: true,
  355. defaultValue: 'transaction.duration',
  356. },
  357. ],
  358. isSortable: true,
  359. },
  360. [AggregationKey.P50]: {
  361. ...getDocsAndOutputType(AggregationKey.P50),
  362. parameters: [
  363. {
  364. kind: 'column',
  365. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  366. defaultValue: 'transaction.duration',
  367. required: false,
  368. },
  369. ],
  370. isSortable: true,
  371. multiPlotType: 'line',
  372. },
  373. [AggregationKey.P75]: {
  374. ...getDocsAndOutputType(AggregationKey.P75),
  375. parameters: [
  376. {
  377. kind: 'column',
  378. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  379. defaultValue: 'transaction.duration',
  380. required: false,
  381. },
  382. ],
  383. isSortable: true,
  384. multiPlotType: 'line',
  385. },
  386. [AggregationKey.P90]: {
  387. ...getDocsAndOutputType(AggregationKey.P90),
  388. parameters: [
  389. {
  390. kind: 'column',
  391. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  392. defaultValue: 'transaction.duration',
  393. required: false,
  394. },
  395. ],
  396. isSortable: true,
  397. multiPlotType: 'line',
  398. },
  399. [AggregationKey.P95]: {
  400. ...getDocsAndOutputType(AggregationKey.P95),
  401. parameters: [
  402. {
  403. kind: 'column',
  404. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  405. defaultValue: 'transaction.duration',
  406. required: false,
  407. },
  408. ],
  409. type: [],
  410. isSortable: true,
  411. multiPlotType: 'line',
  412. },
  413. [AggregationKey.P99]: {
  414. ...getDocsAndOutputType(AggregationKey.P99),
  415. parameters: [
  416. {
  417. kind: 'column',
  418. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  419. defaultValue: 'transaction.duration',
  420. required: false,
  421. },
  422. ],
  423. isSortable: true,
  424. multiPlotType: 'line',
  425. },
  426. [AggregationKey.P100]: {
  427. ...getDocsAndOutputType(AggregationKey.P100),
  428. parameters: [
  429. {
  430. kind: 'column',
  431. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  432. defaultValue: 'transaction.duration',
  433. required: false,
  434. },
  435. ],
  436. isSortable: true,
  437. multiPlotType: 'line',
  438. },
  439. [AggregationKey.PERCENTILE]: {
  440. ...getDocsAndOutputType(AggregationKey.PERCENTILE),
  441. parameters: [
  442. {
  443. kind: 'column',
  444. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  445. defaultValue: 'transaction.duration',
  446. required: true,
  447. },
  448. {
  449. kind: 'value',
  450. dataType: 'number',
  451. defaultValue: '0.5',
  452. required: true,
  453. },
  454. ],
  455. isSortable: true,
  456. multiPlotType: 'line',
  457. },
  458. [AggregationKey.AVG]: {
  459. ...getDocsAndOutputType(AggregationKey.AVG),
  460. parameters: [
  461. {
  462. kind: 'column',
  463. columnTypes: validateForNumericAggregate(['duration', 'number', 'percentage']),
  464. defaultValue: 'transaction.duration',
  465. required: true,
  466. },
  467. ],
  468. isSortable: true,
  469. multiPlotType: 'line',
  470. },
  471. [AggregationKey.APDEX]: {
  472. ...getDocsAndOutputType(AggregationKey.APDEX),
  473. parameters: [
  474. {
  475. kind: 'value',
  476. dataType: 'number',
  477. defaultValue: '300',
  478. required: true,
  479. },
  480. ],
  481. isSortable: true,
  482. multiPlotType: 'line',
  483. },
  484. [AggregationKey.USER_MISERY]: {
  485. ...getDocsAndOutputType(AggregationKey.USER_MISERY),
  486. parameters: [
  487. {
  488. kind: 'value',
  489. dataType: 'number',
  490. defaultValue: '300',
  491. required: true,
  492. },
  493. ],
  494. isSortable: true,
  495. multiPlotType: 'line',
  496. },
  497. [AggregationKey.FAILURE_RATE]: {
  498. ...getDocsAndOutputType(AggregationKey.FAILURE_RATE),
  499. parameters: [],
  500. isSortable: true,
  501. multiPlotType: 'line',
  502. },
  503. [AggregationKey.LAST_SEEN]: {
  504. ...getDocsAndOutputType(AggregationKey.LAST_SEEN),
  505. parameters: [],
  506. isSortable: true,
  507. },
  508. } as const;
  509. // TPM and TPS are aliases that are only used in Performance
  510. export const ALIASES = {
  511. tpm: AggregationKey.EPM,
  512. tps: AggregationKey.EPS,
  513. };
  514. assert(AGGREGATIONS as Readonly<{[key in AggregationKey]: Aggregation}>);
  515. export type AggregationKeyWithAlias = `${AggregationKey}` | keyof typeof ALIASES | '';
  516. export type AggregationOutputType = Extract<
  517. ColumnType,
  518. 'number' | 'integer' | 'date' | 'duration' | 'percentage' | 'string' | 'size' | 'rate'
  519. >;
  520. export type PlotType = 'bar' | 'line' | 'area';
  521. type DefaultValueInputs = {
  522. parameter: AggregateParameter;
  523. };
  524. export type Aggregation = {
  525. /**
  526. * Can this function be used in a sort result
  527. */
  528. isSortable: boolean;
  529. /**
  530. * The output type. Null means to inherit from the field.
  531. */
  532. outputType: AggregationOutputType | null;
  533. /**
  534. * List of parameters for the function.
  535. */
  536. parameters: Readonly<AggregateParameter[]>;
  537. getFieldOverrides?: (
  538. data: DefaultValueInputs
  539. ) => Partial<Omit<AggregateParameter, 'kind'>>;
  540. /**
  541. * How this function should be plotted when shown in a multiseries result (top5)
  542. * Optional because some functions cannot be plotted (strings/dates)
  543. */
  544. multiPlotType?: PlotType;
  545. };
  546. export const DEPRECATED_FIELDS: string[] = [FieldKey.CULPRIT];
  547. export type FieldTag = {
  548. key: FieldKey;
  549. name: FieldKey;
  550. };
  551. export const FIELD_TAGS = Object.freeze(
  552. Object.fromEntries(DISCOVER_FIELDS.map(item => [item, {key: item, name: item}]))
  553. );
  554. export const SEMVER_TAGS = {
  555. [FieldKey.RELEASE_VERSION]: {
  556. key: FieldKey.RELEASE_VERSION,
  557. name: FieldKey.RELEASE_VERSION,
  558. },
  559. [FieldKey.RELEASE_BUILD]: {
  560. key: FieldKey.RELEASE_BUILD,
  561. name: FieldKey.RELEASE_BUILD,
  562. },
  563. [FieldKey.RELEASE_PACKAGE]: {
  564. key: FieldKey.RELEASE_PACKAGE,
  565. name: FieldKey.RELEASE_PACKAGE,
  566. },
  567. [FieldKey.RELEASE_STAGE]: {
  568. key: FieldKey.RELEASE_STAGE,
  569. name: FieldKey.RELEASE_STAGE,
  570. predefined: true,
  571. values: RELEASE_ADOPTION_STAGES,
  572. },
  573. };
  574. /**
  575. * Some tag keys should never be formatted as `tag[...]`
  576. * when used as a filter because they are predefined.
  577. */
  578. const EXCLUDED_TAG_KEYS = new Set(['release', 'user', 'device.class']);
  579. export function formatTagKey(key: string): string {
  580. // Some tags may be normalized from context, but not all of them are.
  581. // This supports a user making a custom tag with the same name as one
  582. // that comes from context as all of these are also tags.
  583. if (key in FIELD_TAGS && !EXCLUDED_TAG_KEYS.has(key)) {
  584. return `tags[${key}]`;
  585. }
  586. return key;
  587. }
  588. // Allows for a less strict field key definition in cases we are returning custom strings as fields
  589. export type LooseFieldKey = FieldKey | string | '';
  590. export type MeasurementType =
  591. | FieldValueType.DURATION
  592. | FieldValueType.NUMBER
  593. | FieldValueType.INTEGER
  594. | FieldValueType.PERCENTAGE;
  595. export function isSpanOperationBreakdownField(field: string) {
  596. return field.startsWith('spans.');
  597. }
  598. // Returns the AGGREGATIONS object with the expected defaults for the given dataset
  599. export function getAggregations(dataset: DiscoverDatasets) {
  600. if (dataset === DiscoverDatasets.DISCOVER) {
  601. return AGGREGATIONS;
  602. }
  603. return {
  604. ...AGGREGATIONS,
  605. [AggregationKey.COUNT_IF]: {
  606. ...AGGREGATIONS[AggregationKey.COUNT_IF],
  607. parameters: [
  608. {
  609. kind: 'column',
  610. columnTypes: validateDenyListColumns(
  611. ['string', 'duration', 'number'],
  612. ['id', 'issue', 'user.display']
  613. ),
  614. defaultValue:
  615. dataset === DiscoverDatasets.TRANSACTIONS
  616. ? 'transaction.duration'
  617. : 'event.type',
  618. required: true,
  619. },
  620. {
  621. kind: 'dropdown',
  622. options: CONDITIONS_ARGUMENTS,
  623. dataType: 'string',
  624. defaultValue: CONDITIONS_ARGUMENTS[0].value,
  625. required: true,
  626. },
  627. {
  628. kind: 'value',
  629. dataType: 'string',
  630. defaultValue: dataset === DiscoverDatasets.TRANSACTIONS ? '300' : 'error',
  631. required: true,
  632. },
  633. ],
  634. },
  635. } as const;
  636. }
  637. export const SPAN_OP_RELATIVE_BREAKDOWN_FIELD = 'span_ops_breakdown.relative';
  638. export function isRelativeSpanOperationBreakdownField(field: string) {
  639. return field === SPAN_OP_RELATIVE_BREAKDOWN_FIELD;
  640. }
  641. export const SPAN_OP_BREAKDOWN_FIELDS = Object.values(SpanOpBreakdown);
  642. // This list contains fields/functions that are available with performance-view feature.
  643. export const TRACING_FIELDS = [
  644. AggregationKey.AVG,
  645. AggregationKey.SUM,
  646. FieldKey.TRANSACTION_DURATION,
  647. FieldKey.TRANSACTION_OP,
  648. FieldKey.TRANSACTION_STATUS,
  649. FieldKey.ISSUE,
  650. AggregationKey.P50,
  651. AggregationKey.P75,
  652. AggregationKey.P95,
  653. AggregationKey.P99,
  654. AggregationKey.P100,
  655. AggregationKey.PERCENTILE,
  656. AggregationKey.FAILURE_RATE,
  657. AggregationKey.APDEX,
  658. AggregationKey.COUNT_MISERABLE,
  659. AggregationKey.USER_MISERY,
  660. AggregationKey.EPS,
  661. AggregationKey.EPM,
  662. 'team_key_transaction',
  663. ...Object.keys(MEASUREMENT_FIELDS),
  664. ...SPAN_OP_BREAKDOWN_FIELDS,
  665. SPAN_OP_RELATIVE_BREAKDOWN_FIELD,
  666. ];
  667. export const TRANSACTION_ONLY_FIELDS: (FieldKey | SpanOpBreakdown)[] = [
  668. FieldKey.TRANSACTION_DURATION,
  669. FieldKey.TRANSACTION_OP,
  670. FieldKey.TRANSACTION_STATUS,
  671. FieldKey.PROFILE_ID,
  672. SpanOpBreakdown.SPANS_BROWSER,
  673. SpanOpBreakdown.SPANS_DB,
  674. SpanOpBreakdown.SPANS_HTTP,
  675. SpanOpBreakdown.SPANS_RESOURCE,
  676. SpanOpBreakdown.SPANS_UI,
  677. ];
  678. export const ERROR_FIELDS = DISCOVER_FIELDS.filter(
  679. f => !TRANSACTION_ONLY_FIELDS.includes(f)
  680. );
  681. export const ERROR_ONLY_FIELDS: (FieldKey | SpanOpBreakdown)[] = [
  682. FieldKey.LOCATION,
  683. FieldKey.EVENT_TYPE,
  684. FieldKey.ERROR_TYPE,
  685. FieldKey.ERROR_VALUE,
  686. FieldKey.ERROR_MECHANISM,
  687. FieldKey.ERROR_HANDLED,
  688. FieldKey.ERROR_UNHANDLED,
  689. FieldKey.ERROR_RECEIVED,
  690. FieldKey.ERROR_MAIN_THREAD,
  691. FieldKey.LEVEL,
  692. FieldKey.STACK_ABS_PATH,
  693. FieldKey.STACK_FILENAME,
  694. FieldKey.STACK_PACKAGE,
  695. FieldKey.STACK_MODULE,
  696. FieldKey.STACK_FUNCTION,
  697. FieldKey.STACK_IN_APP,
  698. FieldKey.STACK_COLNO,
  699. FieldKey.STACK_LINENO,
  700. FieldKey.STACK_STACK_LEVEL,
  701. FieldKey.EVENT_TYPE,
  702. ];
  703. export const TRANSACTION_FIELDS = DISCOVER_FIELDS.filter(
  704. f => !ERROR_ONLY_FIELDS.includes(f)
  705. );
  706. export const ERRORS_AGGREGATION_FUNCTIONS = [
  707. AggregationKey.COUNT,
  708. AggregationKey.COUNT_IF,
  709. AggregationKey.COUNT_UNIQUE,
  710. AggregationKey.EPS,
  711. AggregationKey.EPM,
  712. ];
  713. // This list contains fields/functions that are available with profiling feature.
  714. export const PROFILING_FIELDS: string[] = [FieldKey.PROFILE_ID];
  715. export const MEASUREMENT_PATTERN = /^measurements\.([a-zA-Z0-9-_.]+)$/;
  716. export const SPAN_OP_BREAKDOWN_PATTERN = /^spans\.([a-zA-Z0-9-_.]+)$/;
  717. export function isMeasurement(field: string): boolean {
  718. return MEASUREMENT_PATTERN.test(field);
  719. }
  720. export function measurementType(field: string): MeasurementType {
  721. if (MEASUREMENT_FIELDS.hasOwnProperty(field)) {
  722. return MEASUREMENT_FIELDS[field].valueType as MeasurementType;
  723. }
  724. return FieldValueType.NUMBER;
  725. }
  726. export function getMeasurementSlug(field: string): string | null {
  727. const results = field.match(MEASUREMENT_PATTERN);
  728. if (results && results.length >= 2) {
  729. return results[1];
  730. }
  731. return null;
  732. }
  733. const AGGREGATE_PATTERN = /^(\w+)\((.*)?\)$/;
  734. // Identical to AGGREGATE_PATTERN, but without the $ for newline, or ^ for start of line
  735. const AGGREGATE_BASE = /(\w+)\((.*)?\)/g;
  736. export function getAggregateArg(field: string): string | null {
  737. // only returns the first argument if field is an aggregate
  738. const result = parseFunction(field);
  739. if (result && result.arguments.length > 0) {
  740. return result.arguments[0];
  741. }
  742. return null;
  743. }
  744. export function parseFunction(field: string): ParsedFunction | null {
  745. const results = field.match(AGGREGATE_PATTERN);
  746. if (results && results.length === 3) {
  747. return {
  748. name: results[1],
  749. arguments: parseArguments(results[1], results[2]),
  750. };
  751. }
  752. return null;
  753. }
  754. export function parseArguments(functionText: string, columnText: string): string[] {
  755. // Some functions take a quoted string for their arguments that may contain commas
  756. // This function attempts to be identical with the similarly named parse_arguments
  757. // found in src/sentry/search/events/fields.py
  758. if (
  759. (functionText !== 'to_other' &&
  760. functionText !== 'count_if' &&
  761. functionText !== 'spans_histogram') ||
  762. columnText?.length === 0
  763. ) {
  764. return columnText ? columnText.split(',').map(result => result.trim()) : [];
  765. }
  766. const args: string[] = [];
  767. let quoted = false;
  768. let escaped = false;
  769. let i: number = 0;
  770. let j: number = 0;
  771. while (j < columnText?.length) {
  772. if (i === j && columnText[j] === '"') {
  773. // when we see a quote at the beginning of
  774. // an argument, then this is a quoted string
  775. quoted = true;
  776. } else if (i === j && columnText[j] === ' ') {
  777. // argument has leading spaces, skip over them
  778. i += 1;
  779. } else if (quoted && !escaped && columnText[j] === '\\') {
  780. // when we see a slash inside a quoted string,
  781. // the next character is an escape character
  782. escaped = true;
  783. } else if (quoted && !escaped && columnText[j] === '"') {
  784. // when we see a non-escaped quote while inside
  785. // of a quoted string, we should end it
  786. quoted = false;
  787. } else if (quoted && escaped) {
  788. // when we are inside a quoted string and have
  789. // begun an escape character, we should end it
  790. escaped = false;
  791. } else if (quoted && columnText[j] === ',') {
  792. // when we are inside a quoted string and see
  793. // a comma, it should not be considered an
  794. // argument separator
  795. } else if (columnText[j] === ',') {
  796. // when we see a comma outside of a quoted string
  797. // it is an argument separator
  798. args.push(columnText.substring(i, j).trim());
  799. i = j + 1;
  800. }
  801. j += 1;
  802. }
  803. if (i !== j) {
  804. // add in the last argument if any
  805. args.push(columnText.substring(i).trim());
  806. }
  807. return args;
  808. }
  809. // `|` is an invalid field character, so it is used to determine whether a field is an equation or not
  810. export const EQUATION_PREFIX = 'equation|';
  811. const EQUATION_ALIAS_PATTERN = /^equation\[(\d+)\]$/;
  812. export const CALCULATED_FIELD_PREFIX = 'calculated|';
  813. export function isEquation(field: string): boolean {
  814. return field.startsWith(EQUATION_PREFIX);
  815. }
  816. export function isEquationAlias(field: string): boolean {
  817. return EQUATION_ALIAS_PATTERN.test(field);
  818. }
  819. export function maybeEquationAlias(field: string): boolean {
  820. return field.includes(EQUATION_PREFIX);
  821. }
  822. export function stripEquationPrefix(field: string): string {
  823. return field.replace(EQUATION_PREFIX, '');
  824. }
  825. export function getEquationAliasIndex(field: string): number {
  826. const results = field.match(EQUATION_ALIAS_PATTERN);
  827. if (results && results.length === 2) {
  828. return parseInt(results[1], 10);
  829. }
  830. return -1;
  831. }
  832. export function getEquation(field: string): string {
  833. return field.slice(EQUATION_PREFIX.length);
  834. }
  835. export function isAggregateEquation(field: string): boolean {
  836. const results = field.match(AGGREGATE_BASE);
  837. return isEquation(field) && results !== null && results.length > 0;
  838. }
  839. export function isLegalEquationColumn(column: Column): boolean {
  840. // Any isn't allowed in arithmetic
  841. if (column.kind === 'function' && column.function[0] === 'any') {
  842. return false;
  843. }
  844. const columnType = getColumnType(column);
  845. return columnType === 'number' || columnType === 'integer' || columnType === 'duration';
  846. }
  847. export function generateAggregateFields(
  848. organization: Organization,
  849. eventFields: readonly Field[] | Field[],
  850. excludeFields: readonly string[] = []
  851. ): Field[] {
  852. const functions = Object.keys(AGGREGATIONS);
  853. const fields = Object.values(eventFields).map(field => field.field);
  854. functions.forEach(func => {
  855. const parameters = AGGREGATIONS[func].parameters.map(param => {
  856. const overrides = AGGREGATIONS[func].getFieldOverrides;
  857. if (typeof overrides === 'undefined') {
  858. return param;
  859. }
  860. return {
  861. ...param,
  862. ...overrides({parameter: param, organization}),
  863. };
  864. });
  865. if (parameters.every(param => typeof param.defaultValue !== 'undefined')) {
  866. const newField = `${func}(${parameters
  867. .map(param => param.defaultValue)
  868. .join(',')})`;
  869. if (!fields.includes(newField) && !excludeFields.includes(newField)) {
  870. fields.push(newField);
  871. }
  872. }
  873. });
  874. return fields.map(field => ({field})) as Field[];
  875. }
  876. export function isDerivedMetric(field: string): boolean {
  877. return field.startsWith(CALCULATED_FIELD_PREFIX);
  878. }
  879. export function stripDerivedMetricsPrefix(field: string): string {
  880. return field.replace(CALCULATED_FIELD_PREFIX, '');
  881. }
  882. export function explodeFieldString(field: string, alias?: string): Column {
  883. if (isEquation(field)) {
  884. return {kind: 'equation', field: getEquation(field), alias};
  885. }
  886. if (isDerivedMetric(field)) {
  887. return {kind: 'calculatedField', field: stripDerivedMetricsPrefix(field), alias};
  888. }
  889. const results = parseFunction(field);
  890. if (results) {
  891. return {
  892. kind: 'function',
  893. function: [
  894. results.name as AggregationKey,
  895. results.arguments[0] ?? '',
  896. results.arguments[1] as AggregationRefinement,
  897. results.arguments[2] as AggregationRefinement,
  898. ],
  899. alias,
  900. };
  901. }
  902. return {kind: 'field', field, alias};
  903. }
  904. export function generateFieldAsString(value: QueryFieldValue): string {
  905. if (value.kind === 'field') {
  906. return value.field;
  907. }
  908. if (value.kind === 'calculatedField') {
  909. return `${CALCULATED_FIELD_PREFIX}${value.field}`;
  910. }
  911. if (value.kind === 'equation') {
  912. return `${EQUATION_PREFIX}${value.field.trim()}`;
  913. }
  914. const aggregation = value.function[0];
  915. const parameters = value.function.slice(1).filter(i => i);
  916. return `${aggregation}(${parameters.join(',')})`;
  917. }
  918. export function explodeField(field: Field): Column {
  919. return explodeFieldString(field.field, field.alias);
  920. }
  921. /**
  922. * Get the alias that the API results will have for a given aggregate function name
  923. */
  924. export function getAggregateAlias(field: string): string {
  925. const result = parseFunction(field);
  926. if (!result) {
  927. return field;
  928. }
  929. let alias = result.name;
  930. if (result.arguments.length > 0) {
  931. alias += '_' + result.arguments.join('_');
  932. }
  933. return alias.replace(/[^\w]/g, '_').replace(/^_+/g, '').replace(/_+$/, '');
  934. }
  935. /**
  936. * Check if a field name looks like an aggregate function or known aggregate alias.
  937. */
  938. export function isAggregateField(field: string): boolean {
  939. return parseFunction(field) !== null;
  940. }
  941. export function isAggregateFieldOrEquation(field: string): boolean {
  942. return isAggregateField(field) || isAggregateEquation(field) || isNumericMetrics(field);
  943. }
  944. /**
  945. * Temporary hardcoded hack to enable testing derived metrics.
  946. * Can be removed after we get rid of getAggregateFields
  947. */
  948. export function isNumericMetrics(field: string): boolean {
  949. return [
  950. 'session.crash_free_rate',
  951. 'session.crashed',
  952. 'session.errored_preaggregated',
  953. 'session.errored_set',
  954. 'session.init',
  955. ].includes(field);
  956. }
  957. export function getAggregateFields(fields: string[]): string[] {
  958. return fields.filter(
  959. field =>
  960. isAggregateField(field) || isAggregateEquation(field) || isNumericMetrics(field)
  961. );
  962. }
  963. export function getColumnsAndAggregates(fields: string[]): {
  964. aggregates: string[];
  965. columns: string[];
  966. } {
  967. const aggregates = getAggregateFields(fields);
  968. const columns = fields.filter(field => !aggregates.includes(field));
  969. return {columns, aggregates};
  970. }
  971. export function getColumnsAndAggregatesAsStrings(fields: QueryFieldValue[]): {
  972. aggregates: string[];
  973. columns: string[];
  974. fieldAliases: string[];
  975. } {
  976. // TODO(dam): distinguish between metrics, derived metrics and tags
  977. const aggregateFields: string[] = [];
  978. const nonAggregateFields: string[] = [];
  979. const fieldAliases: string[] = [];
  980. for (const field of fields) {
  981. const fieldString = generateFieldAsString(field);
  982. if (field.kind === 'function' || field.kind === 'calculatedField') {
  983. aggregateFields.push(fieldString);
  984. } else if (field.kind === 'equation') {
  985. if (isAggregateEquation(fieldString)) {
  986. aggregateFields.push(fieldString);
  987. } else {
  988. nonAggregateFields.push(fieldString);
  989. }
  990. } else {
  991. nonAggregateFields.push(fieldString);
  992. }
  993. fieldAliases.push(field.alias ?? '');
  994. }
  995. return {aggregates: aggregateFields, columns: nonAggregateFields, fieldAliases};
  996. }
  997. /**
  998. * Convert a function string into type it will output.
  999. * This is useful when you need to format values in tooltips,
  1000. * or in series markers.
  1001. */
  1002. export function aggregateOutputType(field: string | undefined): AggregationOutputType {
  1003. if (!field) {
  1004. return 'number';
  1005. }
  1006. const result = parseFunction(field);
  1007. if (!result) {
  1008. return 'number';
  1009. }
  1010. const outputType = aggregateFunctionOutputType(result.name, result.arguments[0]);
  1011. if (outputType === null) {
  1012. return 'number';
  1013. }
  1014. return outputType;
  1015. }
  1016. /**
  1017. * Converts a function string and its first argument into its output type.
  1018. * - If the function has a fixed output type, that will be the result.
  1019. * - If the function does not define an output type, the output type will be equal to
  1020. * the type of its first argument.
  1021. * - If the function has an optional first argument, and it was not defined, make sure
  1022. * to use the default argument as the first argument.
  1023. * - If the type could not be determined, return null.
  1024. */
  1025. export function aggregateFunctionOutputType(
  1026. funcName: string,
  1027. firstArg: string | undefined
  1028. ): AggregationOutputType | null {
  1029. const aggregate =
  1030. AGGREGATIONS[ALIASES[funcName] || funcName] ?? SESSIONS_OPERATIONS[funcName];
  1031. // Attempt to use the function's outputType.
  1032. if (aggregate?.outputType) {
  1033. return aggregate.outputType;
  1034. }
  1035. // If the first argument is undefined and it is not required,
  1036. // then we attempt to get the default value.
  1037. if (!firstArg && aggregate?.parameters?.[0]) {
  1038. if (aggregate.parameters[0].required === false) {
  1039. firstArg = aggregate.parameters[0].defaultValue;
  1040. }
  1041. }
  1042. if (firstArg && SESSIONS_FIELDS.hasOwnProperty(firstArg)) {
  1043. return SESSIONS_FIELDS[firstArg].type as AggregationOutputType;
  1044. }
  1045. if (firstArg && STARFISH_FIELDS[firstArg]) {
  1046. return STARFISH_FIELDS[firstArg].outputType;
  1047. }
  1048. if (STARFISH_AGGREGATION_FIELDS[funcName]) {
  1049. return STARFISH_AGGREGATION_FIELDS[funcName].defaultOutputType;
  1050. }
  1051. // If the function is an inherit type it will have a field as
  1052. // the first parameter and we can use that to get the type.
  1053. const fieldDef = getFieldDefinition(firstArg ?? '');
  1054. if (fieldDef !== null) {
  1055. return fieldDef.valueType as AggregationOutputType;
  1056. }
  1057. if (firstArg && isMeasurement(firstArg)) {
  1058. return measurementType(firstArg);
  1059. }
  1060. if (firstArg && isSpanOperationBreakdownField(firstArg)) {
  1061. return 'duration';
  1062. }
  1063. return null;
  1064. }
  1065. export function errorsAndTransactionsAggregateFunctionOutputType(
  1066. funcName: string,
  1067. firstArg: string | undefined
  1068. ): AggregationOutputType | null {
  1069. const aggregate = AGGREGATIONS[ALIASES[funcName] || funcName];
  1070. // Attempt to use the function's outputType.
  1071. if (aggregate?.outputType) {
  1072. return aggregate.outputType;
  1073. }
  1074. // If the first argument is undefined and it is not required,
  1075. // then we attempt to get the default value.
  1076. if (!firstArg && aggregate?.parameters?.[0]) {
  1077. if (aggregate.parameters[0].required === false) {
  1078. firstArg = aggregate.parameters[0].defaultValue;
  1079. }
  1080. }
  1081. // If the function is an inherit type it will have a field as
  1082. // the first parameter and we can use that to get the type.
  1083. const fieldDef = getFieldDefinition(firstArg ?? '');
  1084. if (fieldDef !== null) {
  1085. return fieldDef.valueType as AggregationOutputType;
  1086. }
  1087. if (firstArg && isMeasurement(firstArg)) {
  1088. return measurementType(firstArg);
  1089. }
  1090. if (firstArg && isSpanOperationBreakdownField(firstArg)) {
  1091. return 'duration';
  1092. }
  1093. return null;
  1094. }
  1095. export function sessionsAggregateFunctionOutputType(
  1096. funcName: string,
  1097. firstArg: string | undefined
  1098. ): AggregationOutputType | null {
  1099. const aggregate = SESSIONS_OPERATIONS[funcName];
  1100. // Attempt to use the function's outputType.
  1101. if (aggregate?.outputType) {
  1102. return aggregate.outputType;
  1103. }
  1104. // If the first argument is undefined and it is not required,
  1105. // then we attempt to get the default value.
  1106. if (!firstArg && aggregate?.parameters?.[0]) {
  1107. if (aggregate.parameters[0].required === false) {
  1108. firstArg = aggregate.parameters[0].defaultValue;
  1109. }
  1110. }
  1111. if (firstArg && SESSIONS_FIELDS.hasOwnProperty(firstArg)) {
  1112. return SESSIONS_FIELDS[firstArg].type as AggregationOutputType;
  1113. }
  1114. return null;
  1115. }
  1116. /**
  1117. * Get the multi-series chart type for an aggregate function.
  1118. */
  1119. export function aggregateMultiPlotType(field: string): PlotType {
  1120. if (isEquation(field)) {
  1121. return 'line';
  1122. }
  1123. const result = parseFunction(field);
  1124. // Handle invalid data.
  1125. if (!result) {
  1126. return 'area';
  1127. }
  1128. if (!AGGREGATIONS.hasOwnProperty(result.name)) {
  1129. return 'area';
  1130. }
  1131. return AGGREGATIONS[result.name].multiPlotType;
  1132. }
  1133. function validateForNumericAggregate(
  1134. validColumnTypes: ColumnType[]
  1135. ): ValidateColumnValueFunction {
  1136. return function ({name, dataType}: {dataType: ColumnType; name: string}): boolean {
  1137. // these built-in columns cannot be applied to numeric aggregates such as percentile(...)
  1138. if (
  1139. [
  1140. FieldKey.DEVICE_BATTERY_LEVEL,
  1141. FieldKey.STACK_COLNO,
  1142. FieldKey.STACK_LINENO,
  1143. FieldKey.STACK_STACK_LEVEL,
  1144. ].includes(name as FieldKey)
  1145. ) {
  1146. return false;
  1147. }
  1148. return validColumnTypes.includes(dataType);
  1149. };
  1150. }
  1151. function validateDenyListColumns(
  1152. validColumnTypes: ColumnType[],
  1153. deniedColumns: string[]
  1154. ): ValidateColumnValueFunction {
  1155. return function ({name, dataType}: {dataType: ColumnType; name: string}): boolean {
  1156. return validColumnTypes.includes(dataType) && !deniedColumns.includes(name);
  1157. };
  1158. }
  1159. function validateAllowedColumns(validColumns: string[]): ValidateColumnValueFunction {
  1160. return function ({name}): boolean {
  1161. return validColumns.includes(name);
  1162. };
  1163. }
  1164. const alignedTypes: ColumnValueType[] = [
  1165. 'number',
  1166. 'duration',
  1167. 'integer',
  1168. 'percentage',
  1169. 'percent_change',
  1170. 'rate',
  1171. 'size',
  1172. ];
  1173. export function fieldAlignment(
  1174. columnName: string,
  1175. columnType?: undefined | ColumnValueType,
  1176. metadata?: Record<string, ColumnValueType>
  1177. ): Alignments {
  1178. let align: Alignments = 'left';
  1179. if (isMRIField(columnName)) {
  1180. return 'right';
  1181. }
  1182. if (columnType) {
  1183. align = alignedTypes.includes(columnType) ? 'right' : 'left';
  1184. }
  1185. if (columnType === undefined || columnType === 'never') {
  1186. // fallback to align the column based on the table metadata
  1187. const maybeType = metadata ? metadata[getAggregateAlias(columnName)] : undefined;
  1188. if (maybeType !== undefined && alignedTypes.includes(maybeType)) {
  1189. align = 'right';
  1190. }
  1191. }
  1192. return align;
  1193. }
  1194. /**
  1195. * Match on types that are legal to show on a timeseries chart.
  1196. */
  1197. export function isLegalYAxisType(match: ColumnType | MetricType) {
  1198. return ['number', 'integer', 'duration', 'percentage'].includes(match);
  1199. }
  1200. export function getSpanOperationName(field: string): string | null {
  1201. const results = field.match(SPAN_OP_BREAKDOWN_PATTERN);
  1202. if (results && results.length >= 2) {
  1203. return results[1];
  1204. }
  1205. return null;
  1206. }
  1207. export function getColumnType(column: Column): ColumnType {
  1208. if (column.kind === 'function') {
  1209. const outputType = aggregateFunctionOutputType(
  1210. column.function[0],
  1211. column.function[1]
  1212. );
  1213. if (outputType !== null) {
  1214. return outputType;
  1215. }
  1216. } else if (column.kind === 'field') {
  1217. const fieldDef = getFieldDefinition(column.field);
  1218. if (fieldDef !== null) {
  1219. return fieldDef.valueType as ColumnType;
  1220. }
  1221. if (isMeasurement(column.field)) {
  1222. return measurementType(column.field);
  1223. }
  1224. if (isSpanOperationBreakdownField(column.field)) {
  1225. return 'duration';
  1226. }
  1227. }
  1228. return 'string';
  1229. }
  1230. export function hasDuplicate(columnList: Column[], column: Column): boolean {
  1231. if (column.kind !== 'function' && column.kind !== 'field') {
  1232. return false;
  1233. }
  1234. return columnList.filter(newColumn => isEqual(newColumn, column)).length > 1;
  1235. }
  1236. // Search categorizations for the new `SearchQueryBuilder` component.
  1237. // Each Insights module page will have different points of interest for searching, so use these on a case-by-case basis
  1238. export const TRANSACTION_FILTERS: FilterKeySection = {
  1239. value: 'transaction_event_filters',
  1240. label: 'Event',
  1241. children: [
  1242. FieldKey.TRANSACTION_DURATION,
  1243. FieldKey.TRANSACTION_OP,
  1244. FieldKey.TRANSACTION_STATUS,
  1245. FieldKey.TRANSACTION,
  1246. SpanOpBreakdown.SPANS_BROWSER,
  1247. SpanOpBreakdown.SPANS_DB,
  1248. SpanOpBreakdown.SPANS_HTTP,
  1249. SpanOpBreakdown.SPANS_RESOURCE,
  1250. SpanOpBreakdown.SPANS_UI,
  1251. ],
  1252. };
  1253. export const USER_FILTERS: FilterKeySection = {
  1254. value: 'user_filters',
  1255. label: 'User',
  1256. children: [
  1257. FieldKey.USER,
  1258. FieldKey.USER_DISPLAY,
  1259. FieldKey.USER_EMAIL,
  1260. FieldKey.USER_ID,
  1261. FieldKey.USER_IP,
  1262. FieldKey.USER_USERNAME,
  1263. ],
  1264. };
  1265. export const GEO_FILTERS: FilterKeySection = {
  1266. value: 'geo_filters',
  1267. label: 'Geo',
  1268. children: [
  1269. FieldKey.GEO_CITY,
  1270. FieldKey.GEO_COUNTRY_CODE,
  1271. FieldKey.GEO_REGION,
  1272. FieldKey.GEO_SUBDIVISION,
  1273. ],
  1274. };
  1275. export const HTTP_FILTERS: FilterKeySection = {
  1276. value: 'http_filters',
  1277. label: 'HTTP',
  1278. children: [
  1279. FieldKey.HTTP_METHOD,
  1280. FieldKey.HTTP_REFERER,
  1281. FieldKey.HTTP_STATUS_CODE,
  1282. FieldKey.HTTP_URL,
  1283. ],
  1284. };
  1285. export const WEB_VITAL_FILTERS: FilterKeySection = {
  1286. value: 'web_filters',
  1287. label: 'Web Vitals',
  1288. children: [
  1289. WebVital.CLS,
  1290. WebVital.FCP,
  1291. WebVital.FID,
  1292. WebVital.FP,
  1293. WebVital.INP,
  1294. WebVital.LCP,
  1295. WebVital.REQUEST_TIME,
  1296. ],
  1297. };
  1298. export const MOBILE_VITAL_FILTERS: FilterKeySection = {
  1299. value: 'mobile_vitals_filters',
  1300. label: 'Mobile Vitals',
  1301. children: [
  1302. MobileVital.APP_START_COLD,
  1303. MobileVital.APP_START_WARM,
  1304. MobileVital.FRAMES_FROZEN,
  1305. MobileVital.FRAMES_FROZEN_RATE,
  1306. MobileVital.FRAMES_SLOW,
  1307. MobileVital.FRAMES_SLOW_RATE,
  1308. MobileVital.FRAMES_TOTAL,
  1309. MobileVital.STALL_COUNT,
  1310. MobileVital.STALL_LONGEST_TIME,
  1311. MobileVital.STALL_PERCENTAGE,
  1312. MobileVital.STALL_TOTAL_TIME,
  1313. MobileVital.TIME_TO_FULL_DISPLAY,
  1314. MobileVital.TIME_TO_INITIAL_DISPLAY,
  1315. ],
  1316. };
  1317. export const DEVICE_FILTERS: FilterKeySection = {
  1318. value: 'device_filters',
  1319. label: 'Device',
  1320. children: [
  1321. FieldKey.DEVICE_ARCH,
  1322. FieldKey.DEVICE_BATTERY_LEVEL,
  1323. FieldKey.DEVICE_BRAND,
  1324. FieldKey.DEVICE_CHARGING,
  1325. FieldKey.DEVICE_CLASS,
  1326. FieldKey.DEVICE_FAMILY,
  1327. FieldKey.DEVICE_LOCALE,
  1328. // FieldKey.DEVICE_MODEL_ID,
  1329. FieldKey.DEVICE_NAME,
  1330. FieldKey.DEVICE_ONLINE,
  1331. FieldKey.DEVICE_ORIENTATION,
  1332. FieldKey.DEVICE_SCREEN_DENSITY,
  1333. FieldKey.DEVICE_SCREEN_DPI,
  1334. FieldKey.DEVICE_SCREEN_HEIGHT_PIXELS,
  1335. FieldKey.DEVICE_SCREEN_WIDTH_PIXELS,
  1336. FieldKey.DEVICE_SIMULATOR,
  1337. FieldKey.DEVICE_UUID,
  1338. ],
  1339. };
  1340. export const RELEASE_FILTERS: FilterKeySection = {
  1341. value: 'release_filters',
  1342. label: 'Release',
  1343. children: [
  1344. FieldKey.RELEASE,
  1345. FieldKey.RELEASE_BUILD,
  1346. FieldKey.RELEASE_PACKAGE,
  1347. FieldKey.RELEASE_STAGE,
  1348. FieldKey.RELEASE_VERSION,
  1349. ],
  1350. };
  1351. export const STACKTRACE_FILTERS: FilterKeySection = {
  1352. value: 'stacktrace_filters',
  1353. label: 'Stacktrace',
  1354. children: [
  1355. FieldKey.STACK_ABS_PATH,
  1356. FieldKey.STACK_COLNO,
  1357. FieldKey.STACK_FILENAME,
  1358. FieldKey.STACK_FUNCTION,
  1359. FieldKey.STACK_IN_APP,
  1360. FieldKey.STACK_LINENO,
  1361. FieldKey.STACK_MODULE,
  1362. FieldKey.STACK_PACKAGE,
  1363. FieldKey.STACK_STACK_LEVEL,
  1364. ],
  1365. };
  1366. export const ERROR_DETAIL_FILTERS: FilterKeySection = {
  1367. value: 'error_detail_filters',
  1368. label: 'Error',
  1369. children: [
  1370. FieldKey.LEVEL,
  1371. FieldKey.MESSAGE,
  1372. FieldKey.ERROR_TYPE,
  1373. FieldKey.ERROR_VALUE,
  1374. FieldKey.ERROR_MECHANISM,
  1375. FieldKey.ERROR_HANDLED,
  1376. FieldKey.ERROR_UNHANDLED,
  1377. FieldKey.ERROR_RECEIVED,
  1378. FieldKey.ERROR_MAIN_THREAD,
  1379. ],
  1380. };
  1381. export const MISC_FILTERS: FilterKeySection = {
  1382. value: 'misc_filters',
  1383. label: 'Misc',
  1384. children: [FieldKey.HAS, FieldKey.DIST],
  1385. };
  1386. export const TRANSACTION_EVENT_FILTERS: FilterKeySection = {
  1387. value: 'transaction_event_filters',
  1388. label: 'Event',
  1389. children: [
  1390. ...TRANSACTION_FILTERS.children,
  1391. ...HTTP_FILTERS.children,
  1392. ...RELEASE_FILTERS.children,
  1393. ],
  1394. };
  1395. export const ERROR_EVENT_FILTERS: FilterKeySection = {
  1396. value: 'error_event_filters',
  1397. label: 'Event',
  1398. children: [
  1399. ...ERROR_DETAIL_FILTERS.children,
  1400. ...HTTP_FILTERS.children,
  1401. ...RELEASE_FILTERS.children,
  1402. ],
  1403. };
  1404. export const COMBINED_EVENT_FILTERS: FilterKeySection = {
  1405. value: 'combined_event_filters',
  1406. label: 'Event',
  1407. children: [
  1408. ...TRANSACTION_FILTERS.children,
  1409. ...ERROR_DETAIL_FILTERS.children,
  1410. ...HTTP_FILTERS.children,
  1411. ...RELEASE_FILTERS.children,
  1412. ],
  1413. };
  1414. export const USER_CONTEXT_FILTERS: FilterKeySection = {
  1415. value: 'user_context_filters',
  1416. label: 'User',
  1417. children: [
  1418. ...USER_FILTERS.children,
  1419. ...GEO_FILTERS.children,
  1420. ...DEVICE_FILTERS.children,
  1421. ],
  1422. };
  1423. export const PERFORMANCE_FILTERS: FilterKeySection = {
  1424. value: 'performance_filters',
  1425. label: 'Performance',
  1426. children: [...WEB_VITAL_FILTERS.children, ...MOBILE_VITAL_FILTERS.children],
  1427. };
  1428. export const ALL_INSIGHTS_FILTER_KEY_SECTIONS: FilterKeySection[] = [
  1429. PERFORMANCE_FILTERS,
  1430. TRANSACTION_FILTERS,
  1431. USER_CONTEXT_FILTERS,
  1432. ];
  1433. export const ERRORS_DATASET_FILTER_KEY_SECTIONS: FilterKeySection[] = [
  1434. ERROR_EVENT_FILTERS,
  1435. USER_CONTEXT_FILTERS,
  1436. ];
  1437. export const COMBINED_DATASET_FILTER_KEY_SECTIONS: FilterKeySection[] = [
  1438. PERFORMANCE_FILTERS,
  1439. COMBINED_EVENT_FILTERS,
  1440. USER_CONTEXT_FILTERS,
  1441. ];
  1442. // TODO: In followup PR, add this
  1443. // export const PLATFORM_KEY_TO_FILTER_SECTIONS
  1444. // will take in a project platform key, and output only the relevant filter key sections.
  1445. // This way, users will not be suggested mobile fields for a backend transaction, for example.