monitorForm.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. import {Fragment, useRef} from 'react';
  2. import styled from '@emotion/styled';
  3. import {Observer} from 'mobx-react';
  4. import AlertLink from 'sentry/components/alertLink';
  5. import NumberField from 'sentry/components/forms/fields/numberField';
  6. import SelectField from 'sentry/components/forms/fields/selectField';
  7. import SentryMemberTeamSelectorField from 'sentry/components/forms/fields/sentryMemberTeamSelectorField';
  8. import SentryProjectSelectorField from 'sentry/components/forms/fields/sentryProjectSelectorField';
  9. import TextField from 'sentry/components/forms/fields/textField';
  10. import Form, {FormProps} from 'sentry/components/forms/form';
  11. import FormModel from 'sentry/components/forms/model';
  12. import ExternalLink from 'sentry/components/links/externalLink';
  13. import List from 'sentry/components/list';
  14. import ListItem from 'sentry/components/list/listItem';
  15. import Panel from 'sentry/components/panels/panel';
  16. import PanelBody from 'sentry/components/panels/panelBody';
  17. import Text from 'sentry/components/text';
  18. import {timezoneOptions} from 'sentry/data/timezones';
  19. import {t, tct, tn} from 'sentry/locale';
  20. import {space} from 'sentry/styles/space';
  21. import {SelectValue} from 'sentry/types';
  22. import {isActiveSuperuser} from 'sentry/utils/isActiveSuperuser';
  23. import slugify from 'sentry/utils/slugify';
  24. import commonTheme from 'sentry/utils/theme';
  25. import useOrganization from 'sentry/utils/useOrganization';
  26. import usePageFilters from 'sentry/utils/usePageFilters';
  27. import useProjects from 'sentry/utils/useProjects';
  28. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  29. import {crontabAsText, getScheduleIntervals} from 'sentry/views/monitors/utils';
  30. import {
  31. IntervalConfig,
  32. Monitor,
  33. MonitorConfig,
  34. MonitorType,
  35. ScheduleType,
  36. } from '../types';
  37. const SCHEDULE_OPTIONS: SelectValue<string>[] = [
  38. {value: ScheduleType.CRONTAB, label: t('Crontab')},
  39. {value: ScheduleType.INTERVAL, label: t('Interval')},
  40. ];
  41. export const DEFAULT_MONITOR_TYPE = 'cron_job';
  42. export const DEFAULT_CRONTAB = '0 0 * * *';
  43. // Maps the value from the SentryMemberTeamSelectorField -> the expected alert
  44. // rule key and vice-versa.
  45. //
  46. // XXX(epurkhiser): For whatever reason the rules API wants the team and member
  47. // to be capitalized.
  48. const RULE_TARGET_MAP = {team: 'Team', member: 'Member'} as const;
  49. const RULES_SELECTOR_MAP = {Team: 'team', Member: 'member'} as const;
  50. // In minutes
  51. export const DEFAULT_MAX_RUNTIME = 30;
  52. export const DEFAULT_CHECKIN_MARGIN = 1;
  53. const CHECKIN_MARGIN_MINIMUM = 1;
  54. const TIMEOUT_MINIMUM = 1;
  55. type Props = {
  56. apiEndpoint: string;
  57. apiMethod: FormProps['apiMethod'];
  58. onSubmitSuccess: FormProps['onSubmitSuccess'];
  59. monitor?: Monitor;
  60. submitLabel?: string;
  61. };
  62. interface TransformedData extends Partial<Omit<Monitor, 'config' | 'alertRule'>> {
  63. alertRule?: Partial<Monitor['alertRule']>;
  64. config?: Partial<Monitor['config']>;
  65. }
  66. /**
  67. * Transform sub-fields for what the API expects
  68. */
  69. export function transformMonitorFormData(_data: Record<string, any>, model: FormModel) {
  70. const schedType = model.getValue('config.schedule_type');
  71. // Remove interval fields if the monitor schedule is crontab
  72. const filteredFields = model.fields
  73. .toJSON()
  74. .filter(
  75. ([k, _v]) =>
  76. (schedType === ScheduleType.CRONTAB &&
  77. k !== 'config.schedule.interval' &&
  78. k !== 'config.schedule.frequency') ||
  79. schedType === ScheduleType.INTERVAL
  80. );
  81. const result = filteredFields.reduce<TransformedData>((data, [k, v]) => {
  82. data.config ??= {};
  83. data.alertRule ??= {};
  84. if (k === 'alertRule.targets') {
  85. const alertTargets = (v as string[] | undefined)?.map(item => {
  86. // See SentryMemberTeamSelectorField to understand why these are strings
  87. const [type, id] = item.split(':');
  88. const targetType = RULE_TARGET_MAP[type];
  89. return {targetType, targetIdentifier: Number(id)};
  90. });
  91. data.alertRule.targets = alertTargets;
  92. return data;
  93. }
  94. if (k === 'alertRule.environment') {
  95. const environment = v === '' ? undefined : (v as string);
  96. data.alertRule.environment = environment;
  97. return data;
  98. }
  99. if (k === 'config.schedule.frequency' || k === 'config.schedule.interval') {
  100. if (!Array.isArray(data.config.schedule)) {
  101. data.config.schedule = [1, 'hour'];
  102. }
  103. }
  104. if (Array.isArray(data.config.schedule) && k === 'config.schedule.frequency') {
  105. data.config.schedule[0] = parseInt(v as string, 10);
  106. return data;
  107. }
  108. if (Array.isArray(data.config.schedule) && k === 'config.schedule.interval') {
  109. data.config.schedule[1] = v as IntervalConfig['schedule'][1];
  110. return data;
  111. }
  112. if (k.startsWith('config.')) {
  113. data.config[k.substring(7)] = v;
  114. return data;
  115. }
  116. data[k] = v;
  117. return data;
  118. }, {});
  119. // If targets are not specified, don't send alert rule config to backend
  120. if (!result.alertRule?.targets) {
  121. result.alertRule = undefined;
  122. }
  123. return result;
  124. }
  125. /**
  126. * Transform config field errors from the error response
  127. */
  128. export function mapMonitorFormErrors(responseJson?: any) {
  129. if (responseJson.config === undefined) {
  130. return responseJson;
  131. }
  132. // Bring nested config entries to the top
  133. const {config, ...responseRest} = responseJson;
  134. const configErrors = Object.fromEntries(
  135. Object.entries(config).map(([key, value]) => [`config.${key}`, value])
  136. );
  137. return {...responseRest, ...configErrors};
  138. }
  139. function MonitorForm({
  140. monitor,
  141. submitLabel,
  142. apiEndpoint,
  143. apiMethod,
  144. onSubmitSuccess,
  145. }: Props) {
  146. const form = useRef(
  147. new FormModel({
  148. transformData: transformMonitorFormData,
  149. mapFormErrors: mapMonitorFormErrors,
  150. })
  151. );
  152. const organization = useOrganization();
  153. const {projects} = useProjects();
  154. const {selection} = usePageFilters();
  155. function formDataFromConfig(type: MonitorType, config: MonitorConfig) {
  156. const rv = {};
  157. switch (type) {
  158. case 'cron_job':
  159. rv['config.schedule_type'] = config.schedule_type;
  160. rv['config.checkin_margin'] = config.checkin_margin;
  161. rv['config.max_runtime'] = config.max_runtime;
  162. rv['config.failure_issue_threshold'] = config.failure_issue_threshold;
  163. rv['config.recovery_threshold'] = config.recovery_threshold;
  164. switch (config.schedule_type) {
  165. case 'interval':
  166. rv['config.schedule.frequency'] = config.schedule[0];
  167. rv['config.schedule.interval'] = config.schedule[1];
  168. break;
  169. case 'crontab':
  170. default:
  171. rv['config.schedule'] = config.schedule;
  172. rv['config.timezone'] = config.timezone;
  173. }
  174. break;
  175. default:
  176. }
  177. return rv;
  178. }
  179. const selectedProjectId = selection.projects[0];
  180. const selectedProject = selectedProjectId
  181. ? projects.find(p => p.id === selectedProjectId.toString())
  182. : null;
  183. const isSuperuser = isActiveSuperuser();
  184. const filteredProjects = projects.filter(project => isSuperuser || project.isMember);
  185. const alertRuleTarget = monitor?.alertRule?.targets.map(
  186. target => `${RULES_SELECTOR_MAP[target.targetType]}:${target.targetIdentifier}`
  187. );
  188. const envOptions = selectedProject?.environments.map(e => ({value: e, label: e})) ?? [];
  189. const alertRuleEnvs = [
  190. {
  191. label: 'All Environments',
  192. value: '',
  193. },
  194. ...envOptions,
  195. ];
  196. const hasIssuePlatform = organization.features.includes('issue-platform');
  197. return (
  198. <Form
  199. allowUndo
  200. requireChanges
  201. apiEndpoint={apiEndpoint}
  202. apiMethod={apiMethod}
  203. model={form.current}
  204. initialData={
  205. monitor
  206. ? {
  207. name: monitor.name,
  208. slug: monitor.slug,
  209. type: monitor.type ?? DEFAULT_MONITOR_TYPE,
  210. project: monitor.project.slug,
  211. 'alertRule.targets': alertRuleTarget,
  212. 'alertRule.environment': monitor.alertRule?.environment,
  213. ...formDataFromConfig(monitor.type, monitor.config),
  214. }
  215. : {
  216. project: selectedProject ? selectedProject.slug : null,
  217. type: DEFAULT_MONITOR_TYPE,
  218. }
  219. }
  220. onSubmitSuccess={onSubmitSuccess}
  221. submitLabel={submitLabel}
  222. >
  223. <StyledList symbol="colored-numeric">
  224. <StyledListItem>{t('Add a name and project')}</StyledListItem>
  225. <ListItemSubText>{t('The name will show up in notifications.')}</ListItemSubText>
  226. <InputGroup>
  227. <StyledTextField
  228. name="name"
  229. aria-label={t('Name')}
  230. placeholder={t('My Cron Job')}
  231. required
  232. stacked
  233. inline={false}
  234. />
  235. {monitor && (
  236. <StyledTextField
  237. name="slug"
  238. aria-label={t('Slug')}
  239. help={tct(
  240. 'The [strong:monitor-slug] is used to uniquely identify your monitor within your organization. Changing this slug will require updates to any instrumented check-in calls.',
  241. {strong: <strong />}
  242. )}
  243. placeholder={t('monitor-slug')}
  244. required
  245. stacked
  246. inline={false}
  247. transformInput={slugify}
  248. />
  249. )}
  250. <StyledSentryProjectSelectorField
  251. name="project"
  252. aria-label={t('Project')}
  253. projects={filteredProjects}
  254. placeholder={t('Choose Project')}
  255. disabled={!!monitor}
  256. disabledReason={t('Existing monitors cannot be moved between projects')}
  257. valueIsSlug
  258. required
  259. stacked
  260. inline={false}
  261. />
  262. </InputGroup>
  263. <StyledListItem>{t('Set your schedule')}</StyledListItem>
  264. <ListItemSubText>
  265. {tct('You can use [link:the crontab syntax] or our interval schedule.', {
  266. link: <ExternalLink href="https://en.wikipedia.org/wiki/Cron" />,
  267. })}
  268. </ListItemSubText>
  269. <InputGroup>
  270. <StyledSelectField
  271. name="config.schedule_type"
  272. aria-label={t('Schedule Type')}
  273. options={SCHEDULE_OPTIONS}
  274. defaultValue={ScheduleType.CRONTAB}
  275. orientInline
  276. required
  277. stacked
  278. inline={false}
  279. />
  280. <Observer>
  281. {() => {
  282. const scheduleType = form.current.getValue('config.schedule_type');
  283. const parsedSchedule =
  284. scheduleType === 'crontab'
  285. ? crontabAsText(
  286. form.current.getValue('config.schedule')?.toString() ?? ''
  287. )
  288. : null;
  289. if (scheduleType === 'crontab') {
  290. return (
  291. <MultiColumnInput columns="1fr 2fr">
  292. <StyledTextField
  293. name="config.schedule"
  294. aria-label={t('Crontab Schedule')}
  295. placeholder="* * * * *"
  296. defaultValue={DEFAULT_CRONTAB}
  297. css={{input: {fontFamily: commonTheme.text.familyMono}}}
  298. required
  299. stacked
  300. inline={false}
  301. />
  302. <StyledSelectField
  303. name="config.timezone"
  304. aria-label={t('Timezone')}
  305. defaultValue="UTC"
  306. options={timezoneOptions}
  307. required
  308. stacked
  309. inline={false}
  310. />
  311. {parsedSchedule && <CronstrueText>"{parsedSchedule}"</CronstrueText>}
  312. </MultiColumnInput>
  313. );
  314. }
  315. if (scheduleType === 'interval') {
  316. return (
  317. <MultiColumnInput columns="auto 1fr 2fr">
  318. <LabelText>{t('Every')}</LabelText>
  319. <StyledNumberField
  320. name="config.schedule.frequency"
  321. aria-label={t('Interval Frequency')}
  322. placeholder="e.g. 1"
  323. defaultValue="1"
  324. min={1}
  325. required
  326. stacked
  327. inline={false}
  328. />
  329. <StyledSelectField
  330. name="config.schedule.interval"
  331. aria-label={t('Interval Type')}
  332. options={getScheduleIntervals(
  333. Number(form.current.getValue('config.schedule.frequency') ?? 1)
  334. )}
  335. defaultValue="day"
  336. required
  337. stacked
  338. inline={false}
  339. />
  340. </MultiColumnInput>
  341. );
  342. }
  343. return null;
  344. }}
  345. </Observer>
  346. </InputGroup>
  347. <StyledListItem>{t('Set margins')}</StyledListItem>
  348. <ListItemSubText>
  349. {t('Configure when we mark your monitor as failed or missed.')}
  350. </ListItemSubText>
  351. <InputGroup>
  352. <Panel>
  353. <PanelBody>
  354. <NumberField
  355. name="config.checkin_margin"
  356. min={CHECKIN_MARGIN_MINIMUM}
  357. placeholder={tn(
  358. 'Defaults to %s minute',
  359. 'Defaults to %s minutes',
  360. DEFAULT_CHECKIN_MARGIN
  361. )}
  362. help={t('Number of minutes before a check-in is considered missed.')}
  363. label={t('Grace Period')}
  364. />
  365. <NumberField
  366. name="config.max_runtime"
  367. min={TIMEOUT_MINIMUM}
  368. placeholder={tn(
  369. 'Defaults to %s minute',
  370. 'Defaults to %s minutes',
  371. DEFAULT_MAX_RUNTIME
  372. )}
  373. help={t(
  374. 'Number of a minutes before an in-progress check-in is marked timed out.'
  375. )}
  376. label={t('Max Runtime')}
  377. />
  378. </PanelBody>
  379. </Panel>
  380. </InputGroup>
  381. {hasIssuePlatform && (
  382. <Fragment>
  383. <StyledListItem>{t('Set thresholds')}</StyledListItem>
  384. <ListItemSubText>
  385. {t('Configure when an issue is created or resolved.')}
  386. </ListItemSubText>
  387. <InputGroup>
  388. <Panel>
  389. <PanelBody>
  390. <NumberField
  391. name="config.failure_issue_threshold"
  392. min={1}
  393. placeholder="1"
  394. help={t(
  395. 'Create a new issue when this many consecutive missed or error check-ins are processed.'
  396. )}
  397. label={t('Failure Tolerance')}
  398. />
  399. <NumberField
  400. name="config.recovery_threshold"
  401. min={1}
  402. placeholder="1"
  403. help={t(
  404. 'Resolve the issue when this many consecutive healthy check-ins are processed.'
  405. )}
  406. label={t('Recovery Tolerance')}
  407. />
  408. </PanelBody>
  409. </Panel>
  410. </InputGroup>
  411. </Fragment>
  412. )}
  413. <StyledListItem>{t('Notifications')}</StyledListItem>
  414. <ListItemSubText>
  415. {t('Configure who to notify upon issue creation and when.')}
  416. </ListItemSubText>
  417. <InputGroup>
  418. <Panel>
  419. <PanelBody>
  420. {monitor?.config.alert_rule_id && (
  421. <AlertLink
  422. priority="muted"
  423. to={normalizeUrl(
  424. `/alerts/rules/${monitor.project.slug}/${monitor.config.alert_rule_id}/`
  425. )}
  426. withoutMarginBottom
  427. >
  428. {t('Customize this monitors notification configuration in Alerts')}
  429. </AlertLink>
  430. )}
  431. <SentryMemberTeamSelectorField
  432. label={t('Notify')}
  433. help={t('Send notifications to a member or team.')}
  434. name="alertRule.targets"
  435. multiple
  436. menuPlacement="auto"
  437. />
  438. <Observer>
  439. {() => {
  440. const selectedAssignee = form.current.getValue('alertRule.targets');
  441. // Check for falsey value or empty array value
  442. const disabled = !selectedAssignee || !selectedAssignee.toString();
  443. return (
  444. <SelectField
  445. label={t('Environment')}
  446. help={t('Only receive notifications from a specific environment.')}
  447. name="alertRule.environment"
  448. options={alertRuleEnvs}
  449. disabled={disabled}
  450. menuPlacement="auto"
  451. defaultValue=""
  452. disabledReason={t(
  453. 'Please select which teams or members to notify first.'
  454. )}
  455. />
  456. );
  457. }}
  458. </Observer>
  459. </PanelBody>
  460. </Panel>
  461. </InputGroup>
  462. </StyledList>
  463. </Form>
  464. );
  465. }
  466. export default MonitorForm;
  467. const StyledList = styled(List)`
  468. width: 800px;
  469. `;
  470. const StyledNumberField = styled(NumberField)`
  471. padding: 0;
  472. `;
  473. const StyledSelectField = styled(SelectField)`
  474. padding: 0;
  475. `;
  476. const StyledTextField = styled(TextField)`
  477. padding: 0;
  478. `;
  479. const StyledSentryProjectSelectorField = styled(SentryProjectSelectorField)`
  480. padding: 0;
  481. `;
  482. const StyledListItem = styled(ListItem)`
  483. font-size: ${p => p.theme.fontSizeExtraLarge};
  484. font-weight: bold;
  485. line-height: 1.3;
  486. `;
  487. const LabelText = styled(Text)`
  488. font-weight: bold;
  489. color: ${p => p.theme.subText};
  490. `;
  491. const ListItemSubText = styled(Text)`
  492. padding-left: ${space(4)};
  493. color: ${p => p.theme.subText};
  494. `;
  495. const InputGroup = styled('div')`
  496. padding-left: ${space(4)};
  497. margin-top: ${space(1)};
  498. margin-bottom: ${space(4)};
  499. display: flex;
  500. flex-direction: column;
  501. gap: ${space(1)};
  502. `;
  503. const MultiColumnInput = styled('div')<{columns?: string}>`
  504. display: grid;
  505. align-items: center;
  506. gap: ${space(1)};
  507. grid-template-columns: ${p => p.columns};
  508. `;
  509. const CronstrueText = styled(LabelText)`
  510. font-weight: normal;
  511. font-size: ${p => p.theme.fontSizeExtraSmall};
  512. font-family: ${p => p.theme.text.familyMono};
  513. grid-column: auto / span 2;
  514. `;