spikeProtectionHistoryTable.tsx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import {Component} from 'react';
  2. import styled from '@emotion/styled';
  3. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  4. import {Button, LinkButton} from 'sentry/components/core/button';
  5. import DiscoverButton from 'sentry/components/discoverButton';
  6. import Link from 'sentry/components/links/link';
  7. import LoadingIndicator from 'sentry/components/loadingIndicator';
  8. import {PageHeadingQuestionTooltip} from 'sentry/components/pageHeadingQuestionTooltip';
  9. import Panel from 'sentry/components/panels/panel';
  10. import {PanelTable} from 'sentry/components/panels/panelTable';
  11. import Placeholder from 'sentry/components/placeholder';
  12. import {IconSettings} from 'sentry/icons';
  13. import {IconTelescope} from 'sentry/icons/iconTelescope';
  14. import {t, tct} from 'sentry/locale';
  15. import {space} from 'sentry/styles/space';
  16. import type {DataCategoryInfo} from 'sentry/types/core';
  17. import type {Organization} from 'sentry/types/organization';
  18. import type {Project} from 'sentry/types/project';
  19. import {getExactDuration} from 'sentry/utils/duration/getExactDuration';
  20. import {decodeScalar} from 'sentry/utils/queryString';
  21. import useApi from 'sentry/utils/useApi';
  22. import useOrganization from 'sentry/utils/useOrganization';
  23. import withOrganization from 'sentry/utils/withOrganization';
  24. import {
  25. formatUsageWithUnits,
  26. getFormatUsageOptions,
  27. } from 'sentry/views/organizationStats/utils';
  28. import withSubscription from 'getsentry/components/withSubscription';
  29. import type {Subscription} from 'getsentry/types';
  30. import trackSpendVisibilityAnaltyics, {
  31. SpendVisibilityEvents,
  32. } from 'getsentry/utils/trackSpendVisibilityAnalytics';
  33. import {
  34. SPIKE_PROTECTION_DOCS_LINK,
  35. SPIKE_PROTECTION_ERROR_MESSAGE,
  36. } from 'getsentry/views/spikeProtection/constants';
  37. import SpikeProtectionTimeDetails from 'getsentry/views/spikeProtection/spikeProtectionTimeDetails';
  38. import type {SpikeDetails} from 'getsentry/views/spikeProtection/types';
  39. import {isSpikeProtectionEnabled} from './spikeProtectionProjectToggle';
  40. type Props = {
  41. dataCategoryInfo: DataCategoryInfo;
  42. onEnableSpikeProtection: () => void;
  43. organization: Organization;
  44. project: Project;
  45. spikes: SpikeDetails[];
  46. subscription: Subscription;
  47. isLoading?: boolean;
  48. };
  49. function EnableSpikeProtectionButton({
  50. onEnableSpikeProtection,
  51. project,
  52. subscription,
  53. ...props
  54. }: {
  55. onEnableSpikeProtection: () => void;
  56. project: Project;
  57. subscription: Subscription;
  58. }) {
  59. const api = useApi();
  60. const organization = useOrganization();
  61. const endpoint = `/organizations/${organization.slug}/spike-protections/`;
  62. async function enableSpikeProtection() {
  63. try {
  64. await api.requestPromise(endpoint, {
  65. method: 'POST',
  66. data: {projects: [project.slug]},
  67. });
  68. addSuccessMessage(
  69. tct('[action] spike protection for [project]', {
  70. action: t('Enabled'),
  71. project: project.slug,
  72. })
  73. );
  74. trackSpendVisibilityAnaltyics(SpendVisibilityEvents.SP_PROJECT_TOGGLED, {
  75. organization,
  76. subscription,
  77. project_id: project.id,
  78. value: true,
  79. view: 'project_stats',
  80. });
  81. onEnableSpikeProtection();
  82. } catch {
  83. addErrorMessage(SPIKE_PROTECTION_ERROR_MESSAGE);
  84. }
  85. }
  86. return (
  87. <Button
  88. size="sm"
  89. onClick={() => {
  90. enableSpikeProtection();
  91. }}
  92. {...props}
  93. data-test-id="enable-sp-button"
  94. >
  95. {t('Enable Spike Protection')}
  96. </Button>
  97. );
  98. }
  99. class SpikeProtectionHistoryTable extends Component<Props> {
  100. headers = [
  101. t('Past Spikes'),
  102. t('Initial Threshold'),
  103. t('Duration'),
  104. t('Events Dropped'),
  105. null, // Discover Query button
  106. ];
  107. renderSpikeRow(spike: SpikeDetails) {
  108. const {dataCategoryInfo, project, organization, subscription} = this.props;
  109. // ms -> s, rounds up to get duration in minutes
  110. // rounding up to match the formatted date and time values
  111. const millisecondsPerSecond = 1000;
  112. const secondsPerMinute = 60;
  113. const duration = spike.end
  114. ? Math.ceil(
  115. (new Date(spike.end).valueOf() - new Date(spike.start).valueOf()) /
  116. (millisecondsPerSecond * secondsPerMinute)
  117. ) * secondsPerMinute
  118. : null;
  119. return [
  120. <SpikeProtectionTimeDetails spike={spike} key="time" />,
  121. <StyledCell key="threshold">
  122. {formatUsageWithUnits(
  123. spike.threshold,
  124. dataCategoryInfo.plural,
  125. getFormatUsageOptions(dataCategoryInfo.plural)
  126. )}
  127. </StyledCell>,
  128. <StyledCell key="duration">
  129. {duration ? getExactDuration(duration, true) : t('Ongoing')}
  130. </StyledCell>,
  131. <StyledCell key="dropped">
  132. {spike.dropped
  133. ? formatUsageWithUnits(
  134. spike.dropped,
  135. dataCategoryInfo.plural,
  136. getFormatUsageOptions(dataCategoryInfo.plural)
  137. )
  138. : '-'}
  139. </StyledCell>,
  140. <StyledCell key="discover-button">
  141. <DiscoverButton
  142. icon={<IconTelescope size="sm" />}
  143. data-test-id="spike-protection-discover-button"
  144. onClick={() =>
  145. trackSpendVisibilityAnaltyics(SpendVisibilityEvents.SP_DISCOVER_CLICKED, {
  146. organization,
  147. subscription,
  148. view: 'project_stats',
  149. })
  150. }
  151. to={{
  152. pathname: `/organizations/${organization.slug}/discover/homepage/`,
  153. query: {
  154. project: [project.id],
  155. start: decodeScalar(spike.start),
  156. end: decodeScalar(spike.end),
  157. },
  158. }}
  159. >
  160. {t('Open in Discover')}
  161. </DiscoverButton>
  162. </StyledCell>,
  163. ];
  164. }
  165. renderEmptyMessage() {
  166. const {organization} = this.props;
  167. return (
  168. <EmptySpikeHistory data-test-id="spike-history-empty">
  169. <b>{t('No Significant Spikes')}</b>
  170. <p>
  171. {t(
  172. 'Spike Protection is enabled for this project, but there are no significant spikes that lasted 2hrs or longer.'
  173. )}
  174. <br />
  175. {tct('Please see the [auditLogLink: audit log] for all detected spikes.', {
  176. auditLogLink: <Link to={`/settings/${organization?.slug}/audit-log/`} />,
  177. })}
  178. </p>
  179. </EmptySpikeHistory>
  180. );
  181. }
  182. renderDisabledMessage() {
  183. const {project, subscription, onEnableSpikeProtection} = this.props;
  184. return (
  185. <EmptySpikeHistory data-test-id="spike-history-disabled">
  186. <b>{t('Spike Protection Disabled')}</b>
  187. <p>{t('Spike Protection is currently disabled for this project.')}</p>
  188. <div>
  189. <EnableSpikeProtectionButton
  190. project={project}
  191. subscription={subscription}
  192. onEnableSpikeProtection={onEnableSpikeProtection}
  193. />
  194. </div>
  195. </EmptySpikeHistory>
  196. );
  197. }
  198. renderTable() {
  199. const {spikes, project, isLoading} = this.props;
  200. if (isLoading ?? false) {
  201. return (
  202. <Placeholder height="150px">
  203. <LoadingIndicator mini />
  204. </Placeholder>
  205. );
  206. }
  207. if (!isSpikeProtectionEnabled(project)) {
  208. return this.renderDisabledMessage();
  209. }
  210. if (spikes.length === 0) {
  211. return this.renderEmptyMessage();
  212. }
  213. return (
  214. <PanelTable headers={this.headers}>
  215. {spikes.map(spike => this.renderSpikeRow(spike))}
  216. </PanelTable>
  217. );
  218. }
  219. render() {
  220. const {organization} = this.props;
  221. return (
  222. <div data-test-id="spike-protection-history-table">
  223. <SectionHeading>
  224. <Title>
  225. {t('Spike Protection')}
  226. <PageHeadingQuestionTooltip
  227. docsUrl={SPIKE_PROTECTION_DOCS_LINK}
  228. title={t(
  229. 'Sentry applies a dynamic rate limit to your account designed to protect you from short-term spikes.'
  230. )}
  231. />
  232. </Title>
  233. <LinkButton
  234. size="sm"
  235. icon={<IconSettings />}
  236. aria-label={t('Settings')}
  237. title={t('Go to spike protection settings')}
  238. to={`/settings/${organization.slug}/spike-protection/`}
  239. />
  240. </SectionHeading>
  241. {this.renderTable()}
  242. </div>
  243. );
  244. }
  245. }
  246. export default withSubscription(withOrganization(SpikeProtectionHistoryTable));
  247. const SectionHeading = styled('div')`
  248. display: flex;
  249. gap: ${space(1)};
  250. margin-bottom: ${space(2)};
  251. align-items: center;
  252. `;
  253. const Title = styled('div')`
  254. font-weight: bold;
  255. font-size: ${p => p.theme.fontSizeLarge};
  256. color: ${p => p.theme.gray400};
  257. display: flex;
  258. flex: 1;
  259. align-items: center;
  260. gap: ${space(0.75)};
  261. `;
  262. const StyledCell = styled('div')`
  263. display: flex;
  264. align-items: center;
  265. &:nth-child(5n) {
  266. justify-content: end;
  267. }
  268. `;
  269. const EmptySpikeHistory = styled(Panel)`
  270. width: 100%;
  271. display: flex;
  272. flex-direction: column;
  273. text-align: center;
  274. padding: ${space(4)} ${space(2)};
  275. b {
  276. font-size: ${p => p.theme.fontSizeLarge};
  277. margin-bottom: ${space(1)};
  278. }
  279. p:last-child {
  280. margin: 0;
  281. }
  282. `;