monitorForm.tsx 16 KB

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