monitorForm.tsx 19 KB

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