UNPKG

grafana-cloud-graphite

Version:
63 lines 2.46 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GraphiteHTTP = void 0; const node_fetch_1 = __importDefault(require("node-fetch")); const utils_1 = require("../utils"); class GraphiteHTTP { constructor(options) { this.authToken = `${options.userId}:${options.token}`; this.ingestEndpointURL = options.ingestEndpointURL; this.retryLimit = options.retryLimit ?? 3; this.retryDelay = options.retryDelay ?? 1000; } async sendMetrics(data) { const dataArray = Array.isArray(data) === true ? data : [data]; const metricsToSend = dataArray.map((metric) => ({ ...metric, interval: Math.floor(metric.interval / 1000), time: Math.floor(metric.time / 1000), tags: metric.tags ? Object.entries(metric.tags).map(([key, value]) => `${key}=${value}`) : undefined, })); return await this.HttpSend(JSON.stringify(metricsToSend, (key, value) => { if (value !== undefined) return value; })); } async HttpSend(payload, retry = 0) { let canRetry = true; if (retry > this.retryLimit) { canRetry = false; } try { const response = await (0, node_fetch_1.default)(this.ingestEndpointURL, { method: "POST", headers: { Authorization: `Bearer ${this.authToken}`, "Content-Type": "application/json", }, body: payload, }); if ([401, 403, 404].includes(response.status)) { canRetry = false; throw new Error(`Failed to send metrics, invalid URL ${response.status} - ${response.statusText}`); } if (!response.ok) { throw new Error(`Failed to send metrics: ${response.status} - ${response.statusText}`); } } catch (error) { if (canRetry === false) { throw error; } await (0, utils_1.sleep)(Math.pow(2, retry) * this.retryDelay); return this.HttpSend(payload, retry + 1); } } } exports.GraphiteHTTP = GraphiteHTTP; //# sourceMappingURL=httpHandler.js.map