monitorForm.tsx 19 KB

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