monitorForm.tsx 20 KB

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