monitorForm.tsx 20 KB

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