monitorForm.tsx 14 KB

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