All files / app/assets/javascripts/custom_metrics/components custom_metrics_form_fields.vue

95.74% Statements 45/47
89.66% Branches 26/29
100% Functions 18/18
95.65% Lines 44/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301  9x                 9x 9x 9x 9x 9x 9x   9x 9x       9x 9x   7x 7x               2x                                         49x                                         19x   19x                 24x                 19x     19x         1x       19x 6x       9x 9x                         19x 19x 19x   10x 10x 1x 1x   9x   9x 8x         9x 9x   7x 7x 7x 7x           2x               4x                       115x                                                                                                                                                                                                                                                        
<script>
import {
  GlFormInput,
  GlLink,
  GlFormGroup,
  GlFormRadioGroup,
  GlLoadingIcon,
  GlIcon,
} from '@gitlab/ui';
import { debounce } from 'lodash';
import axios from '~/lib/utils/axios_utils';
import { backOff } from '~/lib/utils/common_utils';
import csrf from '~/lib/utils/csrf';
import statusCodes from '~/lib/utils/http_status';
import { __, s__ } from '~/locale';
import { queryTypes, formDataValidator } from '../constants';
 
const VALIDATION_REQUEST_TIMEOUT = 10000;
const axiosCancelToken = axios.CancelToken;
let cancelTokenSource;
 
function backOffRequest(makeRequestCallback) {
  return backOff((next, stop) => {
    makeRequestCallback()
      .then((resp) => {
E        if (resp.status === statusCodes.OK) {
          stop(resp);
        } else {
          next();
        }
      })
      // 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)));
  }, VALIDATION_REQUEST_TIMEOUT);
}
 
export default {
  components: {
    GlFormInput,
    GlLink,
    GlFormGroup,
    GlFormRadioGroup,
    GlLoadingIcon,
    GlIcon,
  },
  props: {
    formOperation: {
      type: String,
      required: true,
    },
    formData: {
      type: Object,
      required: false,
      default: () => ({
        title: '',
        yLabel: '',
        query: '',
        unit: '',
        group: '',
        legend: '',
      }),
      validator: formDataValidator,
    },
    metricPersisted: {
      type: Boolean,
      required: false,
      default: false,
    },
    validateQueryPath: {
      type: String,
      required: true,
    },
  },
  data() {
    const group = this.formData.group.length ? this.formData.group : queryTypes.business;
 
    return {
      queryIsValid: null,
      queryValidateInFlight: false,
      ...this.formData,
      group,
    };
  },
  computed: {
    formIsValid() {
      return Boolean(
        this.queryIsValid &&
          this.title.length &&
          this.yLabel.length &&
          this.unit.length &&
          this.group.length,
      );
    },
    validQueryMsg() {
      return this.queryIsValid ? s__('Metrics|PromQL query is valid') : '';
    },
    invalidQueryMsg() {
      return !this.queryIsValid ? this.errorMessage : '';
    },
  },
  watch: {
    formIsValid(value) {
      this.$emit('formValidation', value);
    },
  },
  beforeMount() {
    if (this.metricPersisted) {
      this.validateQuery();
    }
  },
  methods: {
    requestValidation(query, cancelToken) {
      return backOffRequest(() =>
        axios.post(
          this.validateQueryPath,
          {
            query,
          },
          {
            cancelToken,
          },
        ),
      );
    },
    setFormState(isValid, inFlight, message) {
      this.queryIsValid = isValid;
      this.queryValidateInFlight = inFlight;
      this.errorMessage = message;
    },
    validateQuery() {
      if (!this.query) {
        this.setFormState(null, false, '');
        return;
      }
      this.setFormState(null, true, '');
      // cancel previously dispatched backoff request
      if (cancelTokenSource) {
        cancelTokenSource.cancel();
      }
      // Creating a new token for each request because
      // if a single token is used it can cancel existing requests
      // as well.
      cancelTokenSource = axiosCancelToken.source();
      this.requestValidation(this.query, cancelTokenSource.token)
        .then((res) => {
          const response = res.data;
          const { valid, error } = response.query;
E          if (response.success) {
            this.setFormState(valid, false, valid ? '' : error);
          } else {
            throw new Error(__('There was an error trying to validate your query'));
          }
        })
        .catch(() => {
          this.setFormState(
            false,
            false,
            s__('Metrics|There was an error trying to validate your query'),
          );
        });
    },
    debouncedValidateQuery: debounce(function checkQuery() {
      this.validateQuery();
    }, 500),
  },
  csrfToken: csrf.token || '',
  formGroupOptions: [
    { text: __('Business'), value: queryTypes.business },
    { text: __('Response'), value: queryTypes.response },
    { text: __('System'), value: queryTypes.system },
  ],
};
</script>
 
<template>
  <div>
    <input ref="method" type="hidden" name="_method" :value="formOperation" />
    <input :value="$options.csrfToken" type="hidden" name="authenticity_token" />
    <gl-form-group :label="__('Name')" label-for="prometheus_metric_title" label-class="label-bold">
      <gl-form-input
        id="prometheus_metric_title"
        v-model="title"
        name="prometheus_metric[title]"
        class="form-control"
        :placeholder="s__('Metrics|e.g. Throughput')"
        data-qa-selector="custom_metric_prometheus_title_field"
        required
      />
      <span class="form-text text-muted">{{ s__('Metrics|Used as a title for the chart') }}</span>
    </gl-form-group>
    <gl-form-group :label="__('Type')" label-for="prometheus_metric_group" label-class="label-bold">
      <gl-form-radio-group
        id="metric-group"
        v-model="group"
        :options="$options.formGroupOptions"
        :checked="group"
        name="prometheus_metric[group]"
      />
      <span class="form-text text-muted">{{ s__('Metrics|For grouping similar metrics') }}</span>
    </gl-form-group>
    <gl-form-group
      :label="__('Query')"
      label-for="prometheus_metric_query"
      label-class="label-bold"
      :state="queryIsValid"
    >
      <gl-form-input
        id="prometheus_metric_query"
        v-model.trim="query"
        data-qa-selector="custom_metric_prometheus_query_field"
        name="prometheus_metric[query]"
        class="form-control"
        :placeholder="s__('Metrics|e.g. rate(http_requests_total[5m])')"
        required
        :state="queryIsValid"
        @input="debouncedValidateQuery"
      />
      <span v-if="queryValidateInFlight" class="form-text text-muted">
        <gl-loading-icon size="sm" :inline="true" class="mr-1 align-middle" />
        {{ s__('Metrics|Validating query') }}
      </span>
      <slot v-if="!queryValidateInFlight" name="valid-feedback">
        <span class="form-text cgreen">
          {{ validQueryMsg }}
        </span>
      </slot>
      <slot v-if="!queryValidateInFlight" name="invalid-feedback">
        <span class="form-text cred">
          {{ invalidQueryMsg }}
        </span>
      </slot>
      <span v-show="query.length === 0" class="form-text text-muted">
        {{ s__('Metrics|Must be a valid PromQL query.') }}
        <gl-link href="https://prometheus.io/docs/prometheus/latest/querying/basics/" tabindex="-1">
          {{ s__('Metrics|Prometheus Query Documentation') }}
          <gl-icon name="external-link" :size="12" />
        </gl-link>
      </span>
    </gl-form-group>
    <gl-form-group
      :label="s__('Metrics|Y-axis label')"
      label-for="prometheus_metric_y_label"
      label-class="label-bold"
    >
      <gl-form-input
        id="prometheus_metric_y_label"
        v-model="yLabel"
        data-qa-selector="custom_metric_prometheus_y_label_field"
        name="prometheus_metric[y_label]"
        class="form-control"
        :placeholder="s__('Metrics|e.g. Requests/second')"
        required
      />
      <span class="form-text text-muted">
        {{
          s__('Metrics|Label of the y-axis (usually the unit). The x-axis always represents time.')
        }}
      </span>
    </gl-form-group>
    <gl-form-group
      :label="s__('Metrics|Unit label')"
      label-for="prometheus_metric_unit"
      label-class="label-bold"
    >
      <gl-form-input
        id="prometheus_metric_unit"
        v-model="unit"
        data-qa-selector="custom_metric_prometheus_unit_label_field"
        name="prometheus_metric[unit]"
        class="form-control"
        :placeholder="s__('Metrics|e.g. req/sec')"
        required
      />
    </gl-form-group>
    <gl-form-group
      :label="s__('Metrics|Legend label (optional)')"
      label-for="prometheus_metric_legend"
      label-class="label-bold"
    >
      <gl-form-input
        id="prometheus_metric_legend"
        v-model="legend"
        data-qa-selector="custom_metric_prometheus_legend_label_field"
        name="prometheus_metric[legend]"
        class="form-control"
        :placeholder="s__('Metrics|e.g. HTTP requests')"
        required
      />
      <span class="form-text text-muted">
        {{
          s__(
            'Metrics|Used if the query returns a single series. If it returns multiple series, their legend labels will be picked up from the response.',
          )
        }}
      </span>
    </gl-form-group>
  </div>
</template>