thresholdGroupRows.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. import {Fragment, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import moment from 'moment';
  4. import type {APIRequestMethod} from 'sentry/api';
  5. import {Button} from 'sentry/components/button';
  6. import {CompactSelect} from 'sentry/components/compactSelect';
  7. import Input from 'sentry/components/input';
  8. import {IconAdd, IconClose, IconDelete, IconEdit} from 'sentry/icons';
  9. import {t} from 'sentry/locale';
  10. import {space} from 'sentry/styles/space';
  11. import type {Project} from 'sentry/types';
  12. import {MonitorType} from 'sentry/types/alerts';
  13. import {getExactDuration, parseLargestSuffix} from 'sentry/utils/formatters';
  14. import {capitalize} from 'sentry/utils/string/capitalize';
  15. import useApi from 'sentry/utils/useApi';
  16. import useOrganization from 'sentry/utils/useOrganization';
  17. import {
  18. // ActionType,
  19. ActivationCondition,
  20. AlertRuleThresholdType,
  21. AlertRuleTriggerType,
  22. Dataset,
  23. EventTypes,
  24. // TargetType,
  25. type UnsavedMetricRule,
  26. } from 'sentry/views/alerts/rules/metric/types';
  27. import {MEPAlertsQueryType} from 'sentry/views/alerts/wizard/options';
  28. import {
  29. CRASH_FREE_SESSION_RATE_STR,
  30. CRASH_FREE_USER_RATE_STR as _CRASH_FREE_USER_RATE_STR,
  31. FAILURE_RATE_STR as _FAILURE_RATE_STR,
  32. NEW_ISSUE_COUNT_STR,
  33. NEW_THRESHOLD_PREFIX,
  34. REGRESSED_ISSUE_COUNT_STR as _REGRESSED_ISSUE_COUNT_STR,
  35. TOTAL_ERROR_COUNT_STR,
  36. UNHANDLED_ISSUE_COUNT_STR as _UNHANDLED_ISSUE_COUNT_STR,
  37. } from '../utils/constants';
  38. import type {EditingThreshold, Threshold} from '../utils/types';
  39. export type ThresholdGroupRowsProps = {
  40. allEnvironmentNames: string[];
  41. project: Project;
  42. refetch: () => void;
  43. setTempError: (msg: string) => void;
  44. isLastRow?: boolean;
  45. newGroup?: boolean;
  46. onFormClose?: (id: string) => void;
  47. threshold?: Threshold;
  48. };
  49. export function ThresholdGroupRows({
  50. allEnvironmentNames,
  51. isLastRow = false,
  52. newGroup = false,
  53. onFormClose,
  54. project,
  55. refetch,
  56. setTempError,
  57. threshold: initialThreshold,
  58. }: ThresholdGroupRowsProps) {
  59. const [editingThresholds, setEditingThresholds] = useState<{
  60. [key: string]: EditingThreshold;
  61. }>(() => {
  62. const editingThreshold = {};
  63. if (newGroup) {
  64. const [windowValue, windowSuffix] = parseLargestSuffix(0);
  65. const id = `${NEW_THRESHOLD_PREFIX}`;
  66. const newGroupEdit = {
  67. id,
  68. project,
  69. windowValue,
  70. windowSuffix,
  71. threshold_type: 'total_error_count',
  72. trigger_type: 'over',
  73. value: 0,
  74. hasError: false,
  75. };
  76. editingThreshold[id] = newGroupEdit;
  77. }
  78. return editingThreshold;
  79. });
  80. const [newThresholdIterator, setNewThresholdIterator] = useState<number>(0); // used simply to initialize new threshold
  81. const api = useApi();
  82. const organization = useOrganization();
  83. const isActivatedAlert = organization.features?.includes('activated-alert-rules');
  84. const thresholdIdSet = useMemo(() => {
  85. const initial = new Set<string>([]);
  86. if (initialThreshold) initial.add(initialThreshold.id);
  87. return new Set([...initial, ...Object.keys(editingThresholds)]);
  88. }, [initialThreshold, editingThresholds]);
  89. const thresholdTypeList = useMemo(() => {
  90. const isInternal = organization.features?.includes('releases-v2-internal');
  91. const list = [
  92. {
  93. value: TOTAL_ERROR_COUNT_STR,
  94. textValue: 'Errors',
  95. label: 'Error Count',
  96. },
  97. ];
  98. if (isInternal) {
  99. list.push(
  100. {
  101. value: CRASH_FREE_SESSION_RATE_STR,
  102. textValue: 'Crash Free Sessions',
  103. label: 'Crash Free Sessions',
  104. },
  105. {
  106. value: NEW_ISSUE_COUNT_STR,
  107. textValue: 'New Issue Count',
  108. label: 'New Issue Count',
  109. }
  110. );
  111. }
  112. return list;
  113. }, [organization]);
  114. const windowOptions = thresholdType => {
  115. let options = [
  116. {
  117. value: 'hours',
  118. textValue: 'hours',
  119. label: 'hrs',
  120. },
  121. {
  122. value: 'days',
  123. textValue: 'days',
  124. label: 'days',
  125. },
  126. ];
  127. if (thresholdType !== CRASH_FREE_SESSION_RATE_STR) {
  128. options = [
  129. {
  130. value: 'seconds',
  131. textValue: 'seconds',
  132. label: 's',
  133. },
  134. {
  135. value: 'minutes',
  136. textValue: 'minutes',
  137. label: 'min',
  138. },
  139. ...options,
  140. ];
  141. }
  142. return options;
  143. };
  144. const initializeNewThreshold = (
  145. environmentName: string | undefined = undefined,
  146. defaultWindow: number = 0
  147. ) => {
  148. if (!project) {
  149. setTempError('No project provided');
  150. return;
  151. }
  152. const thresholdId = `${NEW_THRESHOLD_PREFIX}-${newThresholdIterator}`;
  153. const [windowValue, windowSuffix] = parseLargestSuffix(defaultWindow);
  154. const newThreshold: EditingThreshold = {
  155. id: thresholdId,
  156. project,
  157. environmentName,
  158. windowValue,
  159. windowSuffix,
  160. threshold_type: 'total_error_count',
  161. trigger_type: 'over',
  162. value: 0,
  163. hasError: false,
  164. };
  165. const updatedEditingThresholds = {...editingThresholds};
  166. updatedEditingThresholds[thresholdId] = newThreshold;
  167. setEditingThresholds(updatedEditingThresholds);
  168. setNewThresholdIterator(newThresholdIterator + 1);
  169. };
  170. const enableEditThreshold = (threshold: Threshold) => {
  171. const updatedEditingThresholds = {...editingThresholds};
  172. const [windowValue, windowSuffix] = parseLargestSuffix(threshold.window_in_seconds);
  173. updatedEditingThresholds[threshold.id] = {
  174. ...JSON.parse(JSON.stringify(threshold)), // Deep copy the original threshold object
  175. environmentName: threshold.environment ? threshold.environment.name : '', // convert environment to string for editing
  176. windowValue,
  177. windowSuffix,
  178. hasError: false,
  179. };
  180. setEditingThresholds(updatedEditingThresholds);
  181. };
  182. const saveMetricAlert = (
  183. thresholdData: EditingThreshold,
  184. method: APIRequestMethod = 'POST'
  185. ) => {
  186. const slug = project.slug;
  187. /* Convert threshold data structure to metric alert data structure */
  188. const metricAlertData: UnsavedMetricRule & {name: string} = {
  189. name: `Release Alert Rule for ${slug} in ${thresholdData.environmentName}`,
  190. monitorType: MonitorType.ACTIVATED,
  191. aggregate: 'count()',
  192. dataset: Dataset.ERRORS,
  193. environment: thresholdData.environmentName || null,
  194. projects: [slug],
  195. query: '',
  196. resolveThreshold: null,
  197. thresholdPeriod: 1,
  198. thresholdType: AlertRuleThresholdType.ABOVE,
  199. timeWindow: thresholdData.windowValue,
  200. triggers: [
  201. {
  202. label: AlertRuleTriggerType.CRITICAL,
  203. alertThreshold: thresholdData.value,
  204. // TODO - add a default action to triggers
  205. actions: [],
  206. },
  207. ],
  208. comparisonDelta: null,
  209. eventTypes: [EventTypes.ERROR],
  210. owner: null,
  211. queryType: MEPAlertsQueryType.ERROR,
  212. activationCondition: ActivationCondition.RELEASE_CONDITION,
  213. };
  214. let apiUrl = `/organizations/${organization.slug}/alert-rules/`;
  215. if (!thresholdData.id.includes(NEW_THRESHOLD_PREFIX)) {
  216. apiUrl += `${thresholdData.id}/`;
  217. }
  218. const metricAlertRequest = api.requestPromise(apiUrl, {
  219. method,
  220. data: metricAlertData,
  221. });
  222. return metricAlertRequest;
  223. };
  224. const saveReleaseThreshold = (
  225. thresholdData: EditingThreshold,
  226. method: APIRequestMethod = 'POST'
  227. ) => {
  228. let apiUrl = `/projects/${organization.slug}/${thresholdData.project.slug}/release-thresholds/`;
  229. if (!thresholdData.id.includes(NEW_THRESHOLD_PREFIX)) {
  230. apiUrl += `${thresholdData.id}/`;
  231. }
  232. const releaseRequest = api.requestPromise(apiUrl, {
  233. method,
  234. data: thresholdData,
  235. });
  236. return releaseRequest;
  237. };
  238. const saveThreshold = (saveIds: string[]) => {
  239. saveIds.forEach(id => {
  240. const thresholdData = editingThresholds[id];
  241. const method = id.includes(NEW_THRESHOLD_PREFIX) ? 'POST' : 'PUT';
  242. const seconds = moment
  243. .duration(thresholdData.windowValue, thresholdData.windowSuffix)
  244. .as('seconds');
  245. if (!thresholdData.project) {
  246. setTempError('Project required');
  247. return;
  248. }
  249. const submitData = {
  250. ...thresholdData,
  251. environment: thresholdData.environmentName,
  252. window_in_seconds: seconds,
  253. };
  254. const request = isActivatedAlert
  255. ? saveMetricAlert(submitData, method)
  256. : saveReleaseThreshold(submitData, method);
  257. request
  258. .then(() => {
  259. refetch();
  260. closeEditForm(id);
  261. })
  262. .catch(_err => {
  263. setTempError('Issue saving threshold');
  264. setEditingThresholds(prevState => {
  265. const errorThreshold = {
  266. ...submitData,
  267. hasError: true,
  268. };
  269. const updatedEditingThresholds = {...prevState};
  270. updatedEditingThresholds[id] = errorThreshold;
  271. return updatedEditingThresholds;
  272. });
  273. });
  274. });
  275. };
  276. const deleteThreshold = thresholdId => {
  277. const updatedEditingThresholds = {...editingThresholds};
  278. const thresholdData = editingThresholds[thresholdId];
  279. const method = 'DELETE';
  280. let path = `/projects/${organization.slug}/${thresholdData.project.slug}/release-thresholds/${thresholdId}/`;
  281. if (isActivatedAlert)
  282. path = `/organizations/${organization.slug}/alert-rules/${thresholdId}/`;
  283. if (!thresholdId.includes(NEW_THRESHOLD_PREFIX)) {
  284. const request = api.requestPromise(path, {
  285. method,
  286. });
  287. request.then(refetch).catch(_err => {
  288. setTempError('Issue deleting threshold');
  289. const errorThreshold = {
  290. ...thresholdData,
  291. hasError: true,
  292. };
  293. updatedEditingThresholds[thresholdId] = errorThreshold as EditingThreshold;
  294. setEditingThresholds(updatedEditingThresholds);
  295. });
  296. }
  297. delete updatedEditingThresholds[thresholdId];
  298. setEditingThresholds(updatedEditingThresholds);
  299. };
  300. const closeEditForm = thresholdId => {
  301. const updatedEditingThresholds = {...editingThresholds};
  302. delete updatedEditingThresholds[thresholdId];
  303. setEditingThresholds(updatedEditingThresholds);
  304. onFormClose?.(thresholdId);
  305. };
  306. const editThresholdState = (thresholdId, key, value) => {
  307. if (editingThresholds[thresholdId]) {
  308. const updateEditing = JSON.parse(JSON.stringify(editingThresholds));
  309. const currentThresholdValues = updateEditing[thresholdId];
  310. updateEditing[thresholdId][key] = value;
  311. if (key === 'threshold_type' && value === CRASH_FREE_SESSION_RATE_STR) {
  312. if (['seconds', 'minutes'].indexOf(currentThresholdValues.windowSuffix) > -1) {
  313. updateEditing[thresholdId].windowSuffix = 'hours';
  314. }
  315. }
  316. setEditingThresholds(updateEditing);
  317. }
  318. };
  319. return (
  320. <StyledThresholdGroup>
  321. {Array.from(thresholdIdSet).map((tId: string, idx: number) => {
  322. const isEditing = tId in editingThresholds;
  323. // NOTE: we're casting the threshold type because we can't dynamically derive type below
  324. const threshold = isEditing
  325. ? (editingThresholds[tId] as EditingThreshold)
  326. : (initialThreshold as Threshold);
  327. return (
  328. <StyledRow
  329. key={threshold.id}
  330. lastRow={isLastRow && idx === thresholdIdSet.size - 1}
  331. hasError={isEditing && (threshold as EditingThreshold).hasError}
  332. >
  333. {/* ENV ONLY EDITABLE IF NEW */}
  334. {!initialThreshold || threshold.id !== initialThreshold.id ? (
  335. <CompactSelect
  336. style={{width: '100%'}}
  337. value={(threshold as EditingThreshold).environmentName || ''}
  338. onChange={selectedOption =>
  339. editThresholdState(
  340. threshold.id,
  341. 'environmentName',
  342. selectedOption.value
  343. )
  344. }
  345. options={[
  346. {
  347. value: '',
  348. textValue: '',
  349. label: '',
  350. },
  351. ...allEnvironmentNames.map(env => ({
  352. value: env,
  353. textValue: env,
  354. label: env,
  355. })),
  356. ]}
  357. />
  358. ) : (
  359. <FlexCenter>
  360. {/* '' means it _has_ an environment, but the env has no name */}
  361. {(threshold as Threshold).environment
  362. ? (threshold as Threshold).environment.name || ''
  363. : '{No environment}'}
  364. </FlexCenter>
  365. )}
  366. {/* FOLLOWING COLUMNS ARE EDITABLE */}
  367. {isEditing ? (
  368. <Fragment>
  369. <FlexCenter>
  370. <Input
  371. style={{width: '50%'}}
  372. value={(threshold as EditingThreshold).windowValue}
  373. type="number"
  374. min={0}
  375. onChange={e =>
  376. editThresholdState(threshold.id, 'windowValue', e.target.value)
  377. }
  378. />
  379. <CompactSelect
  380. style={{width: '50%'}}
  381. value={(threshold as EditingThreshold).windowSuffix}
  382. onChange={selectedOption =>
  383. editThresholdState(
  384. threshold.id,
  385. 'windowSuffix',
  386. selectedOption.value
  387. )
  388. }
  389. options={windowOptions(threshold.threshold_type)}
  390. />
  391. </FlexCenter>
  392. <FlexCenter>
  393. <CompactSelect
  394. value={threshold.threshold_type}
  395. onChange={selectedOption =>
  396. editThresholdState(
  397. threshold.id,
  398. 'threshold_type',
  399. selectedOption.value
  400. )
  401. }
  402. options={thresholdTypeList}
  403. />
  404. {threshold.trigger_type === 'over' ? (
  405. <Button
  406. onClick={() =>
  407. editThresholdState(threshold.id, 'trigger_type', 'under')
  408. }
  409. >
  410. &gt;
  411. </Button>
  412. ) : (
  413. <Button
  414. onClick={() =>
  415. editThresholdState(threshold.id, 'trigger_type', 'over')
  416. }
  417. >
  418. &lt;
  419. </Button>
  420. )}
  421. <Input
  422. value={threshold.value}
  423. type="number"
  424. min={0}
  425. onChange={e =>
  426. editThresholdState(threshold.id, 'value', e.target.value)
  427. }
  428. />
  429. </FlexCenter>
  430. </Fragment>
  431. ) : (
  432. <Fragment>
  433. <FlexCenter>
  434. {getExactDuration(
  435. (threshold as Threshold).window_in_seconds || 0,
  436. false,
  437. 'seconds'
  438. )}
  439. </FlexCenter>
  440. <FlexCenter>
  441. <div>
  442. {threshold.threshold_type
  443. .split('_')
  444. .map(word => capitalize(word))
  445. .join(' ')}
  446. </div>
  447. <div>&nbsp;{threshold.trigger_type === 'over' ? '>' : '<'}&nbsp;</div>
  448. <div>{threshold.value}</div>
  449. </FlexCenter>
  450. </Fragment>
  451. )}
  452. {/* END OF EDITABLE COLUMNS */}
  453. <ActionsColumn>
  454. {isEditing ? (
  455. <Fragment>
  456. <Button size="xs" onClick={() => saveThreshold([threshold.id])}>
  457. Save
  458. </Button>
  459. {!threshold.id.includes(NEW_THRESHOLD_PREFIX) && (
  460. <Button
  461. aria-label={t('Delete threshold')}
  462. borderless
  463. icon={<IconDelete color="danger" />}
  464. onClick={() => deleteThreshold(threshold.id)}
  465. size="xs"
  466. />
  467. )}
  468. <Button
  469. aria-label={t('Close')}
  470. borderless
  471. icon={<IconClose />}
  472. onClick={() => closeEditForm(threshold.id)}
  473. size="xs"
  474. />
  475. </Fragment>
  476. ) : (
  477. <Fragment>
  478. <Button
  479. aria-label={t('Edit threshold')}
  480. icon={<IconEdit />}
  481. onClick={() => enableEditThreshold(threshold as Threshold)}
  482. size="xs"
  483. />
  484. <Button
  485. aria-label={t('New Threshold')}
  486. icon={<IconAdd color="activeText" isCircled />}
  487. onClick={() =>
  488. initializeNewThreshold(
  489. initialThreshold?.environment
  490. ? initialThreshold.environment.name
  491. : undefined,
  492. initialThreshold ? initialThreshold.window_in_seconds : 0
  493. )
  494. }
  495. size="xs"
  496. />
  497. </Fragment>
  498. )}
  499. </ActionsColumn>
  500. </StyledRow>
  501. );
  502. })}
  503. </StyledThresholdGroup>
  504. );
  505. }
  506. const StyledThresholdGroup = styled('div')`
  507. display: contents;
  508. `;
  509. type StyledThresholdRowProps = {
  510. lastRow: boolean;
  511. hasError?: boolean;
  512. };
  513. const StyledRow = styled('div')<StyledThresholdRowProps>`
  514. display: contents;
  515. > * {
  516. padding: ${space(2)};
  517. background-color: ${p =>
  518. p.hasError ? 'rgba(255, 0, 0, 0.1)' : 'rgba(255, 255, 255, 0)'};
  519. border-bottom: ${p => (p.lastRow ? 0 : '1px solid ' + p.theme.border)};
  520. }
  521. `;
  522. const FlexCenter = styled('div')`
  523. display: flex;
  524. align-items: center;
  525. > * {
  526. margin: 0 ${space(1)};
  527. }
  528. `;
  529. const ActionsColumn = styled('div')`
  530. display: flex;
  531. align-items: center;
  532. justify-content: space-around;
  533. `;