monitorForm.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. import {Fragment, useRef} from 'react';
  2. import {css} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import {Observer} from 'mobx-react';
  5. import Alert from 'sentry/components/alert';
  6. import AlertLink from 'sentry/components/alertLink';
  7. import FieldWrapper from 'sentry/components/forms/fieldGroup/fieldWrapper';
  8. import NumberField from 'sentry/components/forms/fields/numberField';
  9. import SelectField from 'sentry/components/forms/fields/selectField';
  10. import SentryMemberTeamSelectorField from 'sentry/components/forms/fields/sentryMemberTeamSelectorField';
  11. import SentryProjectSelectorField from 'sentry/components/forms/fields/sentryProjectSelectorField';
  12. import TextField from 'sentry/components/forms/fields/textField';
  13. import type {FormProps} from 'sentry/components/forms/form';
  14. import Form from 'sentry/components/forms/form';
  15. import FormModel from 'sentry/components/forms/model';
  16. import ExternalLink from 'sentry/components/links/externalLink';
  17. import List from 'sentry/components/list';
  18. import ListItem from 'sentry/components/list/listItem';
  19. import Panel from 'sentry/components/panels/panel';
  20. import PanelBody from 'sentry/components/panels/panelBody';
  21. import Text from 'sentry/components/text';
  22. import {timezoneOptions} from 'sentry/data/timezones';
  23. import {t, tct, tn} from 'sentry/locale';
  24. import {space} from 'sentry/styles/space';
  25. import type {SelectValue} from 'sentry/types/core';
  26. import {isActiveSuperuser} from 'sentry/utils/isActiveSuperuser';
  27. import slugify from 'sentry/utils/slugify';
  28. import commonTheme from 'sentry/utils/theme';
  29. import useOrganization from 'sentry/utils/useOrganization';
  30. import usePageFilters from 'sentry/utils/usePageFilters';
  31. import useProjects from 'sentry/utils/useProjects';
  32. import {getScheduleIntervals} from 'sentry/views/monitors/utils';
  33. import {crontabAsText} from 'sentry/views/monitors/utils/crontabAsText';
  34. import type {IntervalConfig, Monitor, MonitorConfig} from '../types';
  35. import {ScheduleType} from '../types';
  36. import {platformsWithGuides} from './monitorQuickStartGuide';
  37. const SCHEDULE_OPTIONS: Array<SelectValue<string>> = [
  38. {value: ScheduleType.CRONTAB, label: t('Crontab')},
  39. {value: ScheduleType.INTERVAL, label: t('Interval')},
  40. ];
  41. export const DEFAULT_MONITOR_TYPE = 'cron_job';
  42. export const DEFAULT_CRONTAB = '0 0 * * *';
  43. // Maps the value from the SentryMemberTeamSelectorField -> the expected alert
  44. // rule key and vice-versa.
  45. //
  46. // XXX(epurkhiser): For whatever reason the rules API wants the team and member
  47. // to be capitalized.
  48. const RULE_TARGET_MAP = {team: 'Team', user: 'Member'} as const;
  49. const RULES_SELECTOR_MAP = {Team: 'team', Member: 'user'} as const;
  50. // In minutes
  51. export const DEFAULT_MAX_RUNTIME = 30;
  52. export const DEFAULT_CHECKIN_MARGIN = 1;
  53. const CHECKIN_MARGIN_MINIMUM = 1;
  54. const TIMEOUT_MINIMUM = 1;
  55. type Props = {
  56. apiEndpoint: string;
  57. apiMethod: FormProps['apiMethod'];
  58. onSubmitSuccess: FormProps['onSubmitSuccess'];
  59. monitor?: Monitor;
  60. submitLabel?: string;
  61. };
  62. interface TransformedData extends Partial<Omit<Monitor, 'config' | 'alertRule'>> {
  63. alertRule?: Partial<Monitor['alertRule']>;
  64. config?: Partial<Monitor['config']>;
  65. }
  66. /**
  67. * Transform sub-fields for what the API expects
  68. */
  69. export function transformMonitorFormData(_data: Record<string, any>, model: FormModel) {
  70. const schedType = model.getValue('config.scheduleType');
  71. // Remove interval fields if the monitor schedule is crontab
  72. const filteredFields = model.fields
  73. .toJSON()
  74. .filter(
  75. ([k, _v]) =>
  76. (schedType === ScheduleType.CRONTAB &&
  77. k !== 'config.schedule.interval' &&
  78. k !== 'config.schedule.frequency') ||
  79. schedType === ScheduleType.INTERVAL
  80. );
  81. const result = filteredFields.reduce<TransformedData>((data, [k, v]) => {
  82. data.config ??= {};
  83. data.alertRule ??= {};
  84. if (k === 'alertRule.targets') {
  85. const alertTargets = (v as string[] | undefined)?.map(item => {
  86. // See SentryMemberTeamSelectorField to understand why these are strings
  87. const [type, id] = item.split(':');
  88. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  89. const targetType = RULE_TARGET_MAP[type!];
  90. return {targetType, targetIdentifier: Number(id)};
  91. });
  92. data.alertRule.targets = alertTargets;
  93. return data;
  94. }
  95. if (k === 'alertRule.environment') {
  96. const environment = v === '' ? undefined : (v as string);
  97. data.alertRule.environment = environment;
  98. return data;
  99. }
  100. if (k === 'config.schedule.frequency' || k === 'config.schedule.interval') {
  101. if (!Array.isArray(data.config.schedule)) {
  102. data.config.schedule = [1, 'hour'];
  103. }
  104. }
  105. if (Array.isArray(data.config.schedule) && k === 'config.schedule.frequency') {
  106. data.config.schedule[0] = parseInt(v as string, 10);
  107. return data;
  108. }
  109. if (Array.isArray(data.config.schedule) && k === 'config.schedule.interval') {
  110. data.config.schedule[1] = v as IntervalConfig['schedule'][1];
  111. return data;
  112. }
  113. if (k.startsWith('config.')) {
  114. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  115. data.config[k.substring(7)] = v;
  116. return data;
  117. }
  118. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  119. data[k] = v;
  120. return data;
  121. }, {});
  122. // If targets are not specified, don't send alert rule config to backend
  123. if (!result.alertRule?.targets) {
  124. result.alertRule = undefined;
  125. }
  126. return result;
  127. }
  128. /**
  129. * Transform config field errors from the error response
  130. */
  131. export function mapMonitorFormErrors(responseJson?: any) {
  132. if (responseJson.config === undefined) {
  133. return responseJson;
  134. }
  135. // Bring nested config entries to the top
  136. const {config, ...responseRest} = responseJson;
  137. const configErrors = Object.fromEntries(
  138. Object.entries(config).map(([key, value]) => [`config.${key}`, value])
  139. );
  140. return {...responseRest, ...configErrors};
  141. }
  142. function MonitorForm({
  143. monitor,
  144. submitLabel,
  145. apiEndpoint,
  146. apiMethod,
  147. onSubmitSuccess,
  148. }: Props) {
  149. const organization = useOrganization();
  150. const form = useRef(
  151. new FormModel({
  152. transformData: transformMonitorFormData,
  153. mapFormErrors: mapMonitorFormErrors,
  154. })
  155. );
  156. const {projects} = useProjects();
  157. const {selection} = usePageFilters();
  158. function formDataFromConfig(config: MonitorConfig) {
  159. const rv: Record<string, MonitorConfig[keyof MonitorConfig]> = {};
  160. rv['config.scheduleType'] = config.schedule_type;
  161. rv['config.checkinMargin'] = config.checkin_margin;
  162. rv['config.maxRuntime'] = config.max_runtime;
  163. rv['config.failureIssueThreshold'] = config.failure_issue_threshold;
  164. rv['config.recoveryThreshold'] = config.recovery_threshold;
  165. switch (config.schedule_type) {
  166. case 'interval':
  167. rv['config.schedule.frequency'] = config.schedule[0];
  168. rv['config.schedule.interval'] = config.schedule[1];
  169. break;
  170. case 'crontab':
  171. default:
  172. rv['config.schedule'] = config.schedule;
  173. rv['config.timezone'] = config.timezone;
  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,
  208. project: monitor.project.slug,
  209. 'alertRule.targets': alertRuleTarget,
  210. 'alertRule.environment': monitor.alertRule?.environment,
  211. ...formDataFromConfig(monitor.config),
  212. }
  213. : {
  214. project: selectedProject ? selectedProject.slug : null,
  215. }
  216. }
  217. onSubmitSuccess={onSubmitSuccess}
  218. submitLabel={submitLabel}
  219. >
  220. <StyledList symbol="colored-numeric">
  221. <StyledListItem>{t('Add a name and project')}</StyledListItem>
  222. <ListItemSubText>{t('The name will show up in notifications.')}</ListItemSubText>
  223. <InputGroup noPadding>
  224. <TextField
  225. name="name"
  226. label={t('Name')}
  227. hideLabel
  228. placeholder={t('My Cron Job')}
  229. required
  230. stacked
  231. inline={false}
  232. />
  233. {monitor && (
  234. <TextField
  235. name="slug"
  236. label={t('Slug')}
  237. hideLabel
  238. help={tct(
  239. '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.',
  240. {strong: <strong />}
  241. )}
  242. placeholder={t('monitor-slug')}
  243. required
  244. stacked
  245. inline={false}
  246. transformInput={slugify}
  247. />
  248. )}
  249. <SentryProjectSelectorField
  250. name="project"
  251. label={t('Project')}
  252. hideLabel
  253. groupProjects={project =>
  254. platformsWithGuides.includes(project.platform) ? 'suggested' : 'other'
  255. }
  256. groups={[
  257. {key: 'suggested', label: t('Suggested Projects')},
  258. {key: 'other', label: t('Other Projects')},
  259. ]}
  260. projects={filteredProjects}
  261. placeholder={t('Choose Project')}
  262. disabled={!!monitor}
  263. disabledReason={t('Existing monitors cannot be moved between projects')}
  264. valueIsSlug
  265. required
  266. stacked
  267. inline={false}
  268. />
  269. </InputGroup>
  270. <StyledListItem>{t('Set your schedule')}</StyledListItem>
  271. <ListItemSubText>
  272. {tct('You can use [link:the crontab syntax] or our interval schedule.', {
  273. link: <ExternalLink href="https://en.wikipedia.org/wiki/Cron" />,
  274. })}
  275. </ListItemSubText>
  276. <InputGroup noPadding>
  277. {monitor !== undefined && (
  278. <StyledAlert type="info">
  279. {t(
  280. 'Any changes you make to the execution schedule will only be applied after the next expected check-in.'
  281. )}
  282. </StyledAlert>
  283. )}
  284. <SelectField
  285. name="config.scheduleType"
  286. label={t('Schedule Type')}
  287. hideLabel
  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. <TextField
  308. name="config.schedule"
  309. label={t('Crontab Schedule')}
  310. hideLabel
  311. placeholder="* * * * *"
  312. defaultValue={DEFAULT_CRONTAB}
  313. css={css`
  314. input {
  315. font-family: ${commonTheme.text.familyMono};
  316. }
  317. `}
  318. required
  319. stacked
  320. inline={false}
  321. />
  322. <SelectField
  323. name="config.timezone"
  324. label={t('Timezone')}
  325. hideLabel
  326. defaultValue="UTC"
  327. options={timezoneOptions}
  328. required
  329. stacked
  330. inline={false}
  331. />
  332. {parsedSchedule && <CronstrueText>"{parsedSchedule}"</CronstrueText>}
  333. </MultiColumnInput>
  334. );
  335. }
  336. if (scheduleType === 'interval') {
  337. return (
  338. <MultiColumnInput columns="auto 1fr 2fr">
  339. <LabelText>{t('Every')}</LabelText>
  340. <NumberField
  341. name="config.schedule.frequency"
  342. label={t('Interval Frequency')}
  343. hideLabel
  344. placeholder="e.g. 1"
  345. defaultValue="1"
  346. min={1}
  347. required
  348. stacked
  349. inline={false}
  350. />
  351. <SelectField
  352. name="config.schedule.interval"
  353. label={t('Interval Type')}
  354. hideLabel
  355. options={getScheduleIntervals(
  356. Number(form.current.getValue('config.schedule.frequency') ?? 1)
  357. )}
  358. defaultValue="day"
  359. required
  360. stacked
  361. inline={false}
  362. />
  363. </MultiColumnInput>
  364. );
  365. }
  366. return null;
  367. }}
  368. </Observer>
  369. </InputGroup>
  370. <StyledListItem>{t('Set margins')}</StyledListItem>
  371. <ListItemSubText>
  372. {t('Configure when we mark your monitor as failed or missed.')}
  373. </ListItemSubText>
  374. <InputGroup>
  375. <Panel>
  376. <PanelBody>
  377. <NumberField
  378. name="config.checkinMargin"
  379. min={CHECKIN_MARGIN_MINIMUM}
  380. placeholder={tn(
  381. 'Defaults to %s minute',
  382. 'Defaults to %s minutes',
  383. DEFAULT_CHECKIN_MARGIN
  384. )}
  385. help={t('Number of minutes before a check-in is considered missed.')}
  386. label={t('Grace Period')}
  387. />
  388. <NumberField
  389. name="config.maxRuntime"
  390. min={TIMEOUT_MINIMUM}
  391. placeholder={tn(
  392. 'Defaults to %s minute',
  393. 'Defaults to %s minutes',
  394. DEFAULT_MAX_RUNTIME
  395. )}
  396. help={t(
  397. 'Number of minutes before an in-progress check-in is marked timed out.'
  398. )}
  399. label={t('Max Runtime')}
  400. />
  401. </PanelBody>
  402. </Panel>
  403. </InputGroup>
  404. <Fragment>
  405. <StyledListItem>{t('Set thresholds')}</StyledListItem>
  406. <ListItemSubText>
  407. {t('Configure when an issue is created or resolved.')}
  408. </ListItemSubText>
  409. <InputGroup>
  410. <Panel>
  411. <PanelBody>
  412. <NumberField
  413. name="config.failureIssueThreshold"
  414. min={1}
  415. placeholder="1"
  416. help={t(
  417. 'Create a new issue when this many consecutive missed or error check-ins are processed.'
  418. )}
  419. label={t('Failure Tolerance')}
  420. />
  421. <NumberField
  422. name="config.recoveryThreshold"
  423. min={1}
  424. placeholder="1"
  425. help={t(
  426. 'Resolve the issue when this many consecutive healthy check-ins are processed.'
  427. )}
  428. label={t('Recovery Tolerance')}
  429. />
  430. </PanelBody>
  431. </Panel>
  432. </InputGroup>
  433. </Fragment>
  434. <StyledListItem>{t('Set Owner')}</StyledListItem>
  435. <ListItemSubText>
  436. {t(
  437. 'Choose a team or member as the monitor owner. Issues created will be automatically assigned to the owner.'
  438. )}
  439. </ListItemSubText>
  440. <InputGroup>
  441. <Panel>
  442. <PanelBody>
  443. <SentryMemberTeamSelectorField
  444. name="owner"
  445. label={t('Owner')}
  446. help={t('Automatically assign issues to a team or user.')}
  447. menuPlacement="auto"
  448. />
  449. </PanelBody>
  450. </Panel>
  451. </InputGroup>
  452. <StyledListItem>{t('Notifications')}</StyledListItem>
  453. <ListItemSubText>
  454. {t('Configure who to notify upon issue creation and when.')}
  455. </ListItemSubText>
  456. <InputGroup>
  457. {monitor?.config.alert_rule_id && (
  458. <AlertLink
  459. priority="muted"
  460. to={`/organizations/${organization.slug}/alerts/rules/${monitor.project.slug}/${monitor.config.alert_rule_id}/`}
  461. withoutMarginBottom
  462. >
  463. {t('Customize this monitors notification configuration in Alerts')}
  464. </AlertLink>
  465. )}
  466. <Panel>
  467. <PanelBody>
  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. `;