monitorForm.tsx 20 KB

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