monitorForm.tsx 12 KB

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