utils.tsx 9.9 KB

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