monitorForm.tsx 16 KB

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