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 AlertLink from 'sentry/components/alertLink';
  6. import {Alert} from 'sentry/components/core/alert';
  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 {makeAlertsPathname} from 'sentry/views/alerts/pathnames';
  33. import {getScheduleIntervals} from 'sentry/views/monitors/utils';
  34. import {crontabAsText} from 'sentry/views/monitors/utils/crontabAsText';
  35. import type {IntervalConfig, Monitor, MonitorConfig} from '../types';
  36. import {ScheduleType} from '../types';
  37. import {platformsWithGuides} from './monitorQuickStartGuide';
  38. const SCHEDULE_OPTIONS: Array<SelectValue<string>> = [
  39. {value: ScheduleType.CRONTAB, label: t('Crontab')},
  40. {value: ScheduleType.INTERVAL, label: t('Interval')},
  41. ];
  42. export const DEFAULT_MONITOR_TYPE = 'cron_job';
  43. export const DEFAULT_CRONTAB = '0 0 * * *';
  44. // Maps the value from the SentryMemberTeamSelectorField -> the expected alert
  45. // rule key and vice-versa.
  46. //
  47. // XXX(epurkhiser): For whatever reason the rules API wants the team and member
  48. // to be capitalized.
  49. const RULE_TARGET_MAP = {team: 'Team', user: 'Member'} as const;
  50. const RULES_SELECTOR_MAP = {Team: 'team', Member: 'user'} as const;
  51. // In minutes
  52. export const DEFAULT_MAX_RUNTIME = 30;
  53. export const DEFAULT_CHECKIN_MARGIN = 1;
  54. const CHECKIN_MARGIN_MINIMUM = 1;
  55. const TIMEOUT_MINIMUM = 1;
  56. type Props = {
  57. apiEndpoint: string;
  58. apiMethod: FormProps['apiMethod'];
  59. onSubmitSuccess: FormProps['onSubmitSuccess'];
  60. monitor?: Monitor;
  61. submitLabel?: string;
  62. };
  63. interface TransformedData extends Partial<Omit<Monitor, 'config' | 'alertRule'>> {
  64. alertRule?: Partial<Monitor['alertRule']>;
  65. config?: Partial<Monitor['config']>;
  66. }
  67. /**
  68. * Transform sub-fields for what the API expects
  69. */
  70. export function transformMonitorFormData(_data: Record<string, any>, model: FormModel) {
  71. const schedType = model.getValue('config.scheduleType');
  72. // Remove interval fields if the monitor schedule is crontab
  73. const filteredFields = model.fields
  74. .toJSON()
  75. .filter(
  76. ([k, _v]) =>
  77. (schedType === ScheduleType.CRONTAB &&
  78. k !== 'config.schedule.interval' &&
  79. k !== 'config.schedule.frequency') ||
  80. schedType === ScheduleType.INTERVAL
  81. );
  82. const result = filteredFields.reduce<TransformedData>((data, [k, v]) => {
  83. data.config ??= {};
  84. data.alertRule ??= {};
  85. if (k === 'alertRule.targets') {
  86. const alertTargets = (v as string[] | undefined)?.map(item => {
  87. // See SentryMemberTeamSelectorField to understand why these are strings
  88. const [type, id] = item.split(':');
  89. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  90. const targetType = RULE_TARGET_MAP[type!];
  91. return {targetType, targetIdentifier: Number(id)};
  92. });
  93. data.alertRule.targets = alertTargets;
  94. return data;
  95. }
  96. if (k === 'alertRule.environment') {
  97. const environment = v === '' ? undefined : (v as string);
  98. data.alertRule.environment = environment;
  99. return data;
  100. }
  101. if (k === 'config.schedule.frequency' || k === 'config.schedule.interval') {
  102. if (!Array.isArray(data.config.schedule)) {
  103. data.config.schedule = [1, 'hour'];
  104. }
  105. }
  106. if (Array.isArray(data.config.schedule) && k === 'config.schedule.frequency') {
  107. data.config.schedule[0] = parseInt(v as string, 10);
  108. return data;
  109. }
  110. if (Array.isArray(data.config.schedule) && k === 'config.schedule.interval') {
  111. data.config.schedule[1] = v as IntervalConfig['schedule'][1];
  112. return data;
  113. }
  114. if (k.startsWith('config.')) {
  115. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  116. data.config[k.substring(7)] = v;
  117. return data;
  118. }
  119. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  120. data[k] = v;
  121. return data;
  122. }, {});
  123. // If targets are not specified, don't send alert rule config to backend
  124. if (!result.alertRule?.targets) {
  125. result.alertRule = undefined;
  126. }
  127. return result;
  128. }
  129. /**
  130. * Transform config field errors from the error response
  131. */
  132. export function mapMonitorFormErrors(responseJson?: any) {
  133. if (responseJson.config === undefined) {
  134. return responseJson;
  135. }
  136. // Bring nested config entries to the top
  137. const {config, ...responseRest} = responseJson;
  138. const configErrors = Object.fromEntries(
  139. Object.entries(config).map(([key, value]) => [`config.${key}`, value])
  140. );
  141. return {...responseRest, ...configErrors};
  142. }
  143. function MonitorForm({
  144. monitor,
  145. submitLabel,
  146. apiEndpoint,
  147. apiMethod,
  148. onSubmitSuccess,
  149. }: Props) {
  150. const organization = useOrganization();
  151. const form = useRef(
  152. new FormModel({
  153. transformData: transformMonitorFormData,
  154. mapFormErrors: mapMonitorFormErrors,
  155. })
  156. );
  157. const {projects} = useProjects();
  158. const {selection} = usePageFilters();
  159. function formDataFromConfig(config: MonitorConfig) {
  160. const rv: Record<string, MonitorConfig[keyof MonitorConfig]> = {};
  161. rv['config.scheduleType'] = config.schedule_type;
  162. rv['config.checkinMargin'] = config.checkin_margin;
  163. rv['config.maxRuntime'] = config.max_runtime;
  164. rv['config.failureIssueThreshold'] = config.failure_issue_threshold;
  165. rv['config.recoveryThreshold'] = config.recovery_threshold;
  166. switch (config.schedule_type) {
  167. case 'interval':
  168. rv['config.schedule.frequency'] = config.schedule[0];
  169. rv['config.schedule.interval'] = config.schedule[1];
  170. break;
  171. case 'crontab':
  172. default:
  173. rv['config.schedule'] = config.schedule;
  174. rv['config.timezone'] = config.timezone;
  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,
  209. project: monitor.project.slug,
  210. 'alertRule.targets': alertRuleTarget,
  211. 'alertRule.environment': monitor.alertRule?.environment,
  212. ...formDataFromConfig(monitor.config),
  213. }
  214. : {
  215. project: selectedProject ? selectedProject.slug : null,
  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 noPadding>
  225. <TextField
  226. name="name"
  227. label={t('Name')}
  228. hideLabel
  229. placeholder={t('My Cron Job')}
  230. required
  231. stacked
  232. inline={false}
  233. />
  234. {monitor && (
  235. <TextField
  236. name="slug"
  237. label={t('Slug')}
  238. hideLabel
  239. help={tct(
  240. '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.',
  241. {strong: <strong />}
  242. )}
  243. placeholder={t('monitor-slug')}
  244. required
  245. stacked
  246. inline={false}
  247. transformInput={slugify}
  248. />
  249. )}
  250. <SentryProjectSelectorField
  251. name="project"
  252. label={t('Project')}
  253. hideLabel
  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 noPadding>
  278. {monitor !== undefined && (
  279. <Alert 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. </Alert>
  284. )}
  285. <SelectField
  286. name="config.scheduleType"
  287. label={t('Schedule Type')}
  288. hideLabel
  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. <TextField
  309. name="config.schedule"
  310. label={t('Crontab Schedule')}
  311. hideLabel
  312. placeholder="* * * * *"
  313. defaultValue={DEFAULT_CRONTAB}
  314. css={css`
  315. input {
  316. font-family: ${commonTheme.text.familyMono};
  317. }
  318. `}
  319. required
  320. stacked
  321. inline={false}
  322. />
  323. <SelectField
  324. name="config.timezone"
  325. label={t('Timezone')}
  326. hideLabel
  327. defaultValue="UTC"
  328. options={timezoneOptions}
  329. required
  330. stacked
  331. inline={false}
  332. />
  333. {parsedSchedule && <CronstrueText>"{parsedSchedule}"</CronstrueText>}
  334. </MultiColumnInput>
  335. );
  336. }
  337. if (scheduleType === 'interval') {
  338. return (
  339. <MultiColumnInput columns="auto 1fr 2fr">
  340. <LabelText>{t('Every')}</LabelText>
  341. <NumberField
  342. name="config.schedule.frequency"
  343. label={t('Interval Frequency')}
  344. hideLabel
  345. placeholder="e.g. 1"
  346. defaultValue="1"
  347. min={1}
  348. required
  349. stacked
  350. inline={false}
  351. />
  352. <SelectField
  353. name="config.schedule.interval"
  354. label={t('Interval Type')}
  355. hideLabel
  356. options={getScheduleIntervals(
  357. Number(form.current.getValue('config.schedule.frequency') ?? 1)
  358. )}
  359. defaultValue="day"
  360. required
  361. stacked
  362. inline={false}
  363. />
  364. </MultiColumnInput>
  365. );
  366. }
  367. return null;
  368. }}
  369. </Observer>
  370. </InputGroup>
  371. <StyledListItem>{t('Set margins')}</StyledListItem>
  372. <ListItemSubText>
  373. {t('Configure when we mark your monitor as failed or missed.')}
  374. </ListItemSubText>
  375. <InputGroup>
  376. <Panel>
  377. <PanelBody>
  378. <NumberField
  379. name="config.checkinMargin"
  380. min={CHECKIN_MARGIN_MINIMUM}
  381. placeholder={tn(
  382. 'Defaults to %s minute',
  383. 'Defaults to %s minutes',
  384. DEFAULT_CHECKIN_MARGIN
  385. )}
  386. help={t('Number of minutes before a check-in is considered missed.')}
  387. label={t('Grace Period')}
  388. />
  389. <NumberField
  390. name="config.maxRuntime"
  391. min={TIMEOUT_MINIMUM}
  392. placeholder={tn(
  393. 'Defaults to %s minute',
  394. 'Defaults to %s minutes',
  395. DEFAULT_MAX_RUNTIME
  396. )}
  397. help={t(
  398. 'Number of minutes before an in-progress check-in is marked timed out.'
  399. )}
  400. label={t('Max Runtime')}
  401. />
  402. </PanelBody>
  403. </Panel>
  404. </InputGroup>
  405. <Fragment>
  406. <StyledListItem>{t('Set thresholds')}</StyledListItem>
  407. <ListItemSubText>
  408. {t('Configure when an issue is created or resolved.')}
  409. </ListItemSubText>
  410. <InputGroup>
  411. <Panel>
  412. <PanelBody>
  413. <NumberField
  414. name="config.failureIssueThreshold"
  415. min={1}
  416. placeholder="1"
  417. help={t(
  418. 'Create a new issue when this many consecutive missed or error check-ins are processed.'
  419. )}
  420. label={t('Failure Tolerance')}
  421. />
  422. <NumberField
  423. name="config.recoveryThreshold"
  424. min={1}
  425. placeholder="1"
  426. help={t(
  427. 'Resolve the issue when this many consecutive healthy check-ins are processed.'
  428. )}
  429. label={t('Recovery Tolerance')}
  430. />
  431. </PanelBody>
  432. </Panel>
  433. </InputGroup>
  434. </Fragment>
  435. <StyledListItem>{t('Set Owner')}</StyledListItem>
  436. <ListItemSubText>
  437. {t(
  438. 'Choose a team or member as the monitor owner. Issues created will be automatically assigned to the owner.'
  439. )}
  440. </ListItemSubText>
  441. <InputGroup>
  442. <Panel>
  443. <PanelBody>
  444. <SentryMemberTeamSelectorField
  445. name="owner"
  446. label={t('Owner')}
  447. help={t('Automatically assign issues to a team or user.')}
  448. menuPlacement="auto"
  449. />
  450. </PanelBody>
  451. </Panel>
  452. </InputGroup>
  453. <StyledListItem>{t('Notifications')}</StyledListItem>
  454. <ListItemSubText>
  455. {t('Configure who to notify upon issue creation and when.')}
  456. </ListItemSubText>
  457. <InputGroup>
  458. {monitor?.config.alert_rule_id && (
  459. <AlertLink
  460. priority="muted"
  461. to={makeAlertsPathname({
  462. path: `/rules/${monitor.project.slug}/${monitor.config.alert_rule_id}/`,
  463. organization,
  464. })}
  465. withoutMarginBottom
  466. >
  467. {t('Customize this monitors notification configuration in Alerts')}
  468. </AlertLink>
  469. )}
  470. <Panel>
  471. <PanelBody>
  472. <Observer>
  473. {() => {
  474. const projectSlug = form.current.getValue('project')?.toString();
  475. return (
  476. <SentryMemberTeamSelectorField
  477. label={t('Notify')}
  478. help={t('Send notifications to a member or team.')}
  479. name="alertRule.targets"
  480. memberOfProjectSlugs={projectSlug ? [projectSlug] : undefined}
  481. multiple
  482. menuPlacement="auto"
  483. />
  484. );
  485. }}
  486. </Observer>
  487. <Observer>
  488. {() => {
  489. const selectedAssignee = form.current.getValue('alertRule.targets');
  490. // Check for falsey value or empty array value
  491. const disabled = !selectedAssignee || !selectedAssignee.toString();
  492. return (
  493. <SelectField
  494. label={t('Environment')}
  495. help={t('Only receive notifications from a specific environment.')}
  496. name="alertRule.environment"
  497. options={alertRuleEnvs}
  498. disabled={disabled}
  499. menuPlacement="auto"
  500. defaultValue=""
  501. disabledReason={t(
  502. 'Please select which teams or members to notify first.'
  503. )}
  504. />
  505. );
  506. }}
  507. </Observer>
  508. </PanelBody>
  509. </Panel>
  510. </InputGroup>
  511. </StyledList>
  512. </Form>
  513. );
  514. }
  515. export default MonitorForm;
  516. const StyledList = styled(List)`
  517. width: 800px;
  518. `;
  519. const StyledListItem = styled(ListItem)`
  520. font-size: ${p => p.theme.fontSizeExtraLarge};
  521. font-weight: ${p => p.theme.fontWeightBold};
  522. line-height: 1.3;
  523. `;
  524. const LabelText = styled(Text)`
  525. font-weight: ${p => p.theme.fontWeightBold};
  526. color: ${p => p.theme.subText};
  527. `;
  528. const ListItemSubText = styled(Text)`
  529. padding-left: ${space(4)};
  530. color: ${p => p.theme.subText};
  531. `;
  532. const InputGroup = styled('div')<{noPadding?: boolean}>`
  533. padding-left: ${space(4)};
  534. margin-top: ${space(1)};
  535. margin-bottom: ${space(4)};
  536. display: flex;
  537. flex-direction: column;
  538. gap: ${space(1)};
  539. ${FieldWrapper} {
  540. ${p => p.noPadding && `padding: 0;`};
  541. }
  542. `;
  543. const MultiColumnInput = styled('div')<{columns?: string}>`
  544. display: grid;
  545. align-items: center;
  546. gap: ${space(1)};
  547. grid-template-columns: ${p => p.columns};
  548. `;
  549. const CronstrueText = styled(LabelText)`
  550. font-weight: ${p => p.theme.fontWeightNormal};
  551. font-size: ${p => p.theme.fontSizeExtraSmall};
  552. font-family: ${p => p.theme.text.familyMono};
  553. grid-column: auto / span 2;
  554. `;