monitorForm.tsx 20 KB

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