monitorForm.tsx 19 KB

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