monitorForm.tsx 16 KB

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