monitorForm.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 {RadioOption} from 'sentry/components/forms/controls/radioGroup';
  7. import NumberField from 'sentry/components/forms/fields/numberField';
  8. import RadioField from 'sentry/components/forms/fields/radioField';
  9. import SelectField from 'sentry/components/forms/fields/selectField';
  10. import SentryMemberTeamSelectorField from 'sentry/components/forms/fields/sentryMemberTeamSelectorField';
  11. import SentryProjectSelectorField from 'sentry/components/forms/fields/sentryProjectSelectorField';
  12. import TextField from 'sentry/components/forms/fields/textField';
  13. import Form, {FormProps} from 'sentry/components/forms/form';
  14. import FormModel from 'sentry/components/forms/model';
  15. import ExternalLink from 'sentry/components/links/externalLink';
  16. import List from 'sentry/components/list';
  17. import ListItem from 'sentry/components/list/listItem';
  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 usePageFilters from 'sentry/utils/usePageFilters';
  27. import useProjects from 'sentry/utils/useProjects';
  28. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  29. import {crontabAsText} from 'sentry/views/monitors/utils';
  30. import {
  31. IntervalConfig,
  32. Monitor,
  33. MonitorConfig,
  34. MonitorType,
  35. ScheduleType,
  36. } from '../types';
  37. const SCHEDULE_OPTIONS: RadioOption<string>[] = [
  38. [ScheduleType.CRONTAB, t('Crontab')],
  39. [ScheduleType.INTERVAL, t('Interval')],
  40. ];
  41. const DEFAULT_MONITOR_TYPE = 'cron_job';
  42. 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. export const DEFAULT_MAX_RUNTIME = 30;
  51. const getIntervals = (n: number): SelectValue<string>[] => [
  52. {value: 'minute', label: tn('minute', 'minutes', n)},
  53. {value: 'hour', label: tn('hour', 'hours', n)},
  54. {value: 'day', label: tn('day', 'days', n)},
  55. {value: 'week', label: tn('week', 'weeks', n)},
  56. {value: 'month', label: tn('month', 'months', n)},
  57. {value: 'year', label: tn('year', 'years', n)},
  58. ];
  59. type Props = {
  60. apiEndpoint: string;
  61. apiMethod: FormProps['apiMethod'];
  62. onSubmitSuccess: FormProps['onSubmitSuccess'];
  63. monitor?: Monitor;
  64. submitLabel?: string;
  65. };
  66. type TransformedData = {
  67. config?: Partial<MonitorConfig>;
  68. };
  69. /**
  70. * Transform config field values into the config object
  71. */
  72. function transformData(_data: Record<string, any>, model: FormModel) {
  73. return model.fields.toJSON().reduce<TransformedData>((data, [k, v]) => {
  74. if (k === 'alertRule') {
  75. const alertTargets = (v as string[] | undefined)?.map(item => {
  76. // See SentryMemberTeamSelectorField to understand why these are strings
  77. const [type, id] = item.split(':');
  78. const targetType = RULE_TARGET_MAP[type];
  79. return {targetType, targetIdentifier: id};
  80. });
  81. data[k] = {targets: alertTargets};
  82. return data;
  83. }
  84. // We're only concerned with transforming the config
  85. if (!k.startsWith('config.')) {
  86. data[k] = v;
  87. return data;
  88. }
  89. // Default to empty object
  90. data.config ??= {};
  91. if (k === 'config.schedule.frequency' || k === 'config.schedule.interval') {
  92. if (!Array.isArray(data.config.schedule)) {
  93. data.config.schedule = [1, 'hour'];
  94. }
  95. }
  96. if (Array.isArray(data.config.schedule) && k === 'config.schedule.frequency') {
  97. data.config.schedule[0] = parseInt(v as string, 10);
  98. return data;
  99. }
  100. if (Array.isArray(data.config.schedule) && k === 'config.schedule.interval') {
  101. data.config.schedule[1] = v as IntervalConfig['schedule'][1];
  102. return data;
  103. }
  104. data.config[k.substring(7)] = v;
  105. return data;
  106. }, {});
  107. }
  108. /**
  109. * Transform config field errors from the error response
  110. */
  111. function mapFormErrors(responseJson?: any) {
  112. if (responseJson.config === undefined) {
  113. return responseJson;
  114. }
  115. // Bring nested config entries to the top
  116. const {config, ...responseRest} = responseJson;
  117. const configErrors = Object.fromEntries(
  118. Object.entries(config).map(([key, value]) => [`config.${key}`, value])
  119. );
  120. return {...responseRest, ...configErrors};
  121. }
  122. function MonitorForm({
  123. monitor,
  124. submitLabel,
  125. apiEndpoint,
  126. apiMethod,
  127. onSubmitSuccess,
  128. }: Props) {
  129. const form = useRef(new FormModel({transformData, mapFormErrors}));
  130. const {projects} = useProjects();
  131. const {selection} = usePageFilters();
  132. function formDataFromConfig(type: MonitorType, config: MonitorConfig) {
  133. const rv = {};
  134. switch (type) {
  135. case 'cron_job':
  136. rv['config.schedule_type'] = config.schedule_type;
  137. rv['config.checkin_margin'] = config.checkin_margin;
  138. rv['config.max_runtime'] = config.max_runtime;
  139. switch (config.schedule_type) {
  140. case 'interval':
  141. rv['config.schedule.frequency'] = config.schedule[0];
  142. rv['config.schedule.interval'] = config.schedule[1];
  143. break;
  144. case 'crontab':
  145. default:
  146. rv['config.schedule'] = config.schedule;
  147. rv['config.timezone'] = config.timezone;
  148. }
  149. break;
  150. default:
  151. }
  152. return rv;
  153. }
  154. const selectedProjectId = selection.projects[0];
  155. const selectedProject = selectedProjectId
  156. ? projects.find(p => p.id === selectedProjectId + '')
  157. : null;
  158. const isSuperuser = isActiveSuperuser();
  159. const filteredProjects = projects.filter(project => isSuperuser || project.isMember);
  160. const alertRule = monitor?.alertRule?.targets.map(
  161. target => `${RULES_SELECTOR_MAP[target.targetType]}:${target.targetIdentifier}`
  162. );
  163. return (
  164. <Form
  165. allowUndo
  166. requireChanges
  167. apiEndpoint={apiEndpoint}
  168. apiMethod={apiMethod}
  169. model={form.current}
  170. initialData={
  171. monitor
  172. ? {
  173. name: monitor.name,
  174. slug: monitor.slug,
  175. type: monitor.type ?? DEFAULT_MONITOR_TYPE,
  176. project: monitor.project.slug,
  177. alertRule,
  178. ...formDataFromConfig(monitor.type, monitor.config),
  179. }
  180. : {
  181. project: selectedProject ? selectedProject.slug : null,
  182. type: DEFAULT_MONITOR_TYPE,
  183. }
  184. }
  185. onSubmitSuccess={onSubmitSuccess}
  186. submitLabel={submitLabel}
  187. >
  188. <StyledList symbol="colored-numeric">
  189. <StyledListItem>{t('Add a name and project')}</StyledListItem>
  190. <ListItemSubText>
  191. {t('The monitor name will show up in alerts and notifications')}
  192. </ListItemSubText>
  193. <InputGroup>
  194. <StyledTextField
  195. name="name"
  196. placeholder={t('My Cron Job')}
  197. required
  198. stacked
  199. inline={false}
  200. />
  201. {monitor && (
  202. <StyledTextField
  203. name="slug"
  204. help={tct(
  205. '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.',
  206. {strong: <strong />}
  207. )}
  208. placeholder={t('monitor-slug')}
  209. required
  210. stacked
  211. inline={false}
  212. transformInput={slugify}
  213. />
  214. )}
  215. <StyledSentryProjectSelectorField
  216. name="project"
  217. projects={filteredProjects}
  218. placeholder={t('Choose Project')}
  219. disabled={!!monitor}
  220. disabledReason={t('Existing monitors cannot be moved between projects')}
  221. valueIsSlug
  222. required
  223. stacked
  224. inline={false}
  225. />
  226. </InputGroup>
  227. <StyledListItem>{t('Choose your schedule type')}</StyledListItem>
  228. <ListItemSubText>
  229. {tct('You can use [link:the crontab syntax] or our interval schedule.', {
  230. link: <ExternalLink href="https://en.wikipedia.org/wiki/Cron" />,
  231. })}
  232. </ListItemSubText>
  233. <InputGroup>
  234. <RadioField
  235. name="config.schedule_type"
  236. choices={SCHEDULE_OPTIONS}
  237. defaultValue={ScheduleType.CRONTAB}
  238. orientInline
  239. required
  240. stacked
  241. inline={false}
  242. />
  243. </InputGroup>
  244. <StyledListItem>{t('Choose your schedule')}</StyledListItem>
  245. <ListItemSubText>
  246. {t('How often you expect your recurring jobs to run.')}
  247. </ListItemSubText>
  248. <InputGroup>
  249. {monitor !== undefined && (
  250. <Alert type="info">
  251. {t(
  252. 'Any changes you make to the execution schedule will only be applied after the next expected check-in.'
  253. )}
  254. </Alert>
  255. )}
  256. <Observer>
  257. {() => {
  258. const scheduleType = form.current.getValue('config.schedule_type');
  259. const parsedSchedule =
  260. scheduleType === 'crontab'
  261. ? crontabAsText(
  262. form.current.getValue('config.schedule')?.toString() ?? ''
  263. )
  264. : null;
  265. if (scheduleType === 'crontab') {
  266. return (
  267. <ScheduleGroupInputs>
  268. <StyledTextField
  269. name="config.schedule"
  270. placeholder="* * * * *"
  271. defaultValue={DEFAULT_CRONTAB}
  272. css={{input: {fontFamily: commonTheme.text.familyMono}}}
  273. required
  274. stacked
  275. inline={false}
  276. />
  277. <StyledSelectField
  278. name="config.timezone"
  279. defaultValue="UTC"
  280. options={timezoneOptions}
  281. required
  282. stacked
  283. inline={false}
  284. />
  285. {parsedSchedule && <CronstrueText>"{parsedSchedule}"</CronstrueText>}
  286. </ScheduleGroupInputs>
  287. );
  288. }
  289. if (scheduleType === 'interval') {
  290. return (
  291. <ScheduleGroupInputs interval>
  292. <LabelText>{t('Every')}</LabelText>
  293. <StyledNumberField
  294. name="config.schedule.frequency"
  295. placeholder="e.g. 1"
  296. defaultValue="1"
  297. required
  298. stacked
  299. inline={false}
  300. />
  301. <StyledSelectField
  302. name="config.schedule.interval"
  303. options={getIntervals(
  304. Number(form.current.getValue('config.schedule.frequency') ?? 1)
  305. )}
  306. defaultValue="day"
  307. required
  308. stacked
  309. inline={false}
  310. />
  311. </ScheduleGroupInputs>
  312. );
  313. }
  314. return null;
  315. }}
  316. </Observer>
  317. </InputGroup>
  318. <StyledListItem>{t('Set a missed status')}</StyledListItem>
  319. <ListItemSubText>
  320. {t("The number of minutes we'll wait before we consider a check-in as missed.")}
  321. </ListItemSubText>
  322. <InputGroup>
  323. <StyledNumberField
  324. name="config.checkin_margin"
  325. placeholder="Defaults to 0 minutes"
  326. stacked
  327. inline={false}
  328. />
  329. </InputGroup>
  330. <StyledListItem>{t('Set a failed status')}</StyledListItem>
  331. <ListItemSubText>
  332. {t(
  333. "The number of minutes a check-in is allowed to run before it's considered failed."
  334. )}
  335. </ListItemSubText>
  336. <InputGroup>
  337. <StyledNumberField
  338. name="config.max_runtime"
  339. placeholder={`Defaults to ${DEFAULT_MAX_RUNTIME} minutes`}
  340. stacked
  341. inline={false}
  342. />
  343. </InputGroup>
  344. <Fragment>
  345. <StyledListItem>{t('Notify members')}</StyledListItem>
  346. <ListItemSubText>
  347. {t(
  348. 'Tell us who to notify when a check-in reaches the thresholds above or has an error. You can send notifications to members or teams.'
  349. )}
  350. </ListItemSubText>
  351. <InputGroup>
  352. {monitor?.config.alert_rule_id && (
  353. <AlertLink
  354. priority="muted"
  355. to={normalizeUrl(
  356. `/alerts/rules/${monitor.project.slug}/${monitor.config.alert_rule_id}/`
  357. )}
  358. >
  359. {t('Customize this monitors notification configuration in Alerts')}
  360. </AlertLink>
  361. )}
  362. <StyledSentryMemberTeamSelectorField
  363. name="alertRule"
  364. multiple
  365. stacked
  366. inline={false}
  367. menuPlacement="auto"
  368. />
  369. </InputGroup>
  370. </Fragment>
  371. </StyledList>
  372. </Form>
  373. );
  374. }
  375. export default MonitorForm;
  376. const StyledList = styled(List)`
  377. width: 600px;
  378. `;
  379. const StyledNumberField = styled(NumberField)`
  380. padding: 0;
  381. `;
  382. const StyledSelectField = styled(SelectField)`
  383. padding: 0;
  384. `;
  385. const StyledTextField = styled(TextField)`
  386. padding: 0;
  387. `;
  388. const StyledSentryProjectSelectorField = styled(SentryProjectSelectorField)`
  389. padding: 0;
  390. `;
  391. const StyledSentryMemberTeamSelectorField = styled(SentryMemberTeamSelectorField)`
  392. padding: 0;
  393. `;
  394. const StyledListItem = styled(ListItem)`
  395. font-size: ${p => p.theme.fontSizeExtraLarge};
  396. font-weight: bold;
  397. line-height: 1.3;
  398. `;
  399. const LabelText = styled(Text)`
  400. font-weight: bold;
  401. color: ${p => p.theme.subText};
  402. `;
  403. const ListItemSubText = styled(LabelText)`
  404. font-weight: normal;
  405. padding-left: ${space(4)};
  406. `;
  407. const InputGroup = styled('div')`
  408. padding-left: ${space(4)};
  409. margin-top: ${space(1)};
  410. margin-bottom: ${space(4)};
  411. display: flex;
  412. flex-direction: column;
  413. gap: ${space(1)};
  414. `;
  415. const ScheduleGroupInputs = styled('div')<{interval?: boolean}>`
  416. display: grid;
  417. align-items: center;
  418. gap: ${space(1)};
  419. grid-template-columns: ${p => p.interval && 'auto'} 1fr 2fr;
  420. `;
  421. const CronstrueText = styled(LabelText)`
  422. font-weight: normal;
  423. font-size: ${p => p.theme.fontSizeExtraSmall};
  424. font-family: ${p => p.theme.text.familyMono};
  425. grid-column: auto / span 2;
  426. `;