summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/monitoring/requests/index.js
blob: 8b65eec051ffba97edb6745a2fb84dc031faaa11 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import axios from '~/lib/utils/axios_utils';
import { backOff } from '~/lib/utils/common_utils';
import statusCodes, {
  HTTP_STATUS_NO_CONTENT,
  HTTP_STATUS_UNPROCESSABLE_ENTITY,
} from '~/lib/utils/http_status';
import { PROMETHEUS_TIMEOUT } from '../constants';

const cancellableBackOffRequest = (makeRequestCallback) =>
  backOff((next, stop) => {
    makeRequestCallback()
      .then((resp) => {
        if (resp.status === HTTP_STATUS_NO_CONTENT) {
          next();
        } else {
          stop(resp);
        }
      })
      // If the request is cancelled by axios
      // then consider it as noop so that its not
      // caught by subsequent catches
      .catch((thrown) => (axios.isCancel(thrown) ? undefined : stop(thrown)));
  }, PROMETHEUS_TIMEOUT);

export const getDashboard = (dashboardEndpoint, params) =>
  cancellableBackOffRequest(() => axios.get(dashboardEndpoint, { params })).then(
    (axiosResponse) => axiosResponse.data,
  );

export const getPrometheusQueryData = (prometheusEndpoint, params, opts) =>
  cancellableBackOffRequest(() => axios.get(prometheusEndpoint, { params, ...opts }))
    .then((axiosResponse) => axiosResponse.data)
    .then((prometheusResponse) => prometheusResponse.data)
    .catch((error) => {
      // Prometheus returns errors in specific cases
      // https://prometheus.io/docs/prometheus/latest/querying/api/#format-overview
      const { response = {} } = error;
      if (
        response.status === statusCodes.BAD_REQUEST ||
        response.status === HTTP_STATUS_UNPROCESSABLE_ENTITY ||
        response.status === statusCodes.SERVICE_UNAVAILABLE
      ) {
        const { data } = response;
        if (data?.status === 'error' && data?.error) {
          throw new Error(data.error);
        }
      }
      throw error;
    });