utils.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. import {browserHistory} from 'react-router';
  2. import {Location, Query} from 'history';
  3. import Papa from 'papaparse';
  4. import {COL_WIDTH_UNDEFINED} from 'app/components/gridEditable';
  5. import {URL_PARAM} from 'app/constants/globalSelectionHeader';
  6. import {t} from 'app/locale';
  7. import {LightWeightOrganization, Organization, SelectValue} from 'app/types';
  8. import {Event} from 'app/types/event';
  9. import {getUtcDateString} from 'app/utils/dates';
  10. import {TableDataRow} from 'app/utils/discover/discoverQuery';
  11. import EventView from 'app/utils/discover/eventView';
  12. import {
  13. aggregateFunctionOutputType,
  14. Aggregation,
  15. AGGREGATIONS,
  16. Column,
  17. ColumnType,
  18. explodeFieldString,
  19. Field,
  20. FIELDS,
  21. getAggregateAlias,
  22. isAggregateEquation,
  23. isEquation,
  24. isMeasurement,
  25. isSpanOperationBreakdownField,
  26. measurementType,
  27. TRACING_FIELDS,
  28. } from 'app/utils/discover/fields';
  29. import {getTitle} from 'app/utils/events';
  30. import localStorage from 'app/utils/localStorage';
  31. import {tokenizeSearch} from 'app/utils/tokenizeSearch';
  32. import {FieldValue, FieldValueKind, TableColumn} from './table/types';
  33. import {ALL_VIEWS, TRANSACTION_VIEWS, WEB_VITALS_VIEWS} from './data';
  34. export type QueryWithColumnState =
  35. | Query
  36. | {
  37. field: string | string[] | null | undefined;
  38. sort: string | string[] | null | undefined;
  39. };
  40. const TEMPLATE_TABLE_COLUMN: TableColumn<React.ReactText> = {
  41. key: '',
  42. name: '',
  43. type: 'never',
  44. isSortable: false,
  45. column: Object.freeze({kind: 'field', field: ''}),
  46. width: COL_WIDTH_UNDEFINED,
  47. };
  48. // TODO(mark) these types are coupled to the gridEditable component types and
  49. // I'd prefer the types to be more general purpose but that will require a second pass.
  50. export function decodeColumnOrder(
  51. fields: Readonly<Field[]>
  52. ): TableColumn<React.ReactText>[] {
  53. let equations = 0;
  54. return fields.map((f: Field) => {
  55. const column: TableColumn<React.ReactText> = {...TEMPLATE_TABLE_COLUMN};
  56. const col = explodeFieldString(f.field);
  57. let columnName = f.field;
  58. if (isEquation(f.field)) {
  59. columnName = `equation[${equations}]`;
  60. equations += 1;
  61. }
  62. column.key = columnName;
  63. column.name = columnName;
  64. column.width = f.width || COL_WIDTH_UNDEFINED;
  65. if (col.kind === 'function') {
  66. // Aggregations can have a strict outputType or they can inherit from their field.
  67. // Otherwise use the FIELDS data to infer types.
  68. const outputType = aggregateFunctionOutputType(col.function[0], col.function[1]);
  69. if (outputType !== null) {
  70. column.type = outputType;
  71. }
  72. const aggregate = AGGREGATIONS[col.function[0]];
  73. column.isSortable = aggregate && aggregate.isSortable;
  74. } else if (col.kind === 'field') {
  75. if (FIELDS.hasOwnProperty(col.field)) {
  76. column.type = FIELDS[col.field];
  77. } else if (isMeasurement(col.field)) {
  78. column.type = measurementType(col.field);
  79. } else if (isSpanOperationBreakdownField(col.field)) {
  80. column.type = 'duration';
  81. }
  82. }
  83. column.column = col;
  84. return column;
  85. });
  86. }
  87. export function pushEventViewToLocation(props: {
  88. location: Location;
  89. nextEventView: EventView;
  90. extraQuery?: Query;
  91. }) {
  92. const {location, nextEventView} = props;
  93. const extraQuery = props.extraQuery || {};
  94. const queryStringObject = nextEventView.generateQueryStringObject();
  95. browserHistory.push({
  96. ...location,
  97. query: {
  98. ...extraQuery,
  99. ...queryStringObject,
  100. },
  101. });
  102. }
  103. export function generateTitle({
  104. eventView,
  105. event,
  106. organization,
  107. }: {
  108. eventView: EventView;
  109. event?: Event;
  110. organization?: Organization;
  111. }) {
  112. const titles = [t('Discover')];
  113. const eventViewName = eventView.name;
  114. if (typeof eventViewName === 'string' && String(eventViewName).trim().length > 0) {
  115. titles.push(String(eventViewName).trim());
  116. }
  117. const eventTitle = event ? getTitle(event, organization?.features).title : undefined;
  118. if (eventTitle) {
  119. titles.push(eventTitle);
  120. }
  121. titles.reverse();
  122. return titles.join(' - ');
  123. }
  124. export function getPrebuiltQueries(organization: LightWeightOrganization) {
  125. const views = [...ALL_VIEWS];
  126. if (organization.features.includes('performance-view')) {
  127. // insert transactions queries at index 2
  128. views.splice(2, 0, ...TRANSACTION_VIEWS);
  129. views.push(...WEB_VITALS_VIEWS);
  130. }
  131. return views;
  132. }
  133. function disableMacros(value: string | null | boolean | number) {
  134. const unsafeCharacterRegex = /^[\=\+\-\@]/;
  135. if (typeof value === 'string' && `${value}`.match(unsafeCharacterRegex)) {
  136. return `'${value}`;
  137. }
  138. return value;
  139. }
  140. export function downloadAsCsv(tableData, columnOrder, filename) {
  141. const {data} = tableData;
  142. const headings = columnOrder.map(column => column.name);
  143. const csvContent = Papa.unparse({
  144. fields: headings,
  145. data: data.map(row =>
  146. headings.map(col => {
  147. col = getAggregateAlias(col);
  148. return disableMacros(row[col]);
  149. })
  150. ),
  151. });
  152. // Need to also manually replace # since encodeURI skips them
  153. const encodedDataUrl = `data:text/csv;charset=utf8,${encodeURIComponent(csvContent)}`;
  154. // Create a download link then click it, this is so we can get a filename
  155. const link = document.createElement('a');
  156. const now = new Date();
  157. link.setAttribute('href', encodedDataUrl);
  158. link.setAttribute('download', `${filename} ${getUtcDateString(now)}.csv`);
  159. link.click();
  160. link.remove();
  161. // Make testing easier
  162. return encodedDataUrl;
  163. }
  164. const ALIASED_AGGREGATES_COLUMN = {
  165. last_seen: 'timestamp',
  166. failure_count: 'transaction.status',
  167. };
  168. /**
  169. * Convert an aggregate into the resulting column from a drilldown action.
  170. * The result is null if the drilldown results in the aggregate being removed.
  171. */
  172. function drilldownAggregate(
  173. func: Extract<Column, {kind: 'function'}>
  174. ): Extract<Column, {kind: 'field'}> | null {
  175. const key = func.function[0];
  176. const aggregation = AGGREGATIONS[key];
  177. let column = func.function[1];
  178. if (ALIASED_AGGREGATES_COLUMN.hasOwnProperty(key)) {
  179. // Some aggregates are just shortcuts to other aggregates with
  180. // predefined arguments so we can directly map them to the result.
  181. column = ALIASED_AGGREGATES_COLUMN[key];
  182. } else if (aggregation?.parameters?.[0]) {
  183. const parameter = aggregation.parameters[0];
  184. if (parameter.kind !== 'column') {
  185. // The aggregation does not accept a column as a parameter,
  186. // so we clear the column.
  187. column = '';
  188. } else if (!column && parameter.required === false) {
  189. // The parameter was not given for a non-required parameter,
  190. // so we fall back to the default.
  191. column = parameter.defaultValue;
  192. }
  193. } else {
  194. // The aggregation does not exist or does not have any parameters,
  195. // so we clear the column.
  196. column = '';
  197. }
  198. return column ? {kind: 'field', field: column} : null;
  199. }
  200. /**
  201. * Convert an aggregated query into one that does not have aggregates.
  202. * Will also apply additions conditions defined in `additionalConditions`
  203. * and generate conditions based on the `dataRow` parameter and the current fields
  204. * in the `eventView`.
  205. */
  206. export function getExpandedResults(
  207. eventView: EventView,
  208. additionalConditions: Record<string, string>,
  209. dataRow?: TableDataRow | Event
  210. ): EventView {
  211. const fieldSet = new Set();
  212. // Expand any functions in the resulting column, and dedupe the result.
  213. // Mark any column as null to remove it.
  214. const expandedColumns: (Column | null)[] = eventView.fields.map((field: Field) => {
  215. const exploded = explodeFieldString(field.field);
  216. const column = exploded.kind === 'function' ? drilldownAggregate(exploded) : exploded;
  217. if (
  218. // if expanding the function failed
  219. column === null ||
  220. // the new column is already present
  221. fieldSet.has(column.field) ||
  222. // Skip aggregate equations, their functions will already be added so we just want to remove it
  223. isAggregateEquation(field.field)
  224. ) {
  225. return null;
  226. }
  227. fieldSet.add(column.field);
  228. return column;
  229. });
  230. // id should be default column when expanded results in no columns; but only if
  231. // the Discover query's columns is non-empty.
  232. // This typically occurs in Discover drilldowns.
  233. if (fieldSet.size === 0 && expandedColumns.length) {
  234. expandedColumns[0] = {kind: 'field', field: 'id'};
  235. }
  236. // update the columns according the the expansion above
  237. const nextView = expandedColumns.reduceRight(
  238. (newView, column, index) =>
  239. column === null
  240. ? newView.withDeletedColumn(index, undefined)
  241. : newView.withUpdatedColumn(index, column, undefined),
  242. eventView.clone()
  243. );
  244. nextView.query = generateExpandedConditions(nextView, additionalConditions, dataRow);
  245. return nextView;
  246. }
  247. /**
  248. * Create additional conditions based on the fields in an EventView
  249. * and a datarow/event
  250. */
  251. function generateAdditionalConditions(
  252. eventView: EventView,
  253. dataRow?: TableDataRow | Event
  254. ): Record<string, string | string[]> {
  255. const specialKeys = Object.values(URL_PARAM);
  256. const conditions: Record<string, string | string[]> = {};
  257. if (!dataRow) {
  258. return conditions;
  259. }
  260. eventView.fields.forEach((field: Field) => {
  261. const column = explodeFieldString(field.field);
  262. // Skip aggregate fields
  263. if (column.kind === 'function') {
  264. return;
  265. }
  266. const dataKey = getAggregateAlias(field.field);
  267. // Append the current field as a condition if it exists in the dataRow
  268. // Or is a simple key in the event. More complex deeply nested fields are
  269. // more challenging to get at as their location in the structure does not
  270. // match their name.
  271. if (dataRow.hasOwnProperty(dataKey)) {
  272. let value = dataRow[dataKey];
  273. if (Array.isArray(value)) {
  274. if (value.length > 1) {
  275. conditions[column.field] = value;
  276. return;
  277. } else {
  278. // An array with only one value is equivalent to the value itself.
  279. value = value[0];
  280. }
  281. }
  282. // if the value will be quoted, then do not trim it as the whitespaces
  283. // may be important to the query and should not be trimmed
  284. const shouldQuote =
  285. value === null || value === undefined
  286. ? false
  287. : /[\s\(\)\\"]/g.test(String(value).trim());
  288. const nextValue =
  289. value === null || value === undefined
  290. ? ''
  291. : shouldQuote
  292. ? String(value)
  293. : String(value).trim();
  294. if (isMeasurement(column.field) && !nextValue) {
  295. // Do not add measurement conditions if nextValue is falsey.
  296. // It's expected that nextValue is a numeric value.
  297. return;
  298. }
  299. switch (column.field) {
  300. case 'timestamp':
  301. // normalize the "timestamp" field to ensure the payload works
  302. conditions[column.field] = getUtcDateString(nextValue);
  303. break;
  304. default:
  305. conditions[column.field] = nextValue;
  306. }
  307. }
  308. // If we have an event, check tags as well.
  309. if (dataRow.tags && Array.isArray(dataRow.tags)) {
  310. const tagIndex = dataRow.tags.findIndex(item => item.key === dataKey);
  311. if (tagIndex > -1) {
  312. const key = specialKeys.includes(column.field)
  313. ? `tags[${column.field}]`
  314. : column.field;
  315. const tagValue = dataRow.tags[tagIndex].value;
  316. conditions[key] = tagValue;
  317. }
  318. }
  319. });
  320. return conditions;
  321. }
  322. function generateExpandedConditions(
  323. eventView: EventView,
  324. additionalConditions: Record<string, string>,
  325. dataRow?: TableDataRow | Event
  326. ): string {
  327. const parsedQuery = tokenizeSearch(eventView.query);
  328. // Remove any aggregates from the search conditions.
  329. // otherwise, it'll lead to an invalid query result.
  330. for (const key in parsedQuery.tagValues) {
  331. const column = explodeFieldString(key);
  332. if (column.kind === 'function') {
  333. parsedQuery.removeTag(key);
  334. }
  335. }
  336. const conditions: Record<string, string | string[]> = Object.assign(
  337. {},
  338. additionalConditions,
  339. generateAdditionalConditions(eventView, dataRow)
  340. );
  341. // Add additional conditions provided and generated.
  342. for (const key in conditions) {
  343. const value = conditions[key];
  344. if (Array.isArray(value)) {
  345. parsedQuery.setTagValues(key, value);
  346. continue;
  347. }
  348. if (key === 'project.id') {
  349. eventView.project = [...eventView.project, parseInt(value, 10)];
  350. continue;
  351. }
  352. if (key === 'environment') {
  353. if (!eventView.environment.includes(value)) {
  354. eventView.environment = [...eventView.environment, value];
  355. }
  356. continue;
  357. }
  358. const column = explodeFieldString(key);
  359. // Skip aggregates as they will be invalid.
  360. if (column.kind === 'function') {
  361. continue;
  362. }
  363. parsedQuery.setTagValues(key, [value]);
  364. }
  365. return parsedQuery.formatString();
  366. }
  367. type FieldGeneratorOpts = {
  368. organization: LightWeightOrganization;
  369. tagKeys?: string[] | null;
  370. measurementKeys?: string[] | null;
  371. spanOperationBreakdownKeys?: string[];
  372. aggregations?: Record<string, Aggregation>;
  373. fields?: Record<string, ColumnType>;
  374. };
  375. export function generateFieldOptions({
  376. organization,
  377. tagKeys,
  378. measurementKeys,
  379. spanOperationBreakdownKeys,
  380. aggregations = AGGREGATIONS,
  381. fields = FIELDS,
  382. }: FieldGeneratorOpts) {
  383. let fieldKeys = Object.keys(fields);
  384. let functions = Object.keys(aggregations);
  385. // Strip tracing features if the org doesn't have access.
  386. if (!organization.features.includes('performance-view')) {
  387. fieldKeys = fieldKeys.filter(item => !TRACING_FIELDS.includes(item));
  388. functions = functions.filter(item => !TRACING_FIELDS.includes(item));
  389. }
  390. // Feature flagged by arithmetic for now
  391. if (!organization.features.includes('discover-arithmetic')) {
  392. functions = functions.filter(item => item !== 'count_if');
  393. }
  394. const fieldOptions: Record<string, SelectValue<FieldValue>> = {};
  395. // Index items by prefixed keys as custom tags can overlap both fields and
  396. // function names. Having a mapping makes finding the value objects easier
  397. // later as well.
  398. functions.forEach(func => {
  399. const ellipsis = aggregations[func].parameters.length ? '\u2026' : '';
  400. const parameters = aggregations[func].parameters.map(param => {
  401. const overrides = AGGREGATIONS[func].getFieldOverrides;
  402. if (typeof overrides === 'undefined') {
  403. return param;
  404. }
  405. return {
  406. ...param,
  407. ...overrides({parameter: param, organization}),
  408. };
  409. });
  410. fieldOptions[`function:${func}`] = {
  411. label: `${func}(${ellipsis})`,
  412. value: {
  413. kind: FieldValueKind.FUNCTION,
  414. meta: {
  415. name: func,
  416. parameters,
  417. },
  418. },
  419. };
  420. });
  421. fieldKeys.forEach(field => {
  422. fieldOptions[`field:${field}`] = {
  423. label: field,
  424. value: {
  425. kind: FieldValueKind.FIELD,
  426. meta: {
  427. name: field,
  428. dataType: fields[field],
  429. },
  430. },
  431. };
  432. });
  433. if (tagKeys !== undefined && tagKeys !== null) {
  434. tagKeys.forEach(tag => {
  435. const tagValue =
  436. fields.hasOwnProperty(tag) || AGGREGATIONS.hasOwnProperty(tag)
  437. ? `tags[${tag}]`
  438. : tag;
  439. fieldOptions[`tag:${tag}`] = {
  440. label: tag,
  441. value: {
  442. kind: FieldValueKind.TAG,
  443. meta: {name: tagValue, dataType: 'string'},
  444. },
  445. };
  446. });
  447. }
  448. if (measurementKeys !== undefined && measurementKeys !== null) {
  449. measurementKeys.forEach(measurement => {
  450. fieldOptions[`measurement:${measurement}`] = {
  451. label: measurement,
  452. value: {
  453. kind: FieldValueKind.MEASUREMENT,
  454. meta: {name: measurement, dataType: measurementType(measurement)},
  455. },
  456. };
  457. });
  458. }
  459. if (Array.isArray(spanOperationBreakdownKeys)) {
  460. spanOperationBreakdownKeys.forEach(breakdownField => {
  461. fieldOptions[`span_op_breakdown:${breakdownField}`] = {
  462. label: breakdownField,
  463. value: {
  464. kind: FieldValueKind.BREAKDOWN,
  465. meta: {name: breakdownField, dataType: 'duration'},
  466. },
  467. };
  468. });
  469. }
  470. return fieldOptions;
  471. }
  472. const RENDER_PREBUILT_KEY = 'discover-render-prebuilt';
  473. export function shouldRenderPrebuilt(): boolean {
  474. const shouldRender = localStorage.getItem(RENDER_PREBUILT_KEY);
  475. return shouldRender === 'true' || shouldRender === null;
  476. }
  477. export function setRenderPrebuilt(value: boolean) {
  478. localStorage.setItem(RENDER_PREBUILT_KEY, value ? 'true' : 'false');
  479. }