monitorForm.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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 + '')
  183. : null;
  184. const isSuperuser = isActiveSuperuser();
  185. const filteredProjects = projects.filter(project => isSuperuser || project.isMember);
  186. const alertRuleTarget = monitor?.alertRule?.targets.map(
  187. target => `${RULES_SELECTOR_MAP[target.targetType]}:${target.targetIdentifier}`
  188. );
  189. const envOptions = selectedProject?.environments.map(e => ({value: e, label: e})) ?? [];
  190. const alertRuleEnvs = [
  191. {
  192. label: 'All Environments',
  193. value: '',
  194. },
  195. ...envOptions,
  196. ];
  197. const hasIssuePlatform = organization.features.includes('issue-platform');
  198. return (
  199. <Form
  200. allowUndo
  201. requireChanges
  202. apiEndpoint={apiEndpoint}
  203. apiMethod={apiMethod}
  204. model={form.current}
  205. initialData={
  206. monitor
  207. ? {
  208. name: monitor.name,
  209. slug: monitor.slug,
  210. type: monitor.type ?? DEFAULT_MONITOR_TYPE,
  211. project: monitor.project.slug,
  212. 'alertRule.targets': alertRuleTarget,
  213. 'alertRule.environment': monitor.alertRule?.environment,
  214. ...formDataFromConfig(monitor.type, monitor.config),
  215. }
  216. : {
  217. project: selectedProject ? selectedProject.slug : null,
  218. type: DEFAULT_MONITOR_TYPE,
  219. }
  220. }
  221. onSubmitSuccess={onSubmitSuccess}
  222. submitLabel={submitLabel}
  223. >
  224. <StyledList symbol="colored-numeric">
  225. <StyledListItem>{t('Add a name and project')}</StyledListItem>
  226. <ListItemSubText>{t('The name will show up in notifications.')}</ListItemSubText>
  227. <InputGroup>
  228. <StyledTextField
  229. name="name"
  230. placeholder={t('My Cron Job')}
  231. required
  232. stacked
  233. inline={false}
  234. />
  235. {monitor && (
  236. <StyledTextField
  237. name="slug"
  238. help={tct(
  239. '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.',
  240. {strong: <strong />}
  241. )}
  242. placeholder={t('monitor-slug')}
  243. required
  244. stacked
  245. inline={false}
  246. transformInput={slugify}
  247. />
  248. )}
  249. <StyledSentryProjectSelectorField
  250. name="project"
  251. projects={filteredProjects}
  252. placeholder={t('Choose Project')}
  253. disabled={!!monitor}
  254. disabledReason={t('Existing monitors cannot be moved between projects')}
  255. valueIsSlug
  256. required
  257. stacked
  258. inline={false}
  259. />
  260. </InputGroup>
  261. <StyledListItem>{t('Set your schedule')}</StyledListItem>
  262. <ListItemSubText>
  263. {tct('You can use [link:the crontab syntax] or our interval schedule.', {
  264. link: <ExternalLink href="https://en.wikipedia.org/wiki/Cron" />,
  265. })}
  266. </ListItemSubText>
  267. <InputGroup>
  268. {monitor !== undefined && (
  269. <StyledAlert type="info">
  270. {t(
  271. 'Any changes you make to the execution schedule will only be applied after the next expected check-in.'
  272. )}
  273. </StyledAlert>
  274. )}
  275. <StyledSelectField
  276. name="config.schedule_type"
  277. options={SCHEDULE_OPTIONS}
  278. defaultValue={ScheduleType.CRONTAB}
  279. orientInline
  280. required
  281. stacked
  282. inline={false}
  283. />
  284. <Observer>
  285. {() => {
  286. const scheduleType = form.current.getValue('config.schedule_type');
  287. const parsedSchedule =
  288. scheduleType === 'crontab'
  289. ? crontabAsText(
  290. form.current.getValue('config.schedule')?.toString() ?? ''
  291. )
  292. : null;
  293. if (scheduleType === 'crontab') {
  294. return (
  295. <MultiColumnInput columns="1fr 2fr">
  296. <StyledTextField
  297. name="config.schedule"
  298. placeholder="* * * * *"
  299. defaultValue={DEFAULT_CRONTAB}
  300. css={{input: {fontFamily: commonTheme.text.familyMono}}}
  301. required
  302. stacked
  303. inline={false}
  304. />
  305. <StyledSelectField
  306. name="config.timezone"
  307. defaultValue="UTC"
  308. options={timezoneOptions}
  309. required
  310. stacked
  311. inline={false}
  312. />
  313. {parsedSchedule && <CronstrueText>"{parsedSchedule}"</CronstrueText>}
  314. </MultiColumnInput>
  315. );
  316. }
  317. if (scheduleType === 'interval') {
  318. return (
  319. <MultiColumnInput columns="auto 1fr 2fr">
  320. <LabelText>{t('Every')}</LabelText>
  321. <StyledNumberField
  322. name="config.schedule.frequency"
  323. placeholder="e.g. 1"
  324. defaultValue="1"
  325. required
  326. stacked
  327. inline={false}
  328. />
  329. <StyledSelectField
  330. name="config.schedule.interval"
  331. options={getScheduleIntervals(
  332. Number(form.current.getValue('config.schedule.frequency') ?? 1)
  333. )}
  334. defaultValue="day"
  335. required
  336. stacked
  337. inline={false}
  338. />
  339. </MultiColumnInput>
  340. );
  341. }
  342. return null;
  343. }}
  344. </Observer>
  345. </InputGroup>
  346. <StyledListItem>{t('Set thresholds')}</StyledListItem>
  347. <ListItemSubText>
  348. {t('Configure when we mark your monitor as failed or missed.')}
  349. </ListItemSubText>
  350. <InputGroup>
  351. <Panel>
  352. <PanelBody>
  353. <NumberField
  354. name="config.checkin_margin"
  355. min={CHECKIN_MARGIN_MINIMUM}
  356. placeholder={tn(
  357. 'Defaults to %s minute',
  358. 'Defaults to %s minutes',
  359. DEFAULT_CHECKIN_MARGIN
  360. )}
  361. help={t('Number of minutes before a check-in is considered missed.')}
  362. label={t('Grace Period')}
  363. />
  364. <NumberField
  365. name="config.max_runtime"
  366. min={TIMEOUT_MINIMUM}
  367. placeholder={tn(
  368. 'Defaults to %s minute',
  369. 'Defaults to %s minutes',
  370. DEFAULT_MAX_RUNTIME
  371. )}
  372. help={t(
  373. 'Number of a minutes before an in-progress check-in is marked timed out.'
  374. )}
  375. label={t('Max Runtime')}
  376. />
  377. </PanelBody>
  378. </Panel>
  379. </InputGroup>
  380. <StyledListItem>{t('Notifications')}</StyledListItem>
  381. <ListItemSubText>{t('Configure who to notify and when.')}</ListItemSubText>
  382. <InputGroup>
  383. <Panel>
  384. <PanelBody>
  385. {monitor?.config.alert_rule_id && (
  386. <AlertLink
  387. priority="muted"
  388. to={normalizeUrl(
  389. `/alerts/rules/${monitor.project.slug}/${monitor.config.alert_rule_id}/`
  390. )}
  391. withoutMarginBottom
  392. >
  393. {t('Customize this monitors notification configuration in Alerts')}
  394. </AlertLink>
  395. )}
  396. <SentryMemberTeamSelectorField
  397. label={t('Notify')}
  398. help={t('Send notifications to a member or team.')}
  399. name="alertRule.targets"
  400. multiple
  401. menuPlacement="auto"
  402. />
  403. {hasIssuePlatform && (
  404. <Fragment>
  405. <NumberField
  406. name="config.failure_issue_threshold"
  407. min={1}
  408. placeholder="1"
  409. help={t(
  410. 'Create a new issue when this many consecutive missed or error check-ins are processed.'
  411. )}
  412. label={t('Failure Tolerance')}
  413. />
  414. <NumberField
  415. name="config.recovery_threshold"
  416. min={1}
  417. placeholder="1"
  418. help={t(
  419. 'Resolve the issue when this many consecutive healthy check-ins are processed.'
  420. )}
  421. label={t('Recovery Tolerance')}
  422. />
  423. </Fragment>
  424. )}
  425. <SelectField
  426. label={t('Environment')}
  427. help={t('Only receive notifications from a specific environment.')}
  428. name="alertRule.environment"
  429. options={alertRuleEnvs}
  430. menuPlacement="auto"
  431. defaultValue=""
  432. />
  433. </PanelBody>
  434. </Panel>
  435. </InputGroup>
  436. </StyledList>
  437. </Form>
  438. );
  439. }
  440. export default MonitorForm;
  441. const StyledList = styled(List)`
  442. width: 800px;
  443. `;
  444. const StyledAlert = styled(Alert)`
  445. margin-bottom: 0;
  446. `;
  447. const StyledNumberField = styled(NumberField)`
  448. padding: 0;
  449. `;
  450. const StyledSelectField = styled(SelectField)`
  451. padding: 0;
  452. `;
  453. const StyledTextField = styled(TextField)`
  454. padding: 0;
  455. `;
  456. const StyledSentryProjectSelectorField = styled(SentryProjectSelectorField)`
  457. padding: 0;
  458. `;
  459. const StyledListItem = styled(ListItem)`
  460. font-size: ${p => p.theme.fontSizeExtraLarge};
  461. font-weight: bold;
  462. line-height: 1.3;
  463. `;
  464. const LabelText = styled(Text)`
  465. font-weight: bold;
  466. color: ${p => p.theme.subText};
  467. `;
  468. const ListItemSubText = styled(Text)`
  469. padding-left: ${space(4)};
  470. color: ${p => p.theme.subText};
  471. `;
  472. const InputGroup = styled('div')`
  473. padding-left: ${space(4)};
  474. margin-top: ${space(1)};
  475. margin-bottom: ${space(4)};
  476. display: flex;
  477. flex-direction: column;
  478. gap: ${space(1)};
  479. `;
  480. const MultiColumnInput = styled('div')<{columns?: string}>`
  481. display: grid;
  482. align-items: center;
  483. gap: ${space(1)};
  484. grid-template-columns: ${p => p.columns};
  485. `;
  486. const CronstrueText = styled(LabelText)`
  487. font-weight: normal;
  488. font-size: ${p => p.theme.fontSizeExtraSmall};
  489. font-family: ${p => p.theme.text.familyMono};
  490. grid-column: auto / span 2;
  491. `;