monitorForm.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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/core';
  24. import {isActiveSuperuser} from 'sentry/utils/isActiveSuperuser';
  25. import slugify from 'sentry/utils/slugify';
  26. import commonTheme from 'sentry/utils/theme';
  27. import usePageFilters from 'sentry/utils/usePageFilters';
  28. import useProjects from 'sentry/utils/useProjects';
  29. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  30. import {getScheduleIntervals} from 'sentry/views/monitors/utils';
  31. import {crontabAsText} from 'sentry/views/monitors/utils/crontabAsText';
  32. import type {IntervalConfig, Monitor, MonitorConfig, MonitorType} from '../types';
  33. import {ScheduleType} from '../types';
  34. import {platformsWithGuides} from './monitorQuickStartGuide';
  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 {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.scheduleType'] = config.schedule_type;
  157. rv['config.checkinMargin'] = config.checkin_margin;
  158. rv['config.maxRuntime'] = config.max_runtime;
  159. rv['config.failureIssueThreshold'] = config.failure_issue_threshold;
  160. rv['config.recoveryThreshold'] = 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 owner = monitor?.owner ? `${monitor.owner.type}:${monitor.owner.id}` : null;
  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. 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. owner: owner,
  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. groupProjects={project =>
  252. platformsWithGuides.includes(project.platform) ? 'suggested' : 'other'
  253. }
  254. groups={[
  255. {key: 'suggested', label: t('Suggested Projects')},
  256. {key: 'other', label: t('Other Projects')},
  257. ]}
  258. projects={filteredProjects}
  259. placeholder={t('Choose Project')}
  260. disabled={!!monitor}
  261. disabledReason={t('Existing monitors cannot be moved between projects')}
  262. valueIsSlug
  263. required
  264. stacked
  265. inline={false}
  266. />
  267. </InputGroup>
  268. <StyledListItem>{t('Set your schedule')}</StyledListItem>
  269. <ListItemSubText>
  270. {tct('You can use [link:the crontab syntax] or our interval schedule.', {
  271. link: <ExternalLink href="https://en.wikipedia.org/wiki/Cron" />,
  272. })}
  273. </ListItemSubText>
  274. <InputGroup>
  275. {monitor !== undefined && (
  276. <StyledAlert type="info">
  277. {t(
  278. 'Any changes you make to the execution schedule will only be applied after the next expected check-in.'
  279. )}
  280. </StyledAlert>
  281. )}
  282. <StyledSelectField
  283. name="config.scheduleType"
  284. aria-label={t('Schedule Type')}
  285. options={SCHEDULE_OPTIONS}
  286. defaultValue={ScheduleType.CRONTAB}
  287. orientInline
  288. required
  289. stacked
  290. inline={false}
  291. />
  292. <Observer>
  293. {() => {
  294. const scheduleType = form.current.getValue('config.scheduleType');
  295. const parsedSchedule =
  296. scheduleType === 'crontab'
  297. ? crontabAsText(
  298. form.current.getValue('config.schedule')?.toString() ?? ''
  299. )
  300. : null;
  301. if (scheduleType === 'crontab') {
  302. return (
  303. <MultiColumnInput columns="1fr 2fr">
  304. <StyledTextField
  305. name="config.schedule"
  306. aria-label={t('Crontab Schedule')}
  307. placeholder="* * * * *"
  308. defaultValue={DEFAULT_CRONTAB}
  309. css={{input: {fontFamily: commonTheme.text.familyMono}}}
  310. required
  311. stacked
  312. inline={false}
  313. />
  314. <StyledSelectField
  315. name="config.timezone"
  316. aria-label={t('Timezone')}
  317. defaultValue="UTC"
  318. options={timezoneOptions}
  319. required
  320. stacked
  321. inline={false}
  322. />
  323. {parsedSchedule && <CronstrueText>"{parsedSchedule}"</CronstrueText>}
  324. </MultiColumnInput>
  325. );
  326. }
  327. if (scheduleType === 'interval') {
  328. return (
  329. <MultiColumnInput columns="auto 1fr 2fr">
  330. <LabelText>{t('Every')}</LabelText>
  331. <StyledNumberField
  332. name="config.schedule.frequency"
  333. aria-label={t('Interval Frequency')}
  334. placeholder="e.g. 1"
  335. defaultValue="1"
  336. min={1}
  337. required
  338. stacked
  339. inline={false}
  340. />
  341. <StyledSelectField
  342. name="config.schedule.interval"
  343. aria-label={t('Interval Type')}
  344. options={getScheduleIntervals(
  345. Number(form.current.getValue('config.schedule.frequency') ?? 1)
  346. )}
  347. defaultValue="day"
  348. required
  349. stacked
  350. inline={false}
  351. />
  352. </MultiColumnInput>
  353. );
  354. }
  355. return null;
  356. }}
  357. </Observer>
  358. </InputGroup>
  359. <StyledListItem>{t('Set margins')}</StyledListItem>
  360. <ListItemSubText>
  361. {t('Configure when we mark your monitor as failed or missed.')}
  362. </ListItemSubText>
  363. <InputGroup>
  364. <Panel>
  365. <PanelBody>
  366. <NumberField
  367. name="config.checkinMargin"
  368. min={CHECKIN_MARGIN_MINIMUM}
  369. placeholder={tn(
  370. 'Defaults to %s minute',
  371. 'Defaults to %s minutes',
  372. DEFAULT_CHECKIN_MARGIN
  373. )}
  374. help={t('Number of minutes before a check-in is considered missed.')}
  375. label={t('Grace Period')}
  376. />
  377. <NumberField
  378. name="config.maxRuntime"
  379. min={TIMEOUT_MINIMUM}
  380. placeholder={tn(
  381. 'Defaults to %s minute',
  382. 'Defaults to %s minutes',
  383. DEFAULT_MAX_RUNTIME
  384. )}
  385. help={t(
  386. 'Number of a minutes before an in-progress check-in is marked timed out.'
  387. )}
  388. label={t('Max Runtime')}
  389. />
  390. </PanelBody>
  391. </Panel>
  392. </InputGroup>
  393. <Fragment>
  394. <StyledListItem>{t('Set thresholds')}</StyledListItem>
  395. <ListItemSubText>
  396. {t('Configure when an issue is created or resolved.')}
  397. </ListItemSubText>
  398. <InputGroup>
  399. <Panel>
  400. <PanelBody>
  401. <NumberField
  402. name="config.failureIssueThreshold"
  403. min={1}
  404. placeholder="1"
  405. help={t(
  406. 'Create a new issue when this many consecutive missed or error check-ins are processed.'
  407. )}
  408. label={t('Failure Tolerance')}
  409. />
  410. <NumberField
  411. name="config.recoveryThreshold"
  412. min={1}
  413. placeholder="1"
  414. help={t(
  415. 'Resolve the issue when this many consecutive healthy check-ins are processed.'
  416. )}
  417. label={t('Recovery Tolerance')}
  418. />
  419. </PanelBody>
  420. </Panel>
  421. </InputGroup>
  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. <StyledListItem>{t('Notifications')}</StyledListItem>
  442. <ListItemSubText>
  443. {t('Configure who to notify upon issue creation and when.')}
  444. </ListItemSubText>
  445. <InputGroup>
  446. <Panel>
  447. <PanelBody>
  448. {monitor?.config.alert_rule_id && (
  449. <AlertLink
  450. priority="muted"
  451. to={normalizeUrl(
  452. `/alerts/rules/${monitor.project.slug}/${monitor.config.alert_rule_id}/`
  453. )}
  454. withoutMarginBottom
  455. >
  456. {t('Customize this monitors notification configuration in Alerts')}
  457. </AlertLink>
  458. )}
  459. <Observer>
  460. {() => {
  461. const projectSlug = form.current.getValue('project')?.toString();
  462. return (
  463. <SentryMemberTeamSelectorField
  464. label={t('Notify')}
  465. help={t('Send notifications to a member or team.')}
  466. name="alertRule.targets"
  467. memberOfProjectSlugs={projectSlug ? [projectSlug] : undefined}
  468. multiple
  469. menuPlacement="auto"
  470. />
  471. );
  472. }}
  473. </Observer>
  474. <Observer>
  475. {() => {
  476. const selectedAssignee = form.current.getValue('alertRule.targets');
  477. // Check for falsey value or empty array value
  478. const disabled = !selectedAssignee || !selectedAssignee.toString();
  479. return (
  480. <SelectField
  481. label={t('Environment')}
  482. help={t('Only receive notifications from a specific environment.')}
  483. name="alertRule.environment"
  484. options={alertRuleEnvs}
  485. disabled={disabled}
  486. menuPlacement="auto"
  487. defaultValue=""
  488. disabledReason={t(
  489. 'Please select which teams or members to notify first.'
  490. )}
  491. />
  492. );
  493. }}
  494. </Observer>
  495. </PanelBody>
  496. </Panel>
  497. </InputGroup>
  498. </StyledList>
  499. </Form>
  500. );
  501. }
  502. export default MonitorForm;
  503. const StyledList = styled(List)`
  504. width: 800px;
  505. `;
  506. const StyledAlert = styled(Alert)`
  507. margin-bottom: 0;
  508. `;
  509. const StyledNumberField = styled(NumberField)`
  510. padding: 0;
  511. `;
  512. const StyledSelectField = styled(SelectField)`
  513. padding: 0;
  514. `;
  515. const StyledTextField = styled(TextField)`
  516. padding: 0;
  517. `;
  518. const StyledSentryProjectSelectorField = styled(SentryProjectSelectorField)`
  519. padding: 0;
  520. `;
  521. const StyledListItem = styled(ListItem)`
  522. font-size: ${p => p.theme.fontSizeExtraLarge};
  523. font-weight: ${p => p.theme.fontWeightBold};
  524. line-height: 1.3;
  525. `;
  526. const LabelText = styled(Text)`
  527. font-weight: ${p => p.theme.fontWeightBold};
  528. color: ${p => p.theme.subText};
  529. `;
  530. const ListItemSubText = styled(Text)`
  531. padding-left: ${space(4)};
  532. color: ${p => p.theme.subText};
  533. `;
  534. const InputGroup = styled('div')`
  535. padding-left: ${space(4)};
  536. margin-top: ${space(1)};
  537. margin-bottom: ${space(4)};
  538. display: flex;
  539. flex-direction: column;
  540. gap: ${space(1)};
  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. `;