eventView.tsx 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  1. import {Location, Query} from 'history';
  2. import cloneDeep from 'lodash/cloneDeep';
  3. import isEqual from 'lodash/isEqual';
  4. import isString from 'lodash/isString';
  5. import omit from 'lodash/omit';
  6. import pick from 'lodash/pick';
  7. import uniqBy from 'lodash/uniqBy';
  8. import moment from 'moment';
  9. import {EventQuery} from 'sentry/actionCreators/events';
  10. import {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable';
  11. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  12. import {DEFAULT_PER_PAGE} from 'sentry/constants';
  13. import {URL_PARAM} from 'sentry/constants/pageFilters';
  14. import {t} from 'sentry/locale';
  15. import {NewQuery, PageFilters, SavedQuery, SelectValue, User} from 'sentry/types';
  16. import {
  17. aggregateOutputType,
  18. Column,
  19. ColumnType,
  20. Field,
  21. generateFieldAsString,
  22. getAggregateAlias,
  23. getEquation,
  24. isAggregateEquation,
  25. isAggregateField,
  26. isEquation,
  27. isLegalYAxisType,
  28. Sort,
  29. WebVital,
  30. } from 'sentry/utils/discover/fields';
  31. import {
  32. CHART_AXIS_OPTIONS,
  33. DISPLAY_MODE_FALLBACK_OPTIONS,
  34. DISPLAY_MODE_OPTIONS,
  35. DisplayModes,
  36. TOP_N,
  37. } from 'sentry/utils/discover/types';
  38. import {decodeList, decodeScalar} from 'sentry/utils/queryString';
  39. import {
  40. FieldValueKind,
  41. TableColumn,
  42. TableColumnSort,
  43. } from 'sentry/views/eventsV2/table/types';
  44. import {decodeColumnOrder} from 'sentry/views/eventsV2/utils';
  45. import {SpanOperationBreakdownFilter} from 'sentry/views/performance/transactionSummary/filter';
  46. import {EventsDisplayFilterName} from 'sentry/views/performance/transactionSummary/transactionEvents/utils';
  47. import {statsPeriodToDays} from '../dates';
  48. import {MutableSearch} from '../tokenizeSearch';
  49. import {getSortField} from './fieldRenderers';
  50. // Metadata mapping for discover results.
  51. export type MetaType = Record<string, ColumnType> & {isMetricsData?: boolean};
  52. // Data in discover results.
  53. export type EventData = Record<string, any>;
  54. export type LocationQuery = {
  55. cursor?: string | string[] | null;
  56. end?: string | string[] | null;
  57. start?: string | string[] | null;
  58. statsPeriod?: string | string[] | null;
  59. utc?: string | string[] | null;
  60. };
  61. const DATETIME_QUERY_STRING_KEYS = ['start', 'end', 'utc', 'statsPeriod'] as const;
  62. const EXTERNAL_QUERY_STRING_KEYS: Readonly<Array<keyof LocationQuery>> = [
  63. ...DATETIME_QUERY_STRING_KEYS,
  64. 'cursor',
  65. ];
  66. const setSortOrder = (sort: Sort, kind: 'desc' | 'asc'): Sort => ({
  67. kind,
  68. field: sort.field,
  69. });
  70. const reverseSort = (sort: Sort): Sort => ({
  71. kind: sort.kind === 'desc' ? 'asc' : 'desc',
  72. field: sort.field,
  73. });
  74. const isSortEqualToField = (
  75. sort: Sort,
  76. field: Field,
  77. tableMeta: MetaType | undefined
  78. ): boolean => {
  79. const sortKey = getSortKeyFromField(field, tableMeta);
  80. return sort.field === sortKey;
  81. };
  82. const fieldToSort = (
  83. field: Field,
  84. tableMeta: MetaType | undefined,
  85. kind?: 'desc' | 'asc'
  86. ): Sort | undefined => {
  87. const sortKey = getSortKeyFromField(field, tableMeta);
  88. if (!sortKey) {
  89. return void 0;
  90. }
  91. return {
  92. kind: kind || 'desc',
  93. field: sortKey,
  94. };
  95. };
  96. function getSortKeyFromField(field: Field, tableMeta?: MetaType): string | null {
  97. const alias = getAggregateAlias(field.field);
  98. return getSortField(alias, tableMeta);
  99. }
  100. export function isFieldSortable(field: Field, tableMeta?: MetaType): boolean {
  101. return !!getSortKeyFromField(field, tableMeta);
  102. }
  103. const decodeFields = (location: Location): Array<Field> => {
  104. const {query} = location;
  105. if (!query || !query.field) {
  106. return [];
  107. }
  108. const fields = decodeList(query.field);
  109. const widths = decodeList(query.widths);
  110. const parsed: Field[] = [];
  111. fields.forEach((field, i) => {
  112. const w = Number(widths[i]);
  113. const width = !isNaN(w) ? w : COL_WIDTH_UNDEFINED;
  114. parsed.push({field, width});
  115. });
  116. return parsed;
  117. };
  118. const parseSort = (sort: string): Sort => {
  119. sort = sort.trim();
  120. if (sort.startsWith('-')) {
  121. return {
  122. kind: 'desc',
  123. field: sort.substring(1),
  124. };
  125. }
  126. return {
  127. kind: 'asc',
  128. field: sort,
  129. };
  130. };
  131. export const fromSorts = (sorts: string | string[] | undefined): Array<Sort> => {
  132. if (sorts === undefined) {
  133. return [];
  134. }
  135. sorts = isString(sorts) ? [sorts] : sorts;
  136. // NOTE: sets are iterated in insertion order
  137. const uniqueSorts = [...new Set(sorts)];
  138. return uniqueSorts.reduce((acc: Array<Sort>, sort: string) => {
  139. acc.push(parseSort(sort));
  140. return acc;
  141. }, []);
  142. };
  143. const decodeSorts = (location: Location): Array<Sort> => {
  144. const {query} = location;
  145. if (!query || !query.sort) {
  146. return [];
  147. }
  148. const sorts = decodeList(query.sort);
  149. return fromSorts(sorts);
  150. };
  151. export const encodeSort = (sort: Sort): string => {
  152. switch (sort.kind) {
  153. case 'desc': {
  154. return `-${sort.field}`;
  155. }
  156. case 'asc': {
  157. return String(sort.field);
  158. }
  159. default: {
  160. throw new Error('Unexpected sort type');
  161. }
  162. }
  163. };
  164. const encodeSorts = (sorts: Readonly<Array<Sort>>): Array<string> =>
  165. sorts.map(encodeSort);
  166. const collectQueryStringByKey = (query: Query, key: string): Array<string> => {
  167. const needle = query[key];
  168. const collection = decodeList(needle);
  169. return collection.reduce((acc: Array<string>, item: string) => {
  170. item = item.trim();
  171. if (item.length > 0) {
  172. acc.push(item);
  173. }
  174. return acc;
  175. }, []);
  176. };
  177. const decodeQuery = (location: Location): string => {
  178. if (!location.query || !location.query.query) {
  179. return '';
  180. }
  181. const queryParameter = location.query.query;
  182. return decodeScalar(queryParameter, '').trim();
  183. };
  184. const decodeTeam = (value: string): 'myteams' | number => {
  185. if (value === 'myteams') {
  186. return value;
  187. }
  188. return parseInt(value, 10);
  189. };
  190. const decodeTeams = (location: Location): ('myteams' | number)[] => {
  191. if (!location.query || !location.query.team) {
  192. return [];
  193. }
  194. const value = location.query.team;
  195. return Array.isArray(value) ? value.map(decodeTeam) : [decodeTeam(value)];
  196. };
  197. const decodeProjects = (location: Location): number[] => {
  198. if (!location.query || !location.query.project) {
  199. return [];
  200. }
  201. const value = location.query.project;
  202. return Array.isArray(value) ? value.map(i => parseInt(i, 10)) : [parseInt(value, 10)];
  203. };
  204. const queryStringFromSavedQuery = (saved: NewQuery | SavedQuery): string => {
  205. if (saved.query) {
  206. return saved.query || '';
  207. }
  208. return '';
  209. };
  210. function validateTableMeta(tableMeta: MetaType | undefined): MetaType | undefined {
  211. return tableMeta && Object.keys(tableMeta).length > 0 ? tableMeta : undefined;
  212. }
  213. class EventView {
  214. id: string | undefined;
  215. name: string | undefined;
  216. fields: Readonly<Field[]>;
  217. sorts: Readonly<Sort[]>;
  218. query: string;
  219. team: Readonly<('myteams' | number)[]>;
  220. project: Readonly<number[]>;
  221. start: string | undefined;
  222. end: string | undefined;
  223. statsPeriod: string | undefined;
  224. utc?: string | boolean | undefined;
  225. environment: Readonly<string[]>;
  226. yAxis: string | undefined;
  227. display: string | undefined;
  228. topEvents: string | undefined;
  229. interval: string | undefined;
  230. expired?: boolean;
  231. createdBy: User | undefined;
  232. additionalConditions: MutableSearch; // This allows views to always add additional conditins to the query to get specific data. It should not show up in the UI unless explicitly called.
  233. constructor(props: {
  234. additionalConditions: MutableSearch;
  235. createdBy: User | undefined;
  236. display: string | undefined;
  237. end: string | undefined;
  238. environment: Readonly<string[]>;
  239. fields: Readonly<Field[]>;
  240. id: string | undefined;
  241. name: string | undefined;
  242. project: Readonly<number[]>;
  243. query: string;
  244. sorts: Readonly<Sort[]>;
  245. start: string | undefined;
  246. statsPeriod: string | undefined;
  247. team: Readonly<('myteams' | number)[]>;
  248. topEvents: string | undefined;
  249. yAxis: string | undefined;
  250. expired?: boolean;
  251. interval?: string;
  252. utc?: string | boolean | undefined;
  253. }) {
  254. const fields: Field[] = Array.isArray(props.fields) ? props.fields : [];
  255. let sorts: Sort[] = Array.isArray(props.sorts) ? props.sorts : [];
  256. const team = Array.isArray(props.team) ? props.team : [];
  257. const project = Array.isArray(props.project) ? props.project : [];
  258. const environment = Array.isArray(props.environment) ? props.environment : [];
  259. // only include sort keys that are included in the fields
  260. let equations = 0;
  261. const sortKeys = fields
  262. .map(field => {
  263. if (field.field && isEquation(field.field)) {
  264. const sortKey = getSortKeyFromField(
  265. {field: `equation[${equations}]`},
  266. undefined
  267. );
  268. equations += 1;
  269. return sortKey;
  270. }
  271. return getSortKeyFromField(field, undefined);
  272. })
  273. .filter((sortKey): sortKey is string => !!sortKey);
  274. const sort = sorts.find(currentSort => sortKeys.includes(currentSort.field));
  275. sorts = sort ? [sort] : [];
  276. const id = props.id !== null && props.id !== void 0 ? String(props.id) : void 0;
  277. this.id = id;
  278. this.name = props.name;
  279. this.fields = fields;
  280. this.sorts = sorts;
  281. this.query = typeof props.query === 'string' ? props.query : '';
  282. this.team = team;
  283. this.project = project;
  284. this.start = props.start;
  285. this.end = props.end;
  286. this.statsPeriod = props.statsPeriod;
  287. this.utc = props.utc;
  288. this.environment = environment;
  289. this.yAxis = props.yAxis;
  290. this.display = props.display;
  291. this.topEvents = props.topEvents;
  292. this.interval = props.interval;
  293. this.createdBy = props.createdBy;
  294. this.expired = props.expired;
  295. this.additionalConditions = props.additionalConditions
  296. ? props.additionalConditions.copy()
  297. : new MutableSearch([]);
  298. }
  299. static fromLocation(location: Location): EventView {
  300. const {start, end, statsPeriod} = normalizeDateTimeParams(location.query);
  301. return new EventView({
  302. id: decodeScalar(location.query.id),
  303. name: decodeScalar(location.query.name),
  304. fields: decodeFields(location),
  305. sorts: decodeSorts(location),
  306. query: decodeQuery(location),
  307. team: decodeTeams(location),
  308. project: decodeProjects(location),
  309. start: decodeScalar(start),
  310. end: decodeScalar(end),
  311. statsPeriod: decodeScalar(statsPeriod),
  312. environment: collectQueryStringByKey(location.query, 'environment'),
  313. yAxis: decodeScalar(location.query.yAxis),
  314. display: decodeScalar(location.query.display),
  315. topEvents: decodeScalar(location.query.topEvents),
  316. interval: decodeScalar(location.query.interval),
  317. createdBy: undefined,
  318. additionalConditions: new MutableSearch([]),
  319. });
  320. }
  321. static fromNewQueryWithLocation(newQuery: NewQuery, location: Location): EventView {
  322. const query = location.query;
  323. // apply global selection header values from location whenever possible
  324. const environment: string[] =
  325. Array.isArray(newQuery.environment) && newQuery.environment.length > 0
  326. ? newQuery.environment
  327. : collectQueryStringByKey(query, 'environment');
  328. const project: number[] =
  329. Array.isArray(newQuery.projects) && newQuery.projects.length > 0
  330. ? newQuery.projects
  331. : decodeProjects(location);
  332. const saved: NewQuery = {
  333. ...newQuery,
  334. environment,
  335. projects: project,
  336. // datetime selection
  337. start: newQuery.start || decodeScalar(query.start),
  338. end: newQuery.end || decodeScalar(query.end),
  339. range: newQuery.range || decodeScalar(query.statsPeriod),
  340. };
  341. return EventView.fromSavedQuery(saved);
  342. }
  343. static getFields(saved: NewQuery | SavedQuery) {
  344. return saved.fields.map((field, i) => {
  345. const width =
  346. saved.widths && saved.widths[i] ? Number(saved.widths[i]) : COL_WIDTH_UNDEFINED;
  347. return {field, width};
  348. });
  349. }
  350. static fromSavedQuery(saved: NewQuery | SavedQuery): EventView {
  351. const fields = EventView.getFields(saved);
  352. // normalize datetime selection
  353. const {start, end, statsPeriod, utc} = normalizeDateTimeParams({
  354. start: saved.start,
  355. end: saved.end,
  356. statsPeriod: saved.range,
  357. utc: saved.utc,
  358. });
  359. return new EventView({
  360. id: saved.id,
  361. name: saved.name,
  362. fields,
  363. query: queryStringFromSavedQuery(saved),
  364. team: saved.teams ?? [],
  365. project: saved.projects,
  366. start: decodeScalar(start),
  367. end: decodeScalar(end),
  368. statsPeriod: decodeScalar(statsPeriod),
  369. utc,
  370. sorts: fromSorts(saved.orderby),
  371. environment: collectQueryStringByKey(
  372. {
  373. environment: saved.environment as string[],
  374. },
  375. 'environment'
  376. ),
  377. // Workaround to only use the first yAxis since eventView yAxis doesn't accept string[]
  378. yAxis: Array.isArray(saved.yAxis) ? saved.yAxis[0] : saved.yAxis,
  379. display: saved.display,
  380. topEvents: saved.topEvents ? saved.topEvents.toString() : undefined,
  381. createdBy: saved.createdBy,
  382. expired: saved.expired,
  383. additionalConditions: new MutableSearch([]),
  384. });
  385. }
  386. static fromSavedQueryOrLocation(
  387. saved: SavedQuery | undefined,
  388. location: Location
  389. ): EventView {
  390. let fields = decodeFields(location);
  391. const {start, end, statsPeriod, utc} = normalizeDateTimeParams(location.query);
  392. const id = decodeScalar(location.query.id);
  393. const teams = decodeTeams(location);
  394. const projects = decodeProjects(location);
  395. const sorts = decodeSorts(location);
  396. const environments = collectQueryStringByKey(location.query, 'environment');
  397. if (saved) {
  398. if (fields.length === 0) {
  399. fields = EventView.getFields(saved);
  400. }
  401. return new EventView({
  402. id: id || saved.id,
  403. name: decodeScalar(location.query.name) || saved.name,
  404. fields,
  405. query:
  406. 'query' in location.query
  407. ? decodeQuery(location)
  408. : queryStringFromSavedQuery(saved),
  409. sorts: sorts.length === 0 ? fromSorts(saved.orderby) : sorts,
  410. yAxis:
  411. decodeScalar(location.query.yAxis) ||
  412. // Workaround to only use the first yAxis since eventView yAxis doesn't accept string[]
  413. (Array.isArray(saved.yAxis) ? saved.yAxis[0] : saved.yAxis),
  414. display: decodeScalar(location.query.display) || saved.display,
  415. topEvents: (
  416. decodeScalar(location.query.topEvents) ||
  417. saved.topEvents ||
  418. TOP_N
  419. ).toString(),
  420. interval: decodeScalar(location.query.interval),
  421. createdBy: saved.createdBy,
  422. expired: saved.expired,
  423. additionalConditions: new MutableSearch([]),
  424. // Always read team from location since they can be set by other parts
  425. // of the UI
  426. team: teams,
  427. // Always read project and environment from location since they can
  428. // be set by the GlobalSelectionHeaders.
  429. project: projects,
  430. environment: environments,
  431. start: decodeScalar(start),
  432. end: decodeScalar(end),
  433. statsPeriod: decodeScalar(statsPeriod),
  434. utc,
  435. });
  436. }
  437. return EventView.fromLocation(location);
  438. }
  439. isEqualTo(other: EventView): boolean {
  440. const defaults = {
  441. id: undefined,
  442. name: undefined,
  443. query: undefined,
  444. statsPeriod: undefined,
  445. fields: undefined,
  446. sorts: undefined,
  447. project: undefined,
  448. environment: undefined,
  449. yAxis: 'count()',
  450. display: DisplayModes.DEFAULT,
  451. topEvents: '5',
  452. };
  453. const keys = Object.keys(defaults);
  454. for (const key of keys) {
  455. const currentValue = this[key] ?? defaults[key];
  456. const otherValue = other[key] ?? defaults[key];
  457. if (!isEqual(currentValue, otherValue)) {
  458. return false;
  459. }
  460. }
  461. // compare datetime selections using moment
  462. const dateTimeKeys = ['start', 'end'];
  463. for (const key of dateTimeKeys) {
  464. const currentValue = this[key];
  465. const otherValue = other[key];
  466. if (currentValue && otherValue) {
  467. const currentDateTime = moment.utc(currentValue);
  468. const othereDateTime = moment.utc(otherValue);
  469. if (!currentDateTime.isSame(othereDateTime)) {
  470. return false;
  471. }
  472. }
  473. }
  474. return true;
  475. }
  476. toNewQuery(): NewQuery {
  477. const orderby = this.sorts.length > 0 ? encodeSorts(this.sorts)[0] : undefined;
  478. const newQuery: NewQuery = {
  479. version: 2,
  480. id: this.id,
  481. name: this.name || '',
  482. fields: this.getFields(),
  483. widths: this.getWidths().map(w => String(w)),
  484. orderby,
  485. query: this.query || '',
  486. projects: this.project,
  487. start: this.start,
  488. end: this.end,
  489. range: this.statsPeriod,
  490. environment: this.environment,
  491. yAxis: this.yAxis ? [this.yAxis] : undefined,
  492. display: this.display,
  493. topEvents: this.topEvents,
  494. };
  495. if (!newQuery.query) {
  496. // if query is an empty string, then it cannot be saved, so we omit it
  497. // from the payload
  498. delete newQuery.query;
  499. }
  500. return newQuery;
  501. }
  502. getPageFilters(): PageFilters {
  503. return {
  504. projects: this.project as number[],
  505. environments: this.environment as string[],
  506. datetime: {
  507. start: this.start ?? null,
  508. end: this.end ?? null,
  509. period: this.statsPeriod ?? null,
  510. // TODO(tony) Add support for the Use UTC option from the global
  511. // headers, currently, that option is not supported and all times are
  512. // assumed to be UTC
  513. utc: true,
  514. },
  515. };
  516. }
  517. getPageFiltersQuery(): Query {
  518. const {
  519. environments: environment,
  520. projects,
  521. datetime: {start, end, period, utc},
  522. } = this.getPageFilters();
  523. return {
  524. project: projects.map(proj => proj.toString()),
  525. environment,
  526. utc: utc ? 'true' : 'false',
  527. // since these values are from `getGlobalSelection`
  528. // we know they have type `string | null`
  529. start: (start ?? undefined) as string | undefined,
  530. end: (end ?? undefined) as string | undefined,
  531. // we can't use the ?? operator here as we want to
  532. // convert the empty string to undefined
  533. statsPeriod: period ? period : undefined,
  534. };
  535. }
  536. generateBlankQueryStringObject(): Query {
  537. const output = {
  538. id: undefined,
  539. name: undefined,
  540. field: undefined,
  541. widths: undefined,
  542. sort: undefined,
  543. tag: undefined,
  544. query: undefined,
  545. yAxis: undefined,
  546. display: undefined,
  547. topEvents: undefined,
  548. interval: undefined,
  549. };
  550. for (const field of EXTERNAL_QUERY_STRING_KEYS) {
  551. output[field] = undefined;
  552. }
  553. return output;
  554. }
  555. generateQueryStringObject(): Query {
  556. const output = {
  557. id: this.id,
  558. name: this.name,
  559. field: this.getFields(),
  560. widths: this.getWidths(),
  561. sort: encodeSorts(this.sorts),
  562. environment: this.environment,
  563. project: this.project,
  564. query: this.query,
  565. yAxis: this.yAxis || this.getYAxis(),
  566. display: this.display,
  567. topEvents: this.topEvents,
  568. interval: this.interval,
  569. };
  570. for (const field of EXTERNAL_QUERY_STRING_KEYS) {
  571. if (this[field] && this[field].length) {
  572. output[field] = this[field];
  573. }
  574. }
  575. return cloneDeep(output as any);
  576. }
  577. isValid(): boolean {
  578. return this.fields.length > 0;
  579. }
  580. getWidths(): number[] {
  581. const result = this.fields.map(field =>
  582. field.width ? field.width : COL_WIDTH_UNDEFINED
  583. );
  584. while (result.length > 0) {
  585. const width = result[result.length - 1];
  586. if (width === COL_WIDTH_UNDEFINED) {
  587. result.pop();
  588. continue;
  589. }
  590. break;
  591. }
  592. return result;
  593. }
  594. getFields(): string[] {
  595. return this.fields.map(field => field.field);
  596. }
  597. getEquations(): string[] {
  598. return this.fields
  599. .filter(field => isEquation(field.field))
  600. .map(field => getEquation(field.field));
  601. }
  602. getAggregateFields(): Field[] {
  603. return this.fields.filter(
  604. field => isAggregateField(field.field) || isAggregateEquation(field.field)
  605. );
  606. }
  607. hasAggregateField() {
  608. return this.fields.some(field => isAggregateField(field.field));
  609. }
  610. hasIdField() {
  611. return this.fields.some(field => field.field === 'id');
  612. }
  613. numOfColumns(): number {
  614. return this.fields.length;
  615. }
  616. getColumns(): TableColumn<React.ReactText>[] {
  617. return decodeColumnOrder(this.fields);
  618. }
  619. getDays(): number {
  620. const statsPeriod = decodeScalar(this.statsPeriod);
  621. return statsPeriodToDays(statsPeriod, this.start, this.end);
  622. }
  623. clone(): EventView {
  624. // NOTE: We rely on usage of Readonly from TypeScript to ensure we do not mutate
  625. // the attributes of EventView directly. This enables us to quickly
  626. // clone new instances of EventView.
  627. return new EventView({
  628. id: this.id,
  629. name: this.name,
  630. fields: this.fields,
  631. sorts: this.sorts,
  632. query: this.query,
  633. team: this.team,
  634. project: this.project,
  635. start: this.start,
  636. end: this.end,
  637. statsPeriod: this.statsPeriod,
  638. environment: this.environment,
  639. yAxis: this.yAxis,
  640. display: this.display,
  641. topEvents: this.topEvents,
  642. interval: this.interval,
  643. expired: this.expired,
  644. createdBy: this.createdBy,
  645. additionalConditions: this.additionalConditions.copy(),
  646. });
  647. }
  648. withSorts(sorts: Sort[]): EventView {
  649. const newEventView = this.clone();
  650. const fields = newEventView.fields.map(field => getAggregateAlias(field.field));
  651. newEventView.sorts = sorts.filter(sort => fields.includes(sort.field));
  652. return newEventView;
  653. }
  654. withColumns(columns: Column[]): EventView {
  655. const newEventView = this.clone();
  656. const fields: Field[] = columns
  657. .filter(
  658. col =>
  659. ((col.kind === 'field' || col.kind === FieldValueKind.EQUATION) && col.field) ||
  660. (col.kind === 'function' && col.function[0])
  661. )
  662. .map(col => generateFieldAsString(col))
  663. .map((field, i) => {
  664. // newly added field
  665. if (!newEventView.fields[i]) {
  666. return {field, width: COL_WIDTH_UNDEFINED};
  667. }
  668. // Existing columns that were not re ordered should retain
  669. // their old widths.
  670. const existing = newEventView.fields[i];
  671. const width =
  672. existing.field === field && existing.width !== undefined
  673. ? existing.width
  674. : COL_WIDTH_UNDEFINED;
  675. return {field, width};
  676. });
  677. newEventView.fields = fields;
  678. // Update sorts as sorted fields may have been removed.
  679. if (newEventView.sorts) {
  680. // Filter the sort fields down to those that are still selected.
  681. const sortKeys = fields.map(field => fieldToSort(field, undefined)?.field);
  682. const newSort = newEventView.sorts.filter(
  683. sort => sort && sortKeys.includes(sort.field)
  684. );
  685. // If the sort field was removed, try and find a new sortable column.
  686. if (newSort.length === 0) {
  687. const sortField = fields.find(field => isFieldSortable(field, undefined));
  688. if (sortField) {
  689. newSort.push({field: sortField.field, kind: 'desc'});
  690. }
  691. }
  692. newEventView.sorts = newSort;
  693. }
  694. newEventView.yAxis = newEventView.getYAxis();
  695. return newEventView;
  696. }
  697. withNewColumn(newColumn: Column): EventView {
  698. const fieldAsString = generateFieldAsString(newColumn);
  699. const newField: Field = {
  700. field: fieldAsString,
  701. width: COL_WIDTH_UNDEFINED,
  702. };
  703. const newEventView = this.clone();
  704. newEventView.fields = [...newEventView.fields, newField];
  705. return newEventView;
  706. }
  707. withResizedColumn(columnIndex: number, newWidth: number) {
  708. const field = this.fields[columnIndex];
  709. const newEventView = this.clone();
  710. if (!field) {
  711. return newEventView;
  712. }
  713. const updateWidth = field.width !== newWidth;
  714. if (updateWidth) {
  715. const fields = [...newEventView.fields];
  716. fields[columnIndex] = {
  717. ...field,
  718. width: newWidth,
  719. };
  720. newEventView.fields = fields;
  721. }
  722. return newEventView;
  723. }
  724. withUpdatedColumn(
  725. columnIndex: number,
  726. updatedColumn: Column,
  727. tableMeta: MetaType | undefined
  728. ): EventView {
  729. const columnToBeUpdated = this.fields[columnIndex];
  730. const fieldAsString = generateFieldAsString(updatedColumn);
  731. const updateField = columnToBeUpdated.field !== fieldAsString;
  732. if (!updateField) {
  733. return this;
  734. }
  735. // ensure tableMeta is non-empty
  736. tableMeta = validateTableMeta(tableMeta);
  737. const newEventView = this.clone();
  738. const updatedField: Field = {
  739. field: fieldAsString,
  740. width: COL_WIDTH_UNDEFINED,
  741. };
  742. const fields = [...newEventView.fields];
  743. fields[columnIndex] = updatedField;
  744. newEventView.fields = fields;
  745. // if the updated column is one of the sorted columns, we may need to remove
  746. // it from the list of sorts
  747. const needleSortIndex = this.sorts.findIndex(sort =>
  748. isSortEqualToField(sort, columnToBeUpdated, tableMeta)
  749. );
  750. if (needleSortIndex >= 0) {
  751. const needleSort = this.sorts[needleSortIndex];
  752. const numOfColumns = this.fields.reduce((sum, currentField) => {
  753. if (isSortEqualToField(needleSort, currentField, tableMeta)) {
  754. return sum + 1;
  755. }
  756. return sum;
  757. }, 0);
  758. // do not bother deleting the sort key if there are more than one columns
  759. // of it in the table.
  760. if (numOfColumns <= 1) {
  761. if (isFieldSortable(updatedField, tableMeta)) {
  762. // use the current updated field as the sort key
  763. const sort = fieldToSort(updatedField, tableMeta)!;
  764. // preserve the sort kind
  765. sort.kind = needleSort.kind;
  766. const sorts = [...newEventView.sorts];
  767. sorts[needleSortIndex] = sort;
  768. newEventView.sorts = sorts;
  769. } else {
  770. const sorts = [...newEventView.sorts];
  771. sorts.splice(needleSortIndex, 1);
  772. newEventView.sorts = [...new Set(sorts)];
  773. }
  774. }
  775. if (newEventView.sorts.length <= 0 && newEventView.fields.length > 0) {
  776. // establish a default sort by finding the first sortable field
  777. if (isFieldSortable(updatedField, tableMeta)) {
  778. // use the current updated field as the sort key
  779. const sort = fieldToSort(updatedField, tableMeta)!;
  780. // preserve the sort kind
  781. sort.kind = needleSort.kind;
  782. newEventView.sorts = [sort];
  783. } else {
  784. const sortableFieldIndex = newEventView.fields.findIndex(currentField =>
  785. isFieldSortable(currentField, tableMeta)
  786. );
  787. if (sortableFieldIndex >= 0) {
  788. const fieldToBeSorted = newEventView.fields[sortableFieldIndex];
  789. const sort = fieldToSort(fieldToBeSorted, tableMeta)!;
  790. newEventView.sorts = [sort];
  791. }
  792. }
  793. }
  794. }
  795. newEventView.yAxis = newEventView.getYAxis();
  796. return newEventView;
  797. }
  798. withDeletedColumn(columnIndex: number, tableMeta: MetaType | undefined): EventView {
  799. // Disallow removal of the orphan column, and check for out-of-bounds
  800. if (this.fields.length <= 1 || this.fields.length <= columnIndex || columnIndex < 0) {
  801. return this;
  802. }
  803. // ensure tableMeta is non-empty
  804. tableMeta = validateTableMeta(tableMeta);
  805. // delete the column
  806. const newEventView = this.clone();
  807. const fields = [...newEventView.fields];
  808. fields.splice(columnIndex, 1);
  809. newEventView.fields = fields;
  810. // Ensure there is at least one auto width column
  811. // To ensure a well formed table results.
  812. const hasAutoIndex = fields.find(field => field.width === COL_WIDTH_UNDEFINED);
  813. if (!hasAutoIndex) {
  814. newEventView.fields[0].width = COL_WIDTH_UNDEFINED;
  815. }
  816. // if the deleted column is one of the sorted columns, we need to remove
  817. // it from the list of sorts
  818. const columnToBeDeleted = this.fields[columnIndex];
  819. const needleSortIndex = this.sorts.findIndex(sort =>
  820. isSortEqualToField(sort, columnToBeDeleted, tableMeta)
  821. );
  822. if (needleSortIndex >= 0) {
  823. const needleSort = this.sorts[needleSortIndex];
  824. const numOfColumns = this.fields.reduce((sum, field) => {
  825. if (isSortEqualToField(needleSort, field, tableMeta)) {
  826. return sum + 1;
  827. }
  828. return sum;
  829. }, 0);
  830. // do not bother deleting the sort key if there are more than one columns
  831. // of it in the table.
  832. if (numOfColumns <= 1) {
  833. const sorts = [...newEventView.sorts];
  834. sorts.splice(needleSortIndex, 1);
  835. newEventView.sorts = [...new Set(sorts)];
  836. if (newEventView.sorts.length <= 0 && newEventView.fields.length > 0) {
  837. // establish a default sort by finding the first sortable field
  838. const sortableFieldIndex = newEventView.fields.findIndex(field =>
  839. isFieldSortable(field, tableMeta)
  840. );
  841. if (sortableFieldIndex >= 0) {
  842. const fieldToBeSorted = newEventView.fields[sortableFieldIndex];
  843. const sort = fieldToSort(fieldToBeSorted, tableMeta)!;
  844. newEventView.sorts = [sort];
  845. }
  846. }
  847. }
  848. }
  849. newEventView.yAxis = newEventView.getYAxis();
  850. return newEventView;
  851. }
  852. withTeams(teams: ('myteams' | number)[]): EventView {
  853. const newEventView = this.clone();
  854. newEventView.team = teams;
  855. return newEventView;
  856. }
  857. getSorts(): TableColumnSort<React.ReactText>[] {
  858. return this.sorts.map(
  859. sort =>
  860. ({
  861. key: sort.field,
  862. order: sort.kind,
  863. } as TableColumnSort<string>)
  864. );
  865. }
  866. // returns query input for the search
  867. getQuery(inputQuery: string | string[] | null | undefined): string {
  868. const queryParts: string[] = [];
  869. if (this.query) {
  870. if (this.additionalConditions) {
  871. queryParts.push(this.getQueryWithAdditionalConditions());
  872. } else {
  873. queryParts.push(this.query);
  874. }
  875. }
  876. if (inputQuery) {
  877. // there may be duplicate query in the query string
  878. // e.g. query=hello&query=world
  879. if (Array.isArray(inputQuery)) {
  880. inputQuery.forEach(query => {
  881. if (typeof query === 'string' && !queryParts.includes(query)) {
  882. queryParts.push(query);
  883. }
  884. });
  885. }
  886. if (typeof inputQuery === 'string' && !queryParts.includes(inputQuery)) {
  887. queryParts.push(inputQuery);
  888. }
  889. }
  890. return queryParts.join(' ');
  891. }
  892. getFacetsAPIPayload(
  893. location: Location
  894. ): Exclude<EventQuery & LocationQuery, 'sort' | 'cursor'> {
  895. const payload = this.getEventsAPIPayload(location);
  896. const remove = [
  897. 'id',
  898. 'name',
  899. 'per_page',
  900. 'sort',
  901. 'cursor',
  902. 'field',
  903. 'equation',
  904. 'interval',
  905. ];
  906. for (const key of remove) {
  907. delete payload[key];
  908. }
  909. return payload;
  910. }
  911. normalizeDateSelection(location: Location) {
  912. const query = (location && location.query) || {};
  913. // pick only the query strings that we care about
  914. const picked = pickRelevantLocationQueryStrings(location);
  915. const hasDateSelection = this.statsPeriod || (this.start && this.end);
  916. // an eventview's date selection has higher precedence than the date selection in the query string
  917. const dateSelection = hasDateSelection
  918. ? {
  919. start: this.start,
  920. end: this.end,
  921. statsPeriod: this.statsPeriod,
  922. }
  923. : {
  924. start: picked.start,
  925. end: picked.end,
  926. period: decodeScalar(query.period),
  927. statsPeriod: picked.statsPeriod,
  928. };
  929. // normalize datetime selection
  930. return normalizeDateTimeParams({
  931. ...dateSelection,
  932. utc: decodeScalar(query.utc),
  933. });
  934. }
  935. // Takes an EventView instance and converts it into the format required for the events API
  936. getEventsAPIPayload(location: Location): EventQuery & LocationQuery {
  937. // pick only the query strings that we care about
  938. const picked = pickRelevantLocationQueryStrings(location);
  939. // normalize datetime selection
  940. const normalizedTimeWindowParams = this.normalizeDateSelection(location);
  941. const sort =
  942. this.sorts.length <= 0
  943. ? undefined
  944. : this.sorts.length > 1
  945. ? encodeSorts(this.sorts)
  946. : encodeSort(this.sorts[0]);
  947. const fields = this.getFields();
  948. const team = this.team.map(proj => String(proj));
  949. const project = this.project.map(proj => String(proj));
  950. const environment = this.environment as string[];
  951. // generate event query
  952. const eventQuery = Object.assign(
  953. omit(picked, DATETIME_QUERY_STRING_KEYS),
  954. normalizedTimeWindowParams,
  955. {
  956. team,
  957. project,
  958. environment,
  959. field: [...new Set(fields)],
  960. sort,
  961. per_page: DEFAULT_PER_PAGE,
  962. query: this.getQueryWithAdditionalConditions(),
  963. }
  964. ) as EventQuery & LocationQuery;
  965. if (eventQuery.team && !eventQuery.team.length) {
  966. delete eventQuery.team;
  967. }
  968. if (!eventQuery.sort) {
  969. delete eventQuery.sort;
  970. }
  971. return eventQuery;
  972. }
  973. getResultsViewUrlTarget(slug: string): {pathname: string; query: Query} {
  974. return {
  975. pathname: `/organizations/${slug}/discover/results/`,
  976. query: this.generateQueryStringObject(),
  977. };
  978. }
  979. getResultsViewShortUrlTarget(slug: string): {pathname: string; query: Query} {
  980. const output = {id: this.id};
  981. for (const field of [...Object.values(URL_PARAM), 'cursor']) {
  982. if (this[field] && this[field].length) {
  983. output[field] = this[field];
  984. }
  985. }
  986. return {
  987. pathname: `/organizations/${slug}/discover/results/`,
  988. query: cloneDeep(output as any),
  989. };
  990. }
  991. getPerformanceTransactionEventsViewUrlTarget(
  992. slug: string,
  993. options: {
  994. breakdown?: SpanOperationBreakdownFilter;
  995. showTransactions?: EventsDisplayFilterName;
  996. webVital?: WebVital;
  997. }
  998. ): {pathname: string; query: Query} {
  999. const {showTransactions, breakdown, webVital} = options;
  1000. const output = {
  1001. sort: encodeSorts(this.sorts),
  1002. project: this.project,
  1003. query: this.query,
  1004. transaction: this.name,
  1005. showTransactions,
  1006. breakdown,
  1007. webVital,
  1008. };
  1009. for (const field of EXTERNAL_QUERY_STRING_KEYS) {
  1010. if (this[field] && this[field].length) {
  1011. output[field] = this[field];
  1012. }
  1013. }
  1014. const query = cloneDeep(output as any);
  1015. return {
  1016. pathname: `/organizations/${slug}/performance/summary/events/`,
  1017. query,
  1018. };
  1019. }
  1020. sortForField(field: Field, tableMeta: MetaType | undefined): Sort | undefined {
  1021. if (!tableMeta) {
  1022. return undefined;
  1023. }
  1024. return this.sorts.find(sort => isSortEqualToField(sort, field, tableMeta));
  1025. }
  1026. sortOnField(field: Field, tableMeta: MetaType, kind?: 'desc' | 'asc'): EventView {
  1027. // check if field can be sorted
  1028. if (!isFieldSortable(field, tableMeta)) {
  1029. return this;
  1030. }
  1031. const needleIndex = this.sorts.findIndex(sort =>
  1032. isSortEqualToField(sort, field, tableMeta)
  1033. );
  1034. if (needleIndex >= 0) {
  1035. const newEventView = this.clone();
  1036. const currentSort = this.sorts[needleIndex];
  1037. const sorts = [...newEventView.sorts];
  1038. sorts[needleIndex] = kind
  1039. ? setSortOrder(currentSort, kind)
  1040. : reverseSort(currentSort);
  1041. newEventView.sorts = sorts;
  1042. return newEventView;
  1043. }
  1044. // field is currently not sorted; so, we sort on it
  1045. const newEventView = this.clone();
  1046. // invariant: this is not falsey, since sortKey exists
  1047. const sort = fieldToSort(field, tableMeta, kind)!;
  1048. newEventView.sorts = [sort];
  1049. return newEventView;
  1050. }
  1051. getYAxisOptions(): SelectValue<string>[] {
  1052. // Make option set and add the default options in.
  1053. return uniqBy(
  1054. this.getAggregateFields()
  1055. // Only include aggregates that make sense to be graphable (eg. not string or date)
  1056. .filter(
  1057. (field: Field) =>
  1058. isLegalYAxisType(aggregateOutputType(field.field)) ||
  1059. isAggregateEquation(field.field)
  1060. )
  1061. .map((field: Field) => ({
  1062. label: isEquation(field.field) ? getEquation(field.field) : field.field,
  1063. value: field.field,
  1064. }))
  1065. .concat(CHART_AXIS_OPTIONS),
  1066. 'value'
  1067. );
  1068. }
  1069. getYAxis(): string {
  1070. const yAxisOptions = this.getYAxisOptions();
  1071. const yAxis = this.yAxis;
  1072. const defaultOption = yAxisOptions[0].value;
  1073. if (!yAxis) {
  1074. return defaultOption;
  1075. }
  1076. // ensure current selected yAxis is one of the items in yAxisOptions
  1077. const result = yAxisOptions.findIndex(
  1078. (option: SelectValue<string>) => option.value === yAxis
  1079. );
  1080. if (result >= 0) {
  1081. return yAxis;
  1082. }
  1083. return defaultOption;
  1084. }
  1085. getDisplayOptions(): SelectValue<string>[] {
  1086. return DISPLAY_MODE_OPTIONS.map(item => {
  1087. if (item.value === DisplayModes.PREVIOUS) {
  1088. if (this.start || this.end) {
  1089. return {...item, disabled: true};
  1090. }
  1091. }
  1092. if (item.value === DisplayModes.TOP5 || item.value === DisplayModes.DAILYTOP5) {
  1093. if (this.getAggregateFields().length === 0) {
  1094. return {
  1095. ...item,
  1096. disabled: true,
  1097. tooltip: t('Add a function that groups events to use this view.'),
  1098. };
  1099. }
  1100. }
  1101. if (item.value === DisplayModes.DAILY || item.value === DisplayModes.DAILYTOP5) {
  1102. if (this.getDays() < 1) {
  1103. return {
  1104. ...item,
  1105. disabled: true,
  1106. tooltip: t('Change the date rage to at least 1 day to use this view.'),
  1107. };
  1108. }
  1109. }
  1110. return item;
  1111. });
  1112. }
  1113. getDisplayMode() {
  1114. const mode = this.display ?? DisplayModes.DEFAULT;
  1115. const displayOptions = this.getDisplayOptions();
  1116. let display = (Object.values(DisplayModes) as string[]).includes(mode)
  1117. ? mode
  1118. : DisplayModes.DEFAULT;
  1119. const cond = option => option.value === display;
  1120. // Just in case we define a fallback chain that results in an infinite loop.
  1121. // The number 5 isn't anything special, its just larger than the longest fallback
  1122. // chain that exists and isn't too big.
  1123. for (let i = 0; i < 5; i++) {
  1124. const selectedOption = displayOptions.find(cond);
  1125. if (selectedOption && !selectedOption.disabled) {
  1126. return display;
  1127. }
  1128. display = DISPLAY_MODE_FALLBACK_OPTIONS[display];
  1129. }
  1130. // after trying to find an enabled display mode and failing to find one,
  1131. // we just use the default display mode
  1132. return DisplayModes.DEFAULT;
  1133. }
  1134. getQueryWithAdditionalConditions() {
  1135. const {query} = this;
  1136. if (this.additionalConditions.isEmpty()) {
  1137. return query;
  1138. }
  1139. const conditions = new MutableSearch(query);
  1140. Object.entries(this.additionalConditions.filters).forEach(([tag, tagValues]) => {
  1141. const existingTagValues = conditions.getFilterValues(tag);
  1142. const newTagValues = tagValues.filter(
  1143. tagValue => !existingTagValues.includes(tagValue)
  1144. );
  1145. if (newTagValues.length) {
  1146. conditions.addFilterValues(tag, newTagValues);
  1147. }
  1148. });
  1149. return conditions.formatString();
  1150. }
  1151. }
  1152. export type ImmutableEventView = Readonly<Omit<EventView, 'additionalConditions'>>;
  1153. const isFieldsSimilar = (
  1154. currentValue: Array<string>,
  1155. otherValue: Array<string>
  1156. ): boolean => {
  1157. // For equation's their order matters because we alias them based on index
  1158. const currentEquations = currentValue.filter(isEquation);
  1159. const otherEquations = otherValue.filter(isEquation);
  1160. // Field orders don't matter, so using a set for comparison
  1161. const currentFields = new Set(currentValue.filter(value => !isEquation(value)));
  1162. const otherFields = new Set(otherValue.filter(value => !isEquation(value)));
  1163. if (!isEqual(currentEquations, otherEquations)) {
  1164. return false;
  1165. }
  1166. if (!isEqual(currentFields, otherFields)) {
  1167. return false;
  1168. }
  1169. return true;
  1170. };
  1171. export const isAPIPayloadSimilar = (
  1172. current: EventQuery & LocationQuery,
  1173. other: EventQuery & LocationQuery
  1174. ): boolean => {
  1175. const currentKeys = new Set(Object.keys(current));
  1176. const otherKeys = new Set(Object.keys(other));
  1177. if (!isEqual(currentKeys, otherKeys)) {
  1178. return false;
  1179. }
  1180. for (const key of currentKeys) {
  1181. const currentValue = current[key];
  1182. const otherValue = other[key];
  1183. if (key === 'field') {
  1184. if (!isFieldsSimilar(currentValue, otherValue)) {
  1185. return false;
  1186. }
  1187. } else {
  1188. const currentTarget = Array.isArray(currentValue)
  1189. ? new Set(currentValue)
  1190. : currentValue;
  1191. const otherTarget = Array.isArray(otherValue) ? new Set(otherValue) : otherValue;
  1192. if (!isEqual(currentTarget, otherTarget)) {
  1193. return false;
  1194. }
  1195. }
  1196. }
  1197. return true;
  1198. };
  1199. export function pickRelevantLocationQueryStrings(location: Location) {
  1200. const query = location.query || {};
  1201. const picked = pick(query || {}, EXTERNAL_QUERY_STRING_KEYS);
  1202. return picked;
  1203. }
  1204. export default EventView;