monitorForm.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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', user: 'Member'} as const;
  47. const RULES_SELECTOR_MAP = {Team: 'team', Member: 'user'} 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.scheduleType');
  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.scheduleType'] = config.schedule_type;
  158. rv['config.checkinMargin'] = config.checkin_margin;
  159. rv['config.maxRuntime'] = config.max_runtime;
  160. rv['config.failureIssueThreshold'] = config.failure_issue_threshold;
  161. rv['config.recoveryThreshold'] = 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 owner = monitor?.owner ? `${monitor.owner.type}:${monitor.owner.id}` : null;
  187. const envOptions = selectedProject?.environments.map(e => ({value: e, label: e})) ?? [];
  188. const alertRuleEnvs = [
  189. {
  190. label: 'All Environments',
  191. value: '',
  192. },
  193. ...envOptions,
  194. ];
  195. const hasIssuePlatform = organization.features.includes('issue-platform');
  196. const hasOwnership = organization.features.includes('crons-ownership');
  197. return (
  198. <Form
  199. allowUndo
  200. requireChanges
  201. apiEndpoint={apiEndpoint}
  202. apiMethod={apiMethod}
  203. model={form.current}
  204. initialData={
  205. monitor
  206. ? {
  207. name: monitor.name,
  208. slug: monitor.slug,
  209. owner: owner,
  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.scheduleType"
  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.scheduleType');
  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.checkinMargin"
  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.maxRuntime"
  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.failureIssueThreshold"
  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.recoveryThreshold"
  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. {hasOwnership && (
  422. <Fragment>
  423. <StyledListItem>{t('Set Owner')}</StyledListItem>
  424. <ListItemSubText>
  425. {t(
  426. 'Choose a team or member as the monitor owner. Issues created will be automatically assigned to the owner.'
  427. )}
  428. </ListItemSubText>
  429. <InputGroup>
  430. <Panel>
  431. <PanelBody>
  432. <SentryMemberTeamSelectorField
  433. name="owner"
  434. label={t('Owner')}
  435. help={t('Automatically assign issues to a team or user.')}
  436. menuPlacement="auto"
  437. />
  438. </PanelBody>
  439. </Panel>
  440. </InputGroup>
  441. </Fragment>
  442. )}
  443. <StyledListItem>{t('Notifications')}</StyledListItem>
  444. <ListItemSubText>
  445. {t('Configure who to notify upon issue creation and when.')}
  446. </ListItemSubText>
  447. <InputGroup>
  448. <Panel>
  449. <PanelBody>
  450. {monitor?.config.alert_rule_id && (
  451. <AlertLink
  452. priority="muted"
  453. to={normalizeUrl(
  454. `/alerts/rules/${monitor.project.slug}/${monitor.config.alert_rule_id}/`
  455. )}
  456. withoutMarginBottom
  457. >
  458. {t('Customize this monitors notification configuration in Alerts')}
  459. </AlertLink>
  460. )}
  461. <SentryMemberTeamSelectorField
  462. label={t('Notify')}
  463. help={t('Send notifications to a member or team.')}
  464. name="alertRule.targets"
  465. multiple
  466. menuPlacement="auto"
  467. />
  468. <Observer>
  469. {() => {
  470. const selectedAssignee = form.current.getValue('alertRule.targets');
  471. // Check for falsey value or empty array value
  472. const disabled = !selectedAssignee || !selectedAssignee.toString();
  473. return (
  474. <SelectField
  475. label={t('Environment')}
  476. help={t('Only receive notifications from a specific environment.')}
  477. name="alertRule.environment"
  478. options={alertRuleEnvs}
  479. disabled={disabled}
  480. menuPlacement="auto"
  481. defaultValue=""
  482. disabledReason={t(
  483. 'Please select which teams or members to notify first.'
  484. )}
  485. />
  486. );
  487. }}
  488. </Observer>
  489. </PanelBody>
  490. </Panel>
  491. </InputGroup>
  492. </StyledList>
  493. </Form>
  494. );
  495. }
  496. export default MonitorForm;
  497. const StyledList = styled(List)`
  498. width: 800px;
  499. `;
  500. const StyledAlert = styled(Alert)`
  501. margin-bottom: 0;
  502. `;
  503. const StyledNumberField = styled(NumberField)`
  504. padding: 0;
  505. `;
  506. const StyledSelectField = styled(SelectField)`
  507. padding: 0;
  508. `;
  509. const StyledTextField = styled(TextField)`
  510. padding: 0;
  511. `;
  512. const StyledSentryProjectSelectorField = styled(SentryProjectSelectorField)`
  513. padding: 0;
  514. `;
  515. const StyledListItem = styled(ListItem)`
  516. font-size: ${p => p.theme.fontSizeExtraLarge};
  517. font-weight: bold;
  518. line-height: 1.3;
  519. `;
  520. const LabelText = styled(Text)`
  521. font-weight: bold;
  522. color: ${p => p.theme.subText};
  523. `;
  524. const ListItemSubText = styled(Text)`
  525. padding-left: ${space(4)};
  526. color: ${p => p.theme.subText};
  527. `;
  528. const InputGroup = styled('div')`
  529. padding-left: ${space(4)};
  530. margin-top: ${space(1)};
  531. margin-bottom: ${space(4)};
  532. display: flex;
  533. flex-direction: column;
  534. gap: ${space(1)};
  535. `;
  536. const MultiColumnInput = styled('div')<{columns?: string}>`
  537. display: grid;
  538. align-items: center;
  539. gap: ${space(1)};
  540. grid-template-columns: ${p => p.columns};
  541. `;
  542. const CronstrueText = styled(LabelText)`
  543. font-weight: normal;
  544. font-size: ${p => p.theme.fontSizeExtraSmall};
  545. font-family: ${p => p.theme.text.familyMono};
  546. grid-column: auto / span 2;
  547. `;