index.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. import {Component, Fragment} from 'react';
  2. import type {WithRouterProps} from 'react-router';
  3. import type {useSortable} from '@dnd-kit/sortable';
  4. import styled from '@emotion/styled';
  5. import type {Location} from 'history';
  6. import type {Client} from 'sentry/api';
  7. import {Alert} from 'sentry/components/alert';
  8. import ErrorPanel from 'sentry/components/charts/errorPanel';
  9. import {HeaderTitle} from 'sentry/components/charts/styles';
  10. import ErrorBoundary from 'sentry/components/errorBoundary';
  11. import {LazyRender} from 'sentry/components/lazyRender';
  12. import ExternalLink from 'sentry/components/links/externalLink';
  13. import Panel from 'sentry/components/panels/panel';
  14. import PanelAlert from 'sentry/components/panels/panelAlert';
  15. import Placeholder from 'sentry/components/placeholder';
  16. import {parseSearch} from 'sentry/components/searchSyntax/parser';
  17. import {Tooltip} from 'sentry/components/tooltip';
  18. import {IconWarning} from 'sentry/icons';
  19. import {t, tct} from 'sentry/locale';
  20. import {space} from 'sentry/styles/space';
  21. import type {Organization, PageFilters} from 'sentry/types';
  22. import type {Series} from 'sentry/types/echarts';
  23. import {getFormattedDate} from 'sentry/utils/dates';
  24. import type {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
  25. import type {AggregationOutputType} from 'sentry/utils/discover/fields';
  26. import {parseFunction} from 'sentry/utils/discover/fields';
  27. import {
  28. hasCustomMetrics,
  29. hasCustomMetricsExtractionRules,
  30. } from 'sentry/utils/metrics/features';
  31. import {VirtualMetricsContextProvider} from 'sentry/utils/metrics/virtualMetricsContext';
  32. import {hasOnDemandMetricWidgetFeature} from 'sentry/utils/onDemandMetrics/features';
  33. import {ExtractedMetricsTag} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext';
  34. import {
  35. MEPConsumer,
  36. MEPState,
  37. } from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  38. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  39. import useOrganization from 'sentry/utils/useOrganization';
  40. import withApi from 'sentry/utils/withApi';
  41. import withOrganization from 'sentry/utils/withOrganization';
  42. import withPageFilters from 'sentry/utils/withPageFilters';
  43. // eslint-disable-next-line no-restricted-imports
  44. import withSentryRouter from 'sentry/utils/withSentryRouter';
  45. import {DASHBOARD_CHART_GROUP} from 'sentry/views/dashboards/dashboard';
  46. import {MetricWidgetCard} from 'sentry/views/dashboards/metrics/widgetCard';
  47. import {Toolbar} from 'sentry/views/dashboards/widgetCard/toolbar';
  48. import type {DashboardFilters, Widget} from '../types';
  49. import {DisplayType, OnDemandExtractionState, WidgetType} from '../types';
  50. import {getColoredWidgetIndicator, hasThresholdMaxValue} from '../utils';
  51. import {DEFAULT_RESULTS_LIMIT} from '../widgetBuilder/utils';
  52. import {DashboardsMEPConsumer, DashboardsMEPProvider} from './dashboardsMEPContext';
  53. import WidgetCardChartContainer from './widgetCardChartContainer';
  54. import WidgetCardContextMenu from './widgetCardContextMenu';
  55. const SESSION_DURATION_INGESTION_STOP_DATE = new Date('2023-01-12');
  56. export const SESSION_DURATION_ALERT = (
  57. <PanelAlert type="warning">
  58. {t(
  59. 'session.duration is no longer being recorded as of %s. Data in this widget may be incomplete.',
  60. getFormattedDate(SESSION_DURATION_INGESTION_STOP_DATE, 'MMM D, YYYY')
  61. )}
  62. </PanelAlert>
  63. );
  64. type DraggableProps = Pick<ReturnType<typeof useSortable>, 'attributes' | 'listeners'>;
  65. type Props = WithRouterProps & {
  66. api: Client;
  67. isEditingDashboard: boolean;
  68. location: Location;
  69. organization: Organization;
  70. selection: PageFilters;
  71. widget: Widget;
  72. widgetLimitReached: boolean;
  73. dashboardFilters?: DashboardFilters;
  74. draggableProps?: DraggableProps;
  75. hideToolbar?: boolean;
  76. index?: string;
  77. isEditingWidget?: boolean;
  78. isMobile?: boolean;
  79. isPreview?: boolean;
  80. isWidgetInvalid?: boolean;
  81. noDashboardsMEPProvider?: boolean;
  82. noLazyLoad?: boolean;
  83. onDataFetched?: (results: TableDataWithTitle[]) => void;
  84. onDelete?: () => void;
  85. onDuplicate?: () => void;
  86. onEdit?: () => void;
  87. onUpdate?: (widget: Widget | null) => void;
  88. onWidgetSplitDecision?: (splitDecision: WidgetType) => void;
  89. renderErrorMessage?: (errorMessage?: string) => React.ReactNode;
  90. showContextMenu?: boolean;
  91. showStoredAlert?: boolean;
  92. tableItemLimit?: number;
  93. windowWidth?: number;
  94. };
  95. type State = {
  96. pageLinks?: string;
  97. seriesData?: Series[];
  98. seriesResultsType?: Record<string, AggregationOutputType>;
  99. tableData?: TableDataWithTitle[];
  100. totalIssuesCount?: string;
  101. };
  102. type SearchFilterKey = {key?: {value: string}};
  103. const ERROR_FIELDS = [
  104. 'error.handled',
  105. 'error.unhandled',
  106. 'error.mechanism',
  107. 'error.type',
  108. 'error.value',
  109. ];
  110. class WidgetCard extends Component<Props, State> {
  111. state: State = {};
  112. renderToolbar() {
  113. const {
  114. onEdit,
  115. onDelete,
  116. onDuplicate,
  117. draggableProps,
  118. hideToolbar,
  119. isEditingDashboard,
  120. isMobile,
  121. } = this.props;
  122. if (!isEditingDashboard) {
  123. return null;
  124. }
  125. return (
  126. <Toolbar
  127. onEdit={onEdit}
  128. onDelete={onDelete}
  129. onDuplicate={onDuplicate}
  130. draggableProps={draggableProps}
  131. hideToolbar={hideToolbar}
  132. isMobile={isMobile}
  133. />
  134. );
  135. }
  136. renderContextMenu() {
  137. const {
  138. widget,
  139. selection,
  140. organization,
  141. showContextMenu,
  142. isPreview,
  143. widgetLimitReached,
  144. onEdit,
  145. onDuplicate,
  146. onDelete,
  147. isEditingDashboard,
  148. router,
  149. location,
  150. index,
  151. } = this.props;
  152. const {seriesData, tableData, pageLinks, totalIssuesCount, seriesResultsType} =
  153. this.state;
  154. if (isEditingDashboard) {
  155. return null;
  156. }
  157. return (
  158. <WidgetCardContextMenu
  159. organization={organization}
  160. widget={widget}
  161. selection={selection}
  162. showContextMenu={showContextMenu}
  163. isPreview={isPreview}
  164. widgetLimitReached={widgetLimitReached}
  165. onDuplicate={onDuplicate}
  166. onEdit={onEdit}
  167. onDelete={onDelete}
  168. router={router}
  169. location={location}
  170. index={index}
  171. seriesData={seriesData}
  172. seriesResultsType={seriesResultsType}
  173. tableData={tableData}
  174. pageLinks={pageLinks}
  175. totalIssuesCount={totalIssuesCount}
  176. />
  177. );
  178. }
  179. setData = ({
  180. tableResults,
  181. timeseriesResults,
  182. totalIssuesCount,
  183. pageLinks,
  184. timeseriesResultsTypes,
  185. }: {
  186. pageLinks?: string;
  187. tableResults?: TableDataWithTitle[];
  188. timeseriesResults?: Series[];
  189. timeseriesResultsTypes?: Record<string, AggregationOutputType>;
  190. totalIssuesCount?: string;
  191. }) => {
  192. const {onDataFetched} = this.props;
  193. if (onDataFetched && tableResults) {
  194. onDataFetched(tableResults);
  195. }
  196. this.setState({
  197. seriesData: timeseriesResults,
  198. tableData: tableResults,
  199. totalIssuesCount,
  200. pageLinks,
  201. seriesResultsType: timeseriesResultsTypes,
  202. });
  203. };
  204. render() {
  205. const {
  206. api,
  207. organization,
  208. selection,
  209. widget,
  210. isMobile,
  211. renderErrorMessage,
  212. tableItemLimit,
  213. windowWidth,
  214. noLazyLoad,
  215. showStoredAlert,
  216. noDashboardsMEPProvider,
  217. dashboardFilters,
  218. isWidgetInvalid,
  219. location,
  220. onWidgetSplitDecision,
  221. } = this.props;
  222. if (widget.displayType === DisplayType.TOP_N) {
  223. const queries = widget.queries.map(query => ({
  224. ...query,
  225. // Use the last aggregate because that's where the y-axis is stored
  226. aggregates: query.aggregates.length
  227. ? [query.aggregates[query.aggregates.length - 1]]
  228. : [],
  229. }));
  230. widget.queries = queries;
  231. widget.limit = DEFAULT_RESULTS_LIMIT;
  232. }
  233. const hasSessionDuration = widget.queries.some(query =>
  234. query.aggregates.some(aggregate => aggregate.includes('session.duration'))
  235. );
  236. function conditionalWrapWithDashboardsMEPProvider(component: React.ReactNode) {
  237. if (noDashboardsMEPProvider) {
  238. return component;
  239. }
  240. return <DashboardsMEPProvider>{component}</DashboardsMEPProvider>;
  241. }
  242. // prettier-ignore
  243. const widgetContainsErrorFields = widget.queries.some(
  244. ({columns, aggregates, conditions}) =>
  245. ERROR_FIELDS.some(
  246. errorField =>
  247. columns.includes(errorField) ||
  248. aggregates.some(
  249. aggregate => parseFunction(aggregate)?.arguments.includes(errorField)
  250. ) ||
  251. parseSearch(conditions)?.some(
  252. filter => (filter as SearchFilterKey).key?.value === errorField
  253. )
  254. )
  255. );
  256. if (widget.widgetType === WidgetType.METRICS) {
  257. if (hasCustomMetrics(organization)) {
  258. return hasCustomMetricsExtractionRules(organization) ? (
  259. <VirtualMetricsContextProvider>
  260. <MetricWidgetCard
  261. index={this.props.index}
  262. isEditingDashboard={this.props.isEditingDashboard}
  263. onEdit={this.props.onEdit}
  264. onDelete={this.props.onDelete}
  265. onDuplicate={this.props.onDuplicate}
  266. router={this.props.router}
  267. location={this.props.location}
  268. organization={organization}
  269. selection={selection}
  270. widget={widget}
  271. dashboardFilters={dashboardFilters}
  272. renderErrorMessage={renderErrorMessage}
  273. showContextMenu={this.props.showContextMenu}
  274. />
  275. </VirtualMetricsContextProvider>
  276. ) : (
  277. <MetricWidgetCard
  278. index={this.props.index}
  279. isEditingDashboard={this.props.isEditingDashboard}
  280. onEdit={this.props.onEdit}
  281. onDelete={this.props.onDelete}
  282. onDuplicate={this.props.onDuplicate}
  283. router={this.props.router}
  284. location={this.props.location}
  285. organization={organization}
  286. selection={selection}
  287. widget={widget}
  288. dashboardFilters={dashboardFilters}
  289. renderErrorMessage={renderErrorMessage}
  290. showContextMenu={this.props.showContextMenu}
  291. />
  292. );
  293. }
  294. }
  295. return (
  296. <ErrorBoundary
  297. customComponent={<ErrorCard>{t('Error loading widget data')}</ErrorCard>}
  298. >
  299. {conditionalWrapWithDashboardsMEPProvider(
  300. <Fragment>
  301. <VisuallyCompleteWithData
  302. id="DashboardList-FirstWidgetCard"
  303. hasData={
  304. ((this.state.tableData?.length || this.state.seriesData?.length) ?? 0) > 0
  305. }
  306. disabled={Number(this.props.index) !== 0}
  307. >
  308. <WidgetCardPanel isDragging={false}>
  309. <WidgetHeaderWrapper>
  310. <WidgetHeaderDescription>
  311. <WidgetTitleRow>
  312. <Tooltip
  313. title={widget.title}
  314. containerDisplayMode="grid"
  315. showOnlyOnOverflow
  316. >
  317. <WidgetTitle>{widget.title}</WidgetTitle>
  318. </Tooltip>
  319. {widget.thresholds &&
  320. hasThresholdMaxValue(widget.thresholds) &&
  321. this.state.tableData &&
  322. organization.features.includes('dashboard-widget-indicators') &&
  323. getColoredWidgetIndicator(
  324. widget.thresholds,
  325. this.state.tableData
  326. )}
  327. <ExtractedMetricsTag queryKey={widget} />
  328. <DisplayOnDemandWarnings widget={widget} />
  329. </WidgetTitleRow>
  330. {widget.description && (
  331. <Tooltip
  332. title={widget.description}
  333. containerDisplayMode="grid"
  334. showOnlyOnOverflow
  335. isHoverable
  336. >
  337. <WidgetDescription>{widget.description}</WidgetDescription>
  338. </Tooltip>
  339. )}
  340. </WidgetHeaderDescription>
  341. {this.renderContextMenu()}
  342. </WidgetHeaderWrapper>
  343. {hasSessionDuration && SESSION_DURATION_ALERT}
  344. {isWidgetInvalid ? (
  345. <Fragment>
  346. {renderErrorMessage?.('Widget query condition is invalid.')}
  347. <StyledErrorPanel>
  348. <IconWarning color="gray500" size="lg" />
  349. </StyledErrorPanel>
  350. </Fragment>
  351. ) : noLazyLoad ? (
  352. <WidgetCardChartContainer
  353. location={location}
  354. api={api}
  355. organization={organization}
  356. selection={selection}
  357. widget={widget}
  358. isMobile={isMobile}
  359. renderErrorMessage={renderErrorMessage}
  360. tableItemLimit={tableItemLimit}
  361. windowWidth={windowWidth}
  362. onDataFetched={this.setData}
  363. dashboardFilters={dashboardFilters}
  364. chartGroup={DASHBOARD_CHART_GROUP}
  365. onWidgetSplitDecision={onWidgetSplitDecision}
  366. />
  367. ) : (
  368. <LazyRender containerHeight={200} withoutContainer>
  369. <WidgetCardChartContainer
  370. location={location}
  371. api={api}
  372. organization={organization}
  373. selection={selection}
  374. widget={widget}
  375. isMobile={isMobile}
  376. renderErrorMessage={renderErrorMessage}
  377. tableItemLimit={tableItemLimit}
  378. windowWidth={windowWidth}
  379. onDataFetched={this.setData}
  380. dashboardFilters={dashboardFilters}
  381. chartGroup={DASHBOARD_CHART_GROUP}
  382. onWidgetSplitDecision={onWidgetSplitDecision}
  383. />
  384. </LazyRender>
  385. )}
  386. {this.renderToolbar()}
  387. </WidgetCardPanel>
  388. </VisuallyCompleteWithData>
  389. {!organization.features.includes('performance-mep-bannerless-ui') && (
  390. <MEPConsumer>
  391. {metricSettingContext => {
  392. return (
  393. <DashboardsMEPConsumer>
  394. {({isMetricsData}) => {
  395. if (
  396. showStoredAlert &&
  397. isMetricsData === false &&
  398. widget.widgetType === WidgetType.DISCOVER &&
  399. metricSettingContext &&
  400. metricSettingContext.metricSettingState !==
  401. MEPState.TRANSACTIONS_ONLY
  402. ) {
  403. if (!widgetContainsErrorFields) {
  404. return (
  405. <StoredDataAlert showIcon>
  406. {tct(
  407. "Your selection is only applicable to [indexedData: indexed event data]. We've automatically adjusted your results.",
  408. {
  409. indexedData: (
  410. <ExternalLink href="https://docs.sentry.io/product/dashboards/widget-builder/#errors--transactions" />
  411. ),
  412. }
  413. )}
  414. </StoredDataAlert>
  415. );
  416. }
  417. }
  418. return null;
  419. }}
  420. </DashboardsMEPConsumer>
  421. );
  422. }}
  423. </MEPConsumer>
  424. )}
  425. </Fragment>
  426. )}
  427. </ErrorBoundary>
  428. );
  429. }
  430. }
  431. export default withApi(withOrganization(withPageFilters(withSentryRouter(WidgetCard))));
  432. function DisplayOnDemandWarnings(props: {widget: Widget}) {
  433. const organization = useOrganization();
  434. if (!hasOnDemandMetricWidgetFeature(organization)) {
  435. return null;
  436. }
  437. // prettier-ignore
  438. const widgetContainsHighCardinality = props.widget.queries.some(
  439. wq =>
  440. wq.onDemand?.some(
  441. d => d.extractionState === OnDemandExtractionState.DISABLED_HIGH_CARDINALITY
  442. )
  443. );
  444. // prettier-ignore
  445. const widgetReachedSpecLimit = props.widget.queries.some(
  446. wq =>
  447. wq.onDemand?.some(
  448. d => d.extractionState === OnDemandExtractionState.DISABLED_SPEC_LIMIT
  449. )
  450. );
  451. if (widgetContainsHighCardinality) {
  452. return (
  453. <Tooltip
  454. containerDisplayMode="inline-flex"
  455. title={t(
  456. 'This widget is using indexed data because it has a column with too many unique values.'
  457. )}
  458. >
  459. <IconWarning color="warningText" />
  460. </Tooltip>
  461. );
  462. }
  463. if (widgetReachedSpecLimit) {
  464. return (
  465. <Tooltip
  466. containerDisplayMode="inline-flex"
  467. title={t(
  468. "This widget is using indexed data because you've reached your organization limit for dynamically extracted metrics."
  469. )}
  470. >
  471. <IconWarning color="warningText" />
  472. </Tooltip>
  473. );
  474. }
  475. return null;
  476. }
  477. const ErrorCard = styled(Placeholder)`
  478. display: flex;
  479. align-items: center;
  480. justify-content: center;
  481. background-color: ${p => p.theme.alert.error.backgroundLight};
  482. border: 1px solid ${p => p.theme.alert.error.border};
  483. color: ${p => p.theme.alert.error.textLight};
  484. border-radius: ${p => p.theme.borderRadius};
  485. margin-bottom: ${space(2)};
  486. `;
  487. export const WidgetCardPanel = styled(Panel, {
  488. shouldForwardProp: prop => prop !== 'isDragging',
  489. })<{
  490. isDragging: boolean;
  491. }>`
  492. margin: 0;
  493. visibility: ${p => (p.isDragging ? 'hidden' : 'visible')};
  494. /* If a panel overflows due to a long title stretch its grid sibling */
  495. height: 100%;
  496. min-height: 96px;
  497. display: flex;
  498. flex-direction: column;
  499. `;
  500. const StoredDataAlert = styled(Alert)`
  501. margin-top: ${space(1)};
  502. margin-bottom: 0;
  503. `;
  504. const StyledErrorPanel = styled(ErrorPanel)`
  505. padding: ${space(2)};
  506. `;
  507. export const WidgetTitleRow = styled('span')`
  508. display: flex;
  509. align-items: center;
  510. gap: ${space(0.75)};
  511. `;
  512. export const WidgetDescription = styled('small')`
  513. ${p => p.theme.overflowEllipsis}
  514. color: ${p => p.theme.gray300};
  515. `;
  516. const WidgetTitle = styled(HeaderTitle)`
  517. ${p => p.theme.overflowEllipsis};
  518. font-weight: ${p => p.theme.fontWeightNormal};
  519. `;
  520. const WidgetHeaderWrapper = styled('div')`
  521. padding: ${space(2)} ${space(1)} 0 ${space(3)};
  522. min-height: 36px;
  523. width: 100%;
  524. display: flex;
  525. align-items: center;
  526. justify-content: space-between;
  527. `;
  528. const WidgetHeaderDescription = styled('div')`
  529. display: flex;
  530. flex-direction: column;
  531. gap: ${space(0.5)};
  532. `;