UNPKG

hypershield

Version:

Middleware suite for high-performance and resilient APIs

64 lines 2.87 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AlertService = void 0; const alertSender_1 = require("../infrastructure/alertSender"); const crypto_1 = require("crypto"); const constants_1 = require("../../../core/constants/constants"); class AlertService { constructor(options) { this.throttleMap = new Map(); this.options = Object.assign({ throttleMs: constants_1.ALERTS.THROTTLE.DEFAULT_MS, retryAttempts: constants_1.ALERTS.RETRY.DEFAULT_ATTEMPTS }, options); } alert(severity, message, source, metadata) { return __awaiter(this, void 0, void 0, function* () { const alert = { id: (0, crypto_1.randomUUID)(), severity, message, timestamp: new Date(), source, metadata }; if (this.shouldThrottle(alert)) { return; } const senders = this.options.destinations.map(dest => alertSender_1.AlertSenderFactory.createSender(dest)); yield Promise.all(senders.map(sender => this.sendWithRetry(sender.send.bind(sender), alert))); }); } shouldThrottle(alert) { const key = `${alert.severity}:${alert.source}`; const now = Date.now(); const lastAlert = this.throttleMap.get(key) || 0; if (now - lastAlert < (this.options.throttleMs || 0)) { return true; } this.throttleMap.set(key, now); return false; } sendWithRetry(sendFn_1, alert_1) { return __awaiter(this, arguments, void 0, function* (sendFn, alert, attempt = 1) { try { yield sendFn(alert); } catch (error) { if (attempt < constants_1.ALERTS.RETRY.MAX_ATTEMPTS) { yield new Promise(resolve => setTimeout(resolve, constants_1.ALERTS.RETRY.BASE_DELAY * attempt)); return this.sendWithRetry(sendFn, alert, attempt + 1); } throw error; } }); } } exports.AlertService = AlertService; //# sourceMappingURL=alertService.js.map