monitorForm.tsx 13 KB

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