monitorForm.tsx 19 KB

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