monitorForm.tsx 13 KB

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