dt-common-device
Version:
A secure and robust device management library for IoT applications
161 lines (160 loc) • 7.78 kB
JavaScript
;
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceQueueService = void 0;
const typedi_1 = require("typedi");
const redis_1 = require("../../db/redis");
const config_1 = require("../../config/config");
const axios_1 = __importDefault(require("axios"));
let ServiceQueueService = (() => {
let _classDecorators = [(0, typedi_1.Service)()];
let _classDescriptor;
let _classExtraInitializers = [];
let _classThis;
var ServiceQueueService = _classThis = class {
constructor() {
this.queue = null;
this.worker = null;
this.queueName = "service-queue";
this.requestsPerSecond = 5;
}
/**
* Initialize the queue and worker
*/
initialize() {
const { Queue, Worker } = require("bullmq");
// Initialize queue
this.queue = new Queue(this.queueName, {
connection: (0, redis_1.getRedisClient)(),
defaultJobOptions: {
attempts: 1,
removeOnComplete: true,
removeOnFail: false,
},
});
// Initialize worker with rate limiting (10 requests per second)
this.worker = new Worker(this.queueName, async (job) => {
await this.processRequest(job);
await this.deleteJob(job.id);
}, {
connection: (0, redis_1.getRedisClient)(),
concurrency: 1,
limiter: {
max: this.requestsPerSecond,
duration: 1000, // 5 requests per second
},
});
(0, config_1.getConfig)().LOGGER.info(`ServiceQueueService initialized with rate limit: ${this.requestsPerSecond} requests/second`);
}
/**
* Add a request to the queue
* @param request - The HTTP request to be queued
* @returns Promise that resolves with the job ID
*/
async addRequestToQueue(request) {
if (!this.queue) {
throw new Error("Queue not initialized. Call initialize() first.");
}
// Add timestamp for FIFO ordering (earlier timestamp = higher priority)
const timestamp = Date.now();
const job = await this.queue.add("http-request", request, {
priority: timestamp, // Lower priority number = higher priority, so earlier timestamps get processed first
});
(0, config_1.getConfig)().LOGGER.info(`Request added to queue. Job ID: ${job.id}, URL: ${request.url}, Timestamp: ${timestamp}`);
return job.id;
}
/**
* Process a request from the queue
* @param job - The BullMQ job containing the request data
*/
async processRequest(job) {
const { method, url, body, params, headers, timeout = 60000 } = job.data;
(0, config_1.getConfig)().LOGGER.info(`Processing request. Job ID: ${job.id}, URL: ${url}, Method: ${method}`);
try {
const axiosConfig = {
method: method.toLowerCase(),
url,
headers: headers || {},
timeout,
data: body,
params: params,
};
await (0, axios_1.default)(axiosConfig);
(0, config_1.getConfig)().LOGGER.info(`Request completed. Job ID: ${job.id}, URL: ${url}`);
}
catch (error) {
(0, config_1.getConfig)().LOGGER.error(`Request failed. Job ID: ${job.id}, URL: ${url}, Error: ${error.message}`);
throw error;
}
}
/**
* Delete a job from the queue after processing
* @param jobId - The job ID to delete
*/
async deleteJob(jobId) {
if (!this.queue) {
return;
}
try {
const job = await this.queue.getJob(jobId);
if (job) {
await job.remove();
(0, config_1.getConfig)().LOGGER.info(`Job ${jobId} deleted from queue`);
}
}
catch (error) {
(0, config_1.getConfig)().LOGGER.error(`Failed to delete job ${jobId}: ${error.message}`);
}
}
};
__setFunctionName(_classThis, "ServiceQueueService");
(() => {
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
ServiceQueueService = _classThis = _classDescriptor.value;
if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
__runInitializers(_classThis, _classExtraInitializers);
})();
return ServiceQueueService = _classThis;
})();
exports.ServiceQueueService = ServiceQueueService;