utils.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import {Query} from 'history';
  2. import cloneDeep from 'lodash/cloneDeep';
  3. import isEmpty from 'lodash/isEmpty';
  4. import pick from 'lodash/pick';
  5. import trimStart from 'lodash/trimStart';
  6. import * as qs from 'query-string';
  7. import WidgetArea from 'sentry-images/dashboard/widget-area.svg';
  8. import WidgetBar from 'sentry-images/dashboard/widget-bar.svg';
  9. import WidgetBigNumber from 'sentry-images/dashboard/widget-big-number.svg';
  10. import WidgetLine from 'sentry-images/dashboard/widget-line-1.svg';
  11. import WidgetTable from 'sentry-images/dashboard/widget-table.svg';
  12. import WidgetWorldMap from 'sentry-images/dashboard/widget-world-map.svg';
  13. import {parseArithmetic} from 'sentry/components/arithmeticInput/parser';
  14. import {
  15. Fidelity,
  16. getDiffInMinutes,
  17. getInterval,
  18. SIX_HOURS,
  19. TWENTY_FOUR_HOURS,
  20. } from 'sentry/components/charts/utils';
  21. import {Organization, PageFilters} from 'sentry/types';
  22. import {defined} from 'sentry/utils';
  23. import {getUtcDateString, parsePeriodToHours} from 'sentry/utils/dates';
  24. import EventView from 'sentry/utils/discover/eventView';
  25. import {
  26. getAggregateAlias,
  27. getAggregateArg,
  28. getColumnsAndAggregates,
  29. isEquation,
  30. isMeasurement,
  31. stripEquationPrefix,
  32. } from 'sentry/utils/discover/fields';
  33. import {DisplayModes} from 'sentry/utils/discover/types';
  34. import {getMeasurements} from 'sentry/utils/measurements/measurements';
  35. import {
  36. DashboardDetails,
  37. DisplayType,
  38. Widget,
  39. WidgetQuery,
  40. WidgetType,
  41. } from 'sentry/views/dashboardsV2/types';
  42. export type ValidationError = {
  43. [key: string]: string | string[] | ValidationError[] | ValidationError;
  44. };
  45. export type FlatValidationError = {
  46. [key: string]: string | FlatValidationError[] | FlatValidationError;
  47. };
  48. export function cloneDashboard(dashboard: DashboardDetails): DashboardDetails {
  49. return cloneDeep(dashboard);
  50. }
  51. export function eventViewFromWidget(
  52. title: string,
  53. query: WidgetQuery,
  54. selection: PageFilters,
  55. widgetDisplayType?: DisplayType
  56. ): EventView {
  57. const {start, end, period: statsPeriod} = selection.datetime;
  58. const {projects, environments} = selection;
  59. // World Map requires an additional column (geo.country_code) to display in discover when navigating from the widget
  60. const fields =
  61. widgetDisplayType === DisplayType.WORLD_MAP &&
  62. !query.columns.includes('geo.country_code')
  63. ? ['geo.country_code', ...query.columns, ...query.aggregates]
  64. : [...query.columns, ...query.aggregates];
  65. const conditions =
  66. widgetDisplayType === DisplayType.WORLD_MAP &&
  67. !query.conditions.includes('has:geo.country_code')
  68. ? `${query.conditions} has:geo.country_code`.trim()
  69. : query.conditions;
  70. const {orderby} = query;
  71. // Need to convert orderby to aggregate alias because eventView still uses aggregate alias format
  72. const aggregateAliasOrderBy = orderby
  73. ? `${orderby.startsWith('-') ? '-' : ''}${getAggregateAlias(trimStart(orderby, '-'))}`
  74. : orderby;
  75. return EventView.fromSavedQuery({
  76. id: undefined,
  77. name: title,
  78. version: 2,
  79. fields,
  80. query: conditions,
  81. orderby: aggregateAliasOrderBy,
  82. projects,
  83. range: statsPeriod ?? undefined,
  84. start: start ? getUtcDateString(start) : undefined,
  85. end: end ? getUtcDateString(end) : undefined,
  86. environment: environments,
  87. });
  88. }
  89. function coerceStringToArray(value?: string | string[] | null) {
  90. return typeof value === 'string' ? [value] : value;
  91. }
  92. export function constructWidgetFromQuery(query?: Query): Widget | undefined {
  93. if (query) {
  94. const queryNames = coerceStringToArray(query.queryNames);
  95. const queryConditions = coerceStringToArray(query.queryConditions);
  96. const queryFields = coerceStringToArray(query.queryFields);
  97. const queries: WidgetQuery[] = [];
  98. if (
  99. queryConditions &&
  100. queryNames &&
  101. queryFields &&
  102. typeof query.queryOrderby === 'string'
  103. ) {
  104. const {columns, aggregates} = getColumnsAndAggregates(queryFields);
  105. queryConditions.forEach((condition, index) => {
  106. queries.push({
  107. name: queryNames[index],
  108. conditions: condition,
  109. fields: queryFields,
  110. columns,
  111. aggregates,
  112. orderby: query.queryOrderby as string,
  113. });
  114. });
  115. }
  116. if (query.title && query.displayType && query.interval && queries.length > 0) {
  117. const newWidget: Widget = {
  118. ...(pick(query, ['title', 'displayType', 'interval']) as {
  119. displayType: DisplayType;
  120. interval: string;
  121. title: string;
  122. }),
  123. widgetType: WidgetType.DISCOVER,
  124. queries,
  125. };
  126. return newWidget;
  127. }
  128. }
  129. return undefined;
  130. }
  131. export function miniWidget(displayType: DisplayType): string {
  132. switch (displayType) {
  133. case DisplayType.BAR:
  134. return WidgetBar;
  135. case DisplayType.AREA:
  136. case DisplayType.TOP_N:
  137. return WidgetArea;
  138. case DisplayType.BIG_NUMBER:
  139. return WidgetBigNumber;
  140. case DisplayType.TABLE:
  141. return WidgetTable;
  142. case DisplayType.WORLD_MAP:
  143. return WidgetWorldMap;
  144. case DisplayType.LINE:
  145. default:
  146. return WidgetLine;
  147. }
  148. }
  149. export function getWidgetInterval(
  150. displayType: DisplayType,
  151. datetimeObj: Partial<PageFilters['datetime']>,
  152. widgetInterval?: string,
  153. fidelity?: Fidelity
  154. ): string {
  155. // Don't fetch more than 66 bins as we're plotting on a small area.
  156. const MAX_BIN_COUNT = 66;
  157. // Bars charts are daily totals to aligned with discover. It also makes them
  158. // usefully different from line/area charts until we expose the interval control, or remove it.
  159. let interval = displayType === 'bar' ? '1d' : widgetInterval;
  160. if (!interval) {
  161. // Default to 5 minutes
  162. interval = '5m';
  163. }
  164. const desiredPeriod = parsePeriodToHours(interval);
  165. const selectedRange = getDiffInMinutes(datetimeObj);
  166. if (fidelity) {
  167. // Primarily to support lower fidelity for Release Health widgets
  168. // the sort on releases and hit the metrics API endpoint.
  169. interval = getInterval(datetimeObj, fidelity);
  170. if (selectedRange > SIX_HOURS && selectedRange <= TWENTY_FOUR_HOURS) {
  171. interval = '1h';
  172. }
  173. return displayType === 'bar' ? '1d' : interval;
  174. }
  175. // selectedRange is in minutes, desiredPeriod is in hours
  176. // convert desiredPeriod to minutes
  177. if (selectedRange / (desiredPeriod * 60) > MAX_BIN_COUNT) {
  178. const highInterval = getInterval(datetimeObj, 'high');
  179. // Only return high fidelity interval if desired interval is higher fidelity
  180. if (desiredPeriod < parsePeriodToHours(highInterval)) {
  181. return highInterval;
  182. }
  183. }
  184. return interval;
  185. }
  186. export function getFieldsFromEquations(fields: string[]): string[] {
  187. // Gather all fields and functions used in equations and prepend them to the provided fields
  188. const termsSet: Set<string> = new Set();
  189. fields.filter(isEquation).forEach(field => {
  190. const parsed = parseArithmetic(stripEquationPrefix(field)).tc;
  191. parsed.fields.forEach(({term}) => termsSet.add(term as string));
  192. parsed.functions.forEach(({term}) => termsSet.add(term as string));
  193. });
  194. return Array.from(termsSet);
  195. }
  196. export function getWidgetDiscoverUrl(
  197. widget: Widget,
  198. selection: PageFilters,
  199. organization: Organization,
  200. index: number = 0,
  201. isMetricsData: boolean = false
  202. ) {
  203. const eventView = eventViewFromWidget(
  204. widget.title,
  205. widget.queries[index],
  206. selection,
  207. widget.displayType
  208. );
  209. const discoverLocation = eventView.getResultsViewUrlTarget(organization.slug);
  210. // Pull a max of 3 valid Y-Axis from the widget
  211. const yAxisOptions = eventView.getYAxisOptions().map(({value}) => value);
  212. discoverLocation.query.yAxis = [
  213. ...new Set(
  214. widget.queries[0].aggregates.filter(aggregate => yAxisOptions.includes(aggregate))
  215. ),
  216. ].slice(0, 3);
  217. // Visualization specific transforms
  218. switch (widget.displayType) {
  219. case DisplayType.WORLD_MAP:
  220. discoverLocation.query.display = DisplayModes.WORLDMAP;
  221. break;
  222. case DisplayType.BAR:
  223. discoverLocation.query.display = DisplayModes.BAR;
  224. break;
  225. case DisplayType.TOP_N:
  226. discoverLocation.query.display = DisplayModes.TOP5;
  227. // Last field is used as the yAxis
  228. const aggregates = widget.queries[0].aggregates;
  229. discoverLocation.query.yAxis = aggregates[aggregates.length - 1];
  230. if (aggregates.slice(0, -1).includes(aggregates[aggregates.length - 1])) {
  231. discoverLocation.query.field = aggregates.slice(0, -1);
  232. }
  233. break;
  234. default:
  235. break;
  236. }
  237. // Equation fields need to have their terms explicitly selected as columns in the discover table
  238. const fields = discoverLocation.query.field;
  239. const query = widget.queries[0];
  240. const queryFields = defined(query.fields)
  241. ? query.fields
  242. : [...query.columns, ...query.aggregates];
  243. const equationFields = getFieldsFromEquations(queryFields);
  244. // Updates fields by adding any individual terms from equation fields as a column
  245. equationFields.forEach(term => {
  246. if (Array.isArray(fields) && !fields.includes(term)) {
  247. fields.unshift(term);
  248. }
  249. });
  250. if (isMetricsData) {
  251. discoverLocation.query.fromMetric = 'true';
  252. }
  253. // Construct and return the discover url
  254. const discoverPath = `${discoverLocation.pathname}?${qs.stringify({
  255. ...discoverLocation.query,
  256. })}`;
  257. return discoverPath;
  258. }
  259. export function getWidgetIssueUrl(
  260. widget: Widget,
  261. selection: PageFilters,
  262. organization: Organization
  263. ) {
  264. const {start, end, utc, period} = selection.datetime;
  265. const datetime =
  266. start && end
  267. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  268. : {statsPeriod: period};
  269. const issuesLocation = `/organizations/${organization.slug}/issues/?${qs.stringify({
  270. query: widget.queries?.[0]?.conditions,
  271. sort: widget.queries?.[0]?.orderby,
  272. ...datetime,
  273. project: selection.projects,
  274. environment: selection.environments,
  275. })}`;
  276. return issuesLocation;
  277. }
  278. export function getWidgetReleasesUrl(
  279. _widget: Widget,
  280. selection: PageFilters,
  281. organization: Organization
  282. ) {
  283. const {start, end, utc, period} = selection.datetime;
  284. const datetime =
  285. start && end
  286. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  287. : {statsPeriod: period};
  288. const releasesLocation = `/organizations/${organization.slug}/releases/?${qs.stringify({
  289. ...datetime,
  290. project: selection.projects,
  291. environment: selection.environments,
  292. })}`;
  293. return releasesLocation;
  294. }
  295. export function flattenErrors(
  296. data: ValidationError | string,
  297. update: FlatValidationError
  298. ): FlatValidationError {
  299. if (typeof data === 'string') {
  300. update.error = data;
  301. } else {
  302. Object.keys(data).forEach((key: string) => {
  303. const value = data[key];
  304. if (typeof value === 'string') {
  305. update[key] = value;
  306. return;
  307. }
  308. // Recurse into nested objects.
  309. if (Array.isArray(value) && typeof value[0] === 'string') {
  310. update[key] = value[0];
  311. return;
  312. }
  313. if (Array.isArray(value) && typeof value[0] === 'object') {
  314. (value as ValidationError[]).map(item => flattenErrors(item, update));
  315. } else {
  316. flattenErrors(value as ValidationError, update);
  317. }
  318. });
  319. }
  320. return update;
  321. }
  322. export function getDashboardsMEPQueryParams(isMEPEnabled: boolean) {
  323. return isMEPEnabled
  324. ? {
  325. dataset: 'metricsEnhanced',
  326. }
  327. : {};
  328. }
  329. export function getNumEquations(possibleEquations: string[]) {
  330. return possibleEquations.filter(isEquation).length;
  331. }
  332. function isCustomMeasurement(field: string) {
  333. const definedMeasurements = Object.keys(getMeasurements());
  334. return isMeasurement(field) && !definedMeasurements.includes(field);
  335. }
  336. export function isCustomMeasurementWidget(widget: Widget) {
  337. return (
  338. widget.widgetType === WidgetType.DISCOVER &&
  339. widget.queries.some(({aggregates, columns, fields}) => {
  340. const aggregateArgs = aggregates.reduce((acc: string[], aggregate) => {
  341. // Should be ok to use getAggregateArg. getAggregateArg only returns the first arg
  342. // but there aren't any custom measurement aggregates that use custom measurements
  343. // outside of the first arg.
  344. const aggregateArg = getAggregateArg(aggregate);
  345. if (aggregateArg) {
  346. acc.push(aggregateArg);
  347. }
  348. return acc;
  349. }, []);
  350. return [...aggregateArgs, ...columns, ...(fields ?? [])].some(field =>
  351. isCustomMeasurement(field)
  352. );
  353. })
  354. );
  355. }
  356. export function getCustomMeasurementQueryParams() {
  357. return {
  358. dataset: 'metrics',
  359. };
  360. }
  361. export function hasSavedPageFilters(dashboard: DashboardDetails) {
  362. return !(
  363. isEmpty(dashboard.projects) &&
  364. dashboard.environment === undefined &&
  365. dashboard.start === undefined &&
  366. dashboard.end === undefined &&
  367. dashboard.period === undefined
  368. );
  369. }