index.tsx 19 KB

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