index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. import {Component} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {LocationDescriptorObject} from 'history';
  4. import omit from 'lodash/omit';
  5. import pick from 'lodash/pick';
  6. import moment from 'moment-timezone';
  7. import type {DateTimeObject} from 'sentry/components/charts/utils';
  8. import {CompactSelect} from 'sentry/components/compactSelect';
  9. import ErrorBoundary from 'sentry/components/errorBoundary';
  10. import HookOrDefault from 'sentry/components/hookOrDefault';
  11. import * as Layout from 'sentry/components/layouts/thirds';
  12. import ExternalLink from 'sentry/components/links/externalLink';
  13. import NoProjectMessage from 'sentry/components/noProjectMessage';
  14. import {DatePageFilter} from 'sentry/components/organizations/datePageFilter';
  15. import PageFilterBar from 'sentry/components/organizations/pageFilterBar';
  16. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  17. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  18. import {ProjectPageFilter} from 'sentry/components/organizations/projectPageFilter';
  19. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  20. import {DATA_CATEGORY_INFO, DEFAULT_STATS_PERIOD} from 'sentry/constants';
  21. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  22. import {t, tct} from 'sentry/locale';
  23. import ConfigStore from 'sentry/stores/configStore';
  24. import {space} from 'sentry/styles/space';
  25. import {
  26. DataCategoryExact,
  27. type DataCategoryInfo,
  28. type PageFilters,
  29. } from 'sentry/types/core';
  30. import type {RouteComponentProps} from 'sentry/types/legacyReactRouter';
  31. import type {Organization} from 'sentry/types/organization';
  32. import type {Project} from 'sentry/types/project';
  33. import {hasDynamicSamplingCustomFeature} from 'sentry/utils/dynamicSampling/features';
  34. import withOrganization from 'sentry/utils/withOrganization';
  35. import withPageFilters from 'sentry/utils/withPageFilters';
  36. import HeaderTabs from 'sentry/views/organizationStats/header';
  37. import {getPerformanceBaseUrl} from 'sentry/views/performance/utils';
  38. import type {ChartDataTransform} from './usageChart';
  39. import {CHART_OPTIONS_DATACATEGORY} from './usageChart';
  40. import UsageStatsOrg from './usageStatsOrg';
  41. import UsageStatsProjects from './usageStatsProjects';
  42. const HookHeader = HookOrDefault({hookName: 'component:org-stats-banner'});
  43. export const PAGE_QUERY_PARAMS = [
  44. // From DatePageFilter
  45. 'statsPeriod',
  46. 'start',
  47. 'end',
  48. 'utc',
  49. // From data category selector
  50. 'dataCategory',
  51. // From UsageOrganizationStats
  52. 'transform',
  53. // From UsageProjectStats
  54. 'sort',
  55. 'query',
  56. 'cursor',
  57. 'spikeCursor',
  58. // From show data discarded on client toggle
  59. 'clientDiscard',
  60. ];
  61. export type OrganizationStatsProps = {
  62. organization: Organization;
  63. selection: PageFilters;
  64. } & RouteComponentProps<{}, {}>;
  65. export class OrganizationStats extends Component<OrganizationStatsProps> {
  66. get dataCategoryInfo(): DataCategoryInfo {
  67. const dataCategoryPlural = this.props.location?.query?.dataCategory;
  68. const categories = Object.values(DATA_CATEGORY_INFO);
  69. const info = categories.find(c => c.plural === dataCategoryPlural);
  70. if (
  71. info?.name === DataCategoryExact.SPAN &&
  72. this.props.organization.features.includes('spans-usage-tracking') &&
  73. !hasDynamicSamplingCustomFeature(this.props.organization)
  74. ) {
  75. return {
  76. ...info,
  77. apiName: 'span_indexed',
  78. };
  79. }
  80. // Default to errors
  81. return info ?? DATA_CATEGORY_INFO.error;
  82. }
  83. get dataCategory() {
  84. return this.dataCategoryInfo.plural;
  85. }
  86. get dataCategoryName() {
  87. return this.dataCategoryInfo.titleName;
  88. }
  89. get dataDatetime(): DateTimeObject {
  90. const params = this.props.selection.datetime;
  91. const {
  92. start,
  93. end,
  94. statsPeriod,
  95. utc: utcString,
  96. } = normalizeDateTimeParams(params, {
  97. allowEmptyPeriod: true,
  98. allowAbsoluteDatetime: true,
  99. allowAbsolutePageDatetime: true,
  100. });
  101. if (!statsPeriod && !start && !end) {
  102. return {period: DEFAULT_STATS_PERIOD};
  103. }
  104. // Following getParams, statsPeriod will take priority over start/end
  105. if (statsPeriod) {
  106. return {period: statsPeriod};
  107. }
  108. const utc = utcString === 'true';
  109. if (start && end) {
  110. return utc
  111. ? {
  112. start: moment.utc(start).format(),
  113. end: moment.utc(end).format(),
  114. utc,
  115. }
  116. : {
  117. start: moment(start).utc().format(),
  118. end: moment(end).utc().format(),
  119. utc,
  120. };
  121. }
  122. return {period: DEFAULT_STATS_PERIOD};
  123. }
  124. get clientDiscard(): boolean {
  125. return this.props.location?.query?.clientDiscard === 'true';
  126. }
  127. // Validation and type-casting should be handled by chart
  128. get chartTransform(): string | undefined {
  129. return this.props.location?.query?.transform;
  130. }
  131. // Validation and type-casting should be handled by table
  132. get tableSort(): string | undefined {
  133. return this.props.location?.query?.sort;
  134. }
  135. get tableQuery(): string | undefined {
  136. return this.props.location?.query?.query;
  137. }
  138. get tableCursor(): string | undefined {
  139. return this.props.location?.query?.cursor;
  140. }
  141. // Project selection from GlobalSelectionHeader
  142. get projectIds(): number[] {
  143. const selection_projects = this.props.selection.projects.length
  144. ? this.props.selection.projects
  145. : [ALL_ACCESS_PROJECTS];
  146. return selection_projects;
  147. }
  148. get isSingleProject(): boolean {
  149. return this.projectIds.length === 1 && !this.projectIds.includes(-1);
  150. }
  151. getNextLocations = (project: Project): Record<string, LocationDescriptorObject> => {
  152. const {location, organization} = this.props;
  153. const nextLocation: LocationDescriptorObject = {
  154. ...location,
  155. query: {
  156. ...location.query,
  157. project: project.id,
  158. },
  159. };
  160. // Do not leak out page-specific keys
  161. nextLocation.query = omit(nextLocation.query, PAGE_QUERY_PARAMS);
  162. return {
  163. performance: {
  164. ...nextLocation,
  165. pathname: getPerformanceBaseUrl(organization.slug),
  166. },
  167. projectDetail: {
  168. ...nextLocation,
  169. pathname: `/organizations/${organization.slug}/projects/${project.slug}/`,
  170. },
  171. issueList: {
  172. ...nextLocation,
  173. pathname: `/organizations/${organization.slug}/issues/`,
  174. },
  175. settings: {
  176. pathname: `/settings/${organization.slug}/projects/${project.slug}/`,
  177. },
  178. };
  179. };
  180. /**
  181. * See PAGE_QUERY_PARAMS for list of accepted keys on nextState
  182. */
  183. setStateOnUrl = (
  184. nextState: {
  185. clientDiscard?: boolean;
  186. cursor?: string;
  187. dataCategory?: DataCategoryInfo['plural'];
  188. query?: string;
  189. sort?: string;
  190. transform?: ChartDataTransform;
  191. },
  192. options: {
  193. willUpdateRouter?: boolean;
  194. } = {
  195. willUpdateRouter: true,
  196. }
  197. ): LocationDescriptorObject => {
  198. const {location, router} = this.props;
  199. const nextQueryParams = pick(nextState, PAGE_QUERY_PARAMS);
  200. const nextLocation = {
  201. ...location,
  202. query: {
  203. ...location?.query,
  204. ...nextQueryParams,
  205. },
  206. };
  207. if (options.willUpdateRouter) {
  208. router.push(nextLocation);
  209. }
  210. return nextLocation;
  211. };
  212. renderProjectPageControl = () => {
  213. const {organization} = this.props;
  214. const isSelfHostedErrorsOnly = ConfigStore.get('isSelfHostedErrorsOnly');
  215. const options = CHART_OPTIONS_DATACATEGORY.filter(opt => {
  216. if (isSelfHostedErrorsOnly) {
  217. return opt.value === DATA_CATEGORY_INFO.error.plural;
  218. }
  219. if (opt.value === DATA_CATEGORY_INFO.replay.plural) {
  220. return organization.features.includes('session-replay');
  221. }
  222. if (DATA_CATEGORY_INFO.span.plural === opt.value) {
  223. return organization.features.includes('span-stats');
  224. }
  225. if (DATA_CATEGORY_INFO.transaction.plural === opt.value) {
  226. return !organization.features.includes('spans-usage-tracking');
  227. }
  228. if (DATA_CATEGORY_INFO.profileDuration.plural === opt.value) {
  229. return (
  230. organization.features.includes('continuous-profiling-stats') ||
  231. organization.features.includes('continuous-profiling')
  232. );
  233. }
  234. if (DATA_CATEGORY_INFO.profile.plural === opt.value) {
  235. return !organization.features.includes('continuous-profiling-stats');
  236. }
  237. return true;
  238. });
  239. return (
  240. <PageControl>
  241. <PageFilterBar>
  242. <ProjectPageFilter />
  243. <DropdownDataCategory
  244. triggerProps={{prefix: t('Category')}}
  245. value={this.dataCategory}
  246. options={options}
  247. onChange={opt => this.setStateOnUrl({dataCategory: String(opt.value)})}
  248. />
  249. <DatePageFilter />
  250. </PageFilterBar>
  251. </PageControl>
  252. );
  253. };
  254. /**
  255. * This method is replaced by the hook "component:enhanced-org-stats"
  256. */
  257. renderUsageStatsOrg() {
  258. const {organization, router, location, params, routes} = this.props;
  259. return (
  260. <UsageStatsOrg
  261. isSingleProject={this.isSingleProject}
  262. projectIds={this.projectIds}
  263. organization={organization}
  264. dataCategory={this.dataCategory}
  265. dataCategoryName={this.dataCategoryInfo.titleName}
  266. dataCategoryApiName={this.dataCategoryInfo.apiName}
  267. dataDatetime={this.dataDatetime}
  268. chartTransform={this.chartTransform}
  269. clientDiscard={this.clientDiscard}
  270. handleChangeState={this.setStateOnUrl}
  271. router={router}
  272. location={location}
  273. params={params}
  274. routes={routes}
  275. />
  276. );
  277. }
  278. render() {
  279. const {organization} = this.props;
  280. const hasTeamInsights = organization.features.includes('team-insights');
  281. return (
  282. <SentryDocumentTitle title={t('Usage Stats')} orgSlug={organization.slug}>
  283. <NoProjectMessage organization={organization}>
  284. <PageFiltersContainer>
  285. {hasTeamInsights ? (
  286. <HeaderTabs organization={organization} activeTab="stats" />
  287. ) : (
  288. <Layout.Header>
  289. <Layout.HeaderContent>
  290. <Layout.Title>{t('Organization Usage Stats')}</Layout.Title>
  291. <HeadingSubtitle>
  292. {tct(
  293. 'A view of the usage data that Sentry has received across your entire organization. [link: Read the docs].',
  294. {
  295. link: (
  296. <ExternalLink href="https://docs.sentry.io/product/stats/" />
  297. ),
  298. }
  299. )}
  300. </HeadingSubtitle>
  301. </Layout.HeaderContent>
  302. </Layout.Header>
  303. )}
  304. <Body>
  305. <Layout.Main fullWidth>
  306. <HookHeader organization={organization} />
  307. {this.renderProjectPageControl()}
  308. <div>
  309. <ErrorBoundary mini>{this.renderUsageStatsOrg()}</ErrorBoundary>
  310. </div>
  311. <ErrorBoundary mini>
  312. <UsageStatsProjects
  313. organization={organization}
  314. dataCategory={this.dataCategoryInfo}
  315. dataCategoryName={this.dataCategoryInfo.titleName}
  316. isSingleProject={this.isSingleProject}
  317. projectIds={this.projectIds}
  318. dataDatetime={this.dataDatetime}
  319. tableSort={this.tableSort}
  320. tableQuery={this.tableQuery}
  321. tableCursor={this.tableCursor}
  322. handleChangeState={this.setStateOnUrl}
  323. getNextLocations={this.getNextLocations}
  324. />
  325. </ErrorBoundary>
  326. </Layout.Main>
  327. </Body>
  328. </PageFiltersContainer>
  329. </NoProjectMessage>
  330. </SentryDocumentTitle>
  331. );
  332. }
  333. }
  334. const HookOrgStats = HookOrDefault({
  335. hookName: 'component:enhanced-org-stats',
  336. defaultComponent: OrganizationStats,
  337. });
  338. export default withPageFilters(withOrganization(HookOrgStats));
  339. const DropdownDataCategory = styled(CompactSelect)`
  340. width: auto;
  341. position: relative;
  342. grid-column: auto / span 1;
  343. button[aria-haspopup='listbox'] {
  344. width: 100%;
  345. height: 100%;
  346. }
  347. @media (min-width: ${p => p.theme.breakpoints.small}) {
  348. grid-column: auto / span 2;
  349. }
  350. @media (min-width: ${p => p.theme.breakpoints.large}) {
  351. grid-column: auto / span 1;
  352. }
  353. &::after {
  354. content: '';
  355. position: absolute;
  356. top: 0;
  357. bottom: 0;
  358. left: 0;
  359. right: 0;
  360. pointer-events: none;
  361. box-shadow: inset 0 0 0 1px ${p => p.theme.border};
  362. border-radius: ${p => p.theme.borderRadius};
  363. }
  364. `;
  365. const Body = styled(Layout.Body)`
  366. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  367. display: block;
  368. }
  369. `;
  370. const HeadingSubtitle = styled('p')`
  371. margin-top: ${space(0.5)};
  372. margin-bottom: 0;
  373. `;
  374. const PageControl = styled('div')`
  375. display: grid;
  376. width: 100%;
  377. margin-bottom: ${space(2)};
  378. grid-template-columns: minmax(0, max-content);
  379. @media (max-width: ${p => p.theme.breakpoints.small}) {
  380. grid-template-columns: minmax(0, 1fr);
  381. }
  382. `;