monitorForm.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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 NumberField from 'sentry/components/forms/fields/numberField';
  7. import SelectField from 'sentry/components/forms/fields/selectField';
  8. import SentryMemberTeamSelectorField from 'sentry/components/forms/fields/sentryMemberTeamSelectorField';
  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 Panel from 'sentry/components/panels/panel';
  17. import PanelBody from 'sentry/components/panels/panelBody';
  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 useOrganization from 'sentry/utils/useOrganization';
  27. import usePageFilters from 'sentry/utils/usePageFilters';
  28. import useProjects from 'sentry/utils/useProjects';
  29. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  30. import {crontabAsText} from 'sentry/views/monitors/utils';
  31. import {
  32. IntervalConfig,
  33. Monitor,
  34. MonitorConfig,
  35. MonitorType,
  36. ScheduleType,
  37. } from '../types';
  38. const SCHEDULE_OPTIONS: SelectValue<string>[] = [
  39. {value: ScheduleType.CRONTAB, label: t('Crontab')},
  40. {value: ScheduleType.INTERVAL, label: t('Interval')},
  41. ];
  42. const DEFAULT_MONITOR_TYPE = 'cron_job';
  43. const DEFAULT_CRONTAB = '0 0 * * *';
  44. // Maps the value from the SentryMemberTeamSelectorField -> the expected alert
  45. // rule key and vice-versa.
  46. //
  47. // XXX(epurkhiser): For whatever reason the rules API wants the team and member
  48. // to be capitalized.
  49. const RULE_TARGET_MAP = {team: 'Team', member: 'Member'} as const;
  50. const RULES_SELECTOR_MAP = {Team: 'team', Member: 'member'} as const;
  51. // In minutes
  52. export const DEFAULT_MAX_RUNTIME = 30;
  53. export const DEFAULT_CHECKIN_MARGIN = 1;
  54. const CHECKIN_MARGIN_MINIMUM = 1;
  55. const TIMEOUT_MINIMUM = 1;
  56. const getIntervals = (n: number): SelectValue<string>[] => [
  57. {value: 'minute', label: tn('minute', 'minutes', n)},
  58. {value: 'hour', label: tn('hour', 'hours', n)},
  59. {value: 'day', label: tn('day', 'days', n)},
  60. {value: 'week', label: tn('week', 'weeks', n)},
  61. {value: 'month', label: tn('month', 'months', n)},
  62. {value: 'year', label: tn('year', 'years', n)},
  63. ];
  64. type Props = {
  65. apiEndpoint: string;
  66. apiMethod: FormProps['apiMethod'];
  67. onSubmitSuccess: FormProps['onSubmitSuccess'];
  68. monitor?: Monitor;
  69. submitLabel?: string;
  70. };
  71. interface TransformedData extends Partial<Omit<Monitor, 'config' | 'alertRule'>> {
  72. alertRule?: Partial<Monitor['alertRule']>;
  73. config?: Partial<Monitor['config']>;
  74. }
  75. /**
  76. * Transform sub-fields for what the API expects
  77. */
  78. function transformData(_data: Record<string, any>, model: FormModel) {
  79. const result = model.fields.toJSON().reduce<TransformedData>((data, [k, v]) => {
  80. data.config ??= {};
  81. data.alertRule ??= {};
  82. if (k === 'alertRule.targets') {
  83. const alertTargets = (v as string[] | undefined)?.map(item => {
  84. // See SentryMemberTeamSelectorField to understand why these are strings
  85. const [type, id] = item.split(':');
  86. const targetType = RULE_TARGET_MAP[type];
  87. return {targetType, targetIdentifier: Number(id)};
  88. });
  89. data.alertRule.targets = alertTargets;
  90. return data;
  91. }
  92. if (k === 'alertRule.environment') {
  93. const environment = v === '' ? undefined : (v as string);
  94. data.alertRule.environment = environment;
  95. return data;
  96. }
  97. if (k === 'config.schedule.frequency' || k === 'config.schedule.interval') {
  98. if (!Array.isArray(data.config.schedule)) {
  99. data.config.schedule = [1, 'hour'];
  100. }
  101. }
  102. if (Array.isArray(data.config.schedule) && k === 'config.schedule.frequency') {
  103. data.config.schedule[0] = parseInt(v as string, 10);
  104. return data;
  105. }
  106. if (Array.isArray(data.config.schedule) && k === 'config.schedule.interval') {
  107. data.config.schedule[1] = v as IntervalConfig['schedule'][1];
  108. return data;
  109. }
  110. if (k.startsWith('config.')) {
  111. data.config[k.substring(7)] = v;
  112. return data;
  113. }
  114. data[k] = v;
  115. return data;
  116. }, {});
  117. // If targets are not specified, don't send alert rule config to backend
  118. if (!result.alertRule?.targets) {
  119. result.alertRule = undefined;
  120. }
  121. return result;
  122. }
  123. /**
  124. * Transform config field errors from the error response
  125. */
  126. function mapFormErrors(responseJson?: any) {
  127. if (responseJson.config === undefined) {
  128. return responseJson;
  129. }
  130. // Bring nested config entries to the top
  131. const {config, ...responseRest} = responseJson;
  132. const configErrors = Object.fromEntries(
  133. Object.entries(config).map(([key, value]) => [`config.${key}`, value])
  134. );
  135. return {...responseRest, ...configErrors};
  136. }
  137. function MonitorForm({
  138. monitor,
  139. submitLabel,
  140. apiEndpoint,
  141. apiMethod,
  142. onSubmitSuccess,
  143. }: Props) {
  144. const form = useRef(new FormModel({transformData, mapFormErrors}));
  145. const organization = useOrganization();
  146. const {projects} = useProjects();
  147. const {selection} = usePageFilters();
  148. function formDataFromConfig(type: MonitorType, config: MonitorConfig) {
  149. const rv = {};
  150. switch (type) {
  151. case 'cron_job':
  152. rv['config.schedule_type'] = config.schedule_type;
  153. rv['config.checkin_margin'] = config.checkin_margin;
  154. rv['config.max_runtime'] = config.max_runtime;
  155. rv['config.failure_issue_threshold'] = config.failure_issue_threshold;
  156. rv['config.recovery_threshold'] = config.recovery_threshold;
  157. switch (config.schedule_type) {
  158. case 'interval':
  159. rv['config.schedule.frequency'] = config.schedule[0];
  160. rv['config.schedule.interval'] = config.schedule[1];
  161. break;
  162. case 'crontab':
  163. default:
  164. rv['config.schedule'] = config.schedule;
  165. rv['config.timezone'] = config.timezone;
  166. }
  167. break;
  168. default:
  169. }
  170. return rv;
  171. }
  172. const selectedProjectId = selection.projects[0];
  173. const selectedProject = selectedProjectId
  174. ? projects.find(p => p.id === selectedProjectId + '')
  175. : null;
  176. const isSuperuser = isActiveSuperuser();
  177. const filteredProjects = projects.filter(project => isSuperuser || project.isMember);
  178. const alertRuleTarget = monitor?.alertRule?.targets.map(
  179. target => `${RULES_SELECTOR_MAP[target.targetType]}:${target.targetIdentifier}`
  180. );
  181. const envOptions = selectedProject?.environments.map(e => ({value: e, label: e})) ?? [];
  182. const alertRuleEnvs = [
  183. {
  184. label: 'All Environments',
  185. value: '',
  186. },
  187. ...envOptions,
  188. ];
  189. const hasIssuePlatform = organization.features.includes('issue-platform');
  190. return (
  191. <Form
  192. allowUndo
  193. requireChanges
  194. apiEndpoint={apiEndpoint}
  195. apiMethod={apiMethod}
  196. model={form.current}
  197. initialData={
  198. monitor
  199. ? {
  200. name: monitor.name,
  201. slug: monitor.slug,
  202. type: monitor.type ?? DEFAULT_MONITOR_TYPE,
  203. project: monitor.project.slug,
  204. 'alertRule.targets': alertRuleTarget,
  205. 'alertRule.environment': monitor.alertRule?.environment,
  206. ...formDataFromConfig(monitor.type, monitor.config),
  207. }
  208. : {
  209. project: selectedProject ? selectedProject.slug : null,
  210. type: DEFAULT_MONITOR_TYPE,
  211. }
  212. }
  213. onSubmitSuccess={onSubmitSuccess}
  214. submitLabel={submitLabel}
  215. >
  216. <StyledList symbol="colored-numeric">
  217. <StyledListItem>{t('Add a name and project')}</StyledListItem>
  218. <ListItemSubText>{t('The name will show up in notifications.')}</ListItemSubText>
  219. <InputGroup>
  220. <StyledTextField
  221. name="name"
  222. placeholder={t('My Cron Job')}
  223. required
  224. stacked
  225. inline={false}
  226. />
  227. {monitor && (
  228. <StyledTextField
  229. name="slug"
  230. help={tct(
  231. '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.',
  232. {strong: <strong />}
  233. )}
  234. placeholder={t('monitor-slug')}
  235. required
  236. stacked
  237. inline={false}
  238. transformInput={slugify}
  239. />
  240. )}
  241. <StyledSentryProjectSelectorField
  242. name="project"
  243. projects={filteredProjects}
  244. placeholder={t('Choose Project')}
  245. disabled={!!monitor}
  246. disabledReason={t('Existing monitors cannot be moved between projects')}
  247. valueIsSlug
  248. required
  249. stacked
  250. inline={false}
  251. />
  252. </InputGroup>
  253. <StyledListItem>{t('Set your schedule')}</StyledListItem>
  254. <ListItemSubText>
  255. {tct('You can use [link:the crontab syntax] or our interval schedule.', {
  256. link: <ExternalLink href="https://en.wikipedia.org/wiki/Cron" />,
  257. })}
  258. </ListItemSubText>
  259. <InputGroup>
  260. {monitor !== undefined && (
  261. <StyledAlert type="info">
  262. {t(
  263. 'Any changes you make to the execution schedule will only be applied after the next expected check-in.'
  264. )}
  265. </StyledAlert>
  266. )}
  267. <StyledSelectField
  268. name="config.schedule_type"
  269. options={SCHEDULE_OPTIONS}
  270. defaultValue={ScheduleType.CRONTAB}
  271. orientInline
  272. required
  273. stacked
  274. inline={false}
  275. />
  276. <Observer>
  277. {() => {
  278. const scheduleType = form.current.getValue('config.schedule_type');
  279. const parsedSchedule =
  280. scheduleType === 'crontab'
  281. ? crontabAsText(
  282. form.current.getValue('config.schedule')?.toString() ?? ''
  283. )
  284. : null;
  285. if (scheduleType === 'crontab') {
  286. return (
  287. <MultiColumnInput columns="1fr 2fr">
  288. <StyledTextField
  289. name="config.schedule"
  290. placeholder="* * * * *"
  291. defaultValue={DEFAULT_CRONTAB}
  292. css={{input: {fontFamily: commonTheme.text.familyMono}}}
  293. required
  294. stacked
  295. inline={false}
  296. />
  297. <StyledSelectField
  298. name="config.timezone"
  299. defaultValue="UTC"
  300. options={timezoneOptions}
  301. required
  302. stacked
  303. inline={false}
  304. />
  305. {parsedSchedule && <CronstrueText>"{parsedSchedule}"</CronstrueText>}
  306. </MultiColumnInput>
  307. );
  308. }
  309. if (scheduleType === 'interval') {
  310. return (
  311. <MultiColumnInput columns="auto 1fr 2fr">
  312. <LabelText>{t('Every')}</LabelText>
  313. <StyledNumberField
  314. name="config.schedule.frequency"
  315. placeholder="e.g. 1"
  316. defaultValue="1"
  317. required
  318. stacked
  319. inline={false}
  320. />
  321. <StyledSelectField
  322. name="config.schedule.interval"
  323. options={getIntervals(
  324. Number(form.current.getValue('config.schedule.frequency') ?? 1)
  325. )}
  326. defaultValue="day"
  327. required
  328. stacked
  329. inline={false}
  330. />
  331. </MultiColumnInput>
  332. );
  333. }
  334. return null;
  335. }}
  336. </Observer>
  337. </InputGroup>
  338. <StyledListItem>{t('Set thresholds')}</StyledListItem>
  339. <ListItemSubText>
  340. {t('Configure when we mark your monitor as failed or missed.')}
  341. </ListItemSubText>
  342. <InputGroup>
  343. <Panel>
  344. <PanelBody>
  345. <NumberField
  346. name="config.checkin_margin"
  347. min={CHECKIN_MARGIN_MINIMUM}
  348. placeholder={tn(
  349. 'Defaults to %s minute',
  350. 'Defaults to %s minutes',
  351. DEFAULT_CHECKIN_MARGIN
  352. )}
  353. help={t('Number of minutes before a check-in is considered missed.')}
  354. label={t('Grace Period')}
  355. />
  356. <NumberField
  357. name="config.max_runtime"
  358. min={TIMEOUT_MINIMUM}
  359. placeholder={tn(
  360. 'Defaults to %s minute',
  361. 'Defaults to %s minutes',
  362. DEFAULT_MAX_RUNTIME
  363. )}
  364. help={t(
  365. 'Number of a minutes before an in-progress check-in is marked timed out.'
  366. )}
  367. label={t('Max Runtime')}
  368. />
  369. </PanelBody>
  370. </Panel>
  371. </InputGroup>
  372. <StyledListItem>{t('Notifications')}</StyledListItem>
  373. <ListItemSubText>{t('Configure who to notify and when.')}</ListItemSubText>
  374. <InputGroup>
  375. <Panel>
  376. <PanelBody>
  377. {monitor?.config.alert_rule_id && (
  378. <AlertLink
  379. priority="muted"
  380. to={normalizeUrl(
  381. `/alerts/rules/${monitor.project.slug}/${monitor.config.alert_rule_id}/`
  382. )}
  383. withoutMarginBottom
  384. >
  385. {t('Customize this monitors notification configuration in Alerts')}
  386. </AlertLink>
  387. )}
  388. <SentryMemberTeamSelectorField
  389. label={t('Notify')}
  390. help={t('Send notifications to a member or team.')}
  391. name="alertRule.targets"
  392. multiple
  393. menuPlacement="auto"
  394. />
  395. {hasIssuePlatform && (
  396. <Fragment>
  397. <NumberField
  398. name="config.failure_issue_threshold"
  399. min={1}
  400. placeholder="1"
  401. help={t('Create an issue after this many missed or error check-ins')}
  402. label={t('Tolerate Failures')}
  403. />
  404. <NumberField
  405. name="config.recovery_threshold"
  406. min={1}
  407. placeholder="1"
  408. help={t('Recover monitor status after this many healthy check-ins')}
  409. label={t('Recovery Threshold')}
  410. />
  411. </Fragment>
  412. )}
  413. <SelectField
  414. label={t('Environment')}
  415. help={t('Only receive notifications from a specific environment.')}
  416. name="alertRule.environment"
  417. options={alertRuleEnvs}
  418. menuPlacement="auto"
  419. defaultValue=""
  420. />
  421. </PanelBody>
  422. </Panel>
  423. </InputGroup>
  424. </StyledList>
  425. </Form>
  426. );
  427. }
  428. export default MonitorForm;
  429. const StyledList = styled(List)`
  430. width: 800px;
  431. `;
  432. const StyledAlert = styled(Alert)`
  433. margin-bottom: 0;
  434. `;
  435. const StyledNumberField = styled(NumberField)`
  436. padding: 0;
  437. `;
  438. const StyledSelectField = styled(SelectField)`
  439. padding: 0;
  440. `;
  441. const StyledTextField = styled(TextField)`
  442. padding: 0;
  443. `;
  444. const StyledSentryProjectSelectorField = styled(SentryProjectSelectorField)`
  445. padding: 0;
  446. `;
  447. const StyledListItem = styled(ListItem)`
  448. font-size: ${p => p.theme.fontSizeExtraLarge};
  449. font-weight: bold;
  450. line-height: 1.3;
  451. `;
  452. const LabelText = styled(Text)`
  453. font-weight: bold;
  454. color: ${p => p.theme.subText};
  455. `;
  456. const ListItemSubText = styled(Text)`
  457. padding-left: ${space(4)};
  458. color: ${p => p.theme.subText};
  459. `;
  460. const InputGroup = styled('div')`
  461. padding-left: ${space(4)};
  462. margin-top: ${space(1)};
  463. margin-bottom: ${space(4)};
  464. display: flex;
  465. flex-direction: column;
  466. gap: ${space(1)};
  467. `;
  468. const MultiColumnInput = styled('div')<{columns?: string}>`
  469. display: grid;
  470. align-items: center;
  471. gap: ${space(1)};
  472. grid-template-columns: ${p => p.columns};
  473. `;
  474. const CronstrueText = styled(LabelText)`
  475. font-weight: normal;
  476. font-size: ${p => p.theme.fontSizeExtraSmall};
  477. font-family: ${p => p.theme.text.familyMono};
  478. grid-column: auto / span 2;
  479. `;