useMonitorStats.tsx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import {useState} from 'react';
  2. import type {TimeWindowConfig} from 'sentry/components/checkInTimeline/types';
  3. import {useApiQuery} from 'sentry/utils/queryClient';
  4. import {useLocation} from 'sentry/utils/useLocation';
  5. import useOrganization from 'sentry/utils/useOrganization';
  6. import type {MonitorBucket} from '../types';
  7. interface Options {
  8. /**
  9. * The list of monitor IDs to fetch stats for
  10. */
  11. monitors: string[];
  12. /**
  13. * The window configuration object
  14. */
  15. timeWindowConfig: TimeWindowConfig;
  16. /**
  17. * Do not query stats when set to false
  18. */
  19. enabled?: boolean;
  20. }
  21. /**
  22. * Fetches Monitor stats
  23. */
  24. export function useMonitorStats({monitors, timeWindowConfig, enabled = true}: Options) {
  25. const {start, end, rollupConfig} = timeWindowConfig;
  26. const [now] = useState(() => new Date().getTime() / 1000);
  27. const until =
  28. Math.floor(end.getTime() / 1000) +
  29. rollupConfig.underscanPeriod -
  30. // XXX(epurkhiser): We are dropping 1 bucket worth of data on the right
  31. // side to account for the fact that this bucket is actually over-scan
  32. // becauase the query on the backend is inclusive.
  33. rollupConfig.interval;
  34. const selectionQuery = {
  35. since: Math.floor(start.getTime() / 1000),
  36. until: Math.min(until, now),
  37. resolution: `${rollupConfig.interval}s`,
  38. };
  39. const organization = useOrganization();
  40. const location = useLocation();
  41. const monitorStatsQueryKey = `/organizations/${organization.slug}/monitors-stats/`;
  42. return useApiQuery<Record<string, MonitorBucket[]>>(
  43. [
  44. monitorStatsQueryKey,
  45. {
  46. query: {
  47. monitor: monitors,
  48. project: location.query.project,
  49. environment: location.query.environment,
  50. ...selectionQuery,
  51. },
  52. },
  53. ],
  54. {
  55. staleTime: 0,
  56. enabled: enabled && rollupConfig.totalBuckets > 0,
  57. }
  58. );
  59. }