dt-common-device
Version:
A secure and robust device management library for IoT applications
197 lines (196 loc) • 10.3 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.CopilotQueueService = void 0;
const typedi_1 = require("typedi");
const axios_1 = __importDefault(require("axios"));
const config_1 = require("../../config/config");
const utils_1 = require("../utils");
let CopilotQueueService = (() => {
let _classDecorators = [(0, typedi_1.Service)()];
let _classDescriptor;
let _classExtraInitializers = [];
let _classThis;
var CopilotQueueService = _classThis = class {
constructor() {
this.copilotQueues = new Map(); // BullMQ Queue instances
this.workers = new Map(); // BullMQ Worker instances
}
async processRequest(job) {
const { url, method, headers, body } = job.data;
const propertyId = body?.propertyId;
const startTime = Date.now();
try {
(0, config_1.getConfig)().LOGGER.info(`Processing request for property ${propertyId}: ${method} ${url}`);
// Prepare axios request configuration
const axiosConfig = {
method: method.toLowerCase(),
url,
headers: {
"Content-Type": "application/json",
...headers,
},
timeout: 30000, // 30 second timeout
};
// Add body for POST, PUT, PATCH requests
if (body && ["post", "put", "patch"].includes(method.toLowerCase())) {
axiosConfig.data = body;
}
// Execute the HTTP request (fire and forget - no response processing)
await (0, axios_1.default)(axiosConfig);
const responseTime = Date.now() - startTime;
(0, config_1.getConfig)().LOGGER.info(`Request executed for property ${propertyId}: ${method} ${url} (${responseTime}ms)`);
return {
success: true,
responseTime,
};
}
catch (error) {
const responseTime = Date.now() - startTime;
const errorMessage = error.response?.data?.message || error.message || "Unknown error";
(0, config_1.getConfig)().LOGGER.error(`Request failed for property ${propertyId}: ${errorMessage} (${responseTime}ms)`);
return {
success: false,
error: errorMessage,
statusCode: error.response?.status || 500,
responseTime,
};
}
}
async addQueueRequest(request, options) {
try {
// Validate required fields
if (!request.url ||
!request.method ||
!request.body ||
!request.body.propertyId) {
throw new Error("Missing required fields: url, method, and body with propertyId are required");
}
const propertyId = request.body.propertyId;
const queueName = utils_1.QueueManager.generateQueueName(propertyId);
// Get or create queue and worker using the QueueManager
const queue = await utils_1.QueueManager.getOrCreateQueue(queueName, this.copilotQueues);
// Create worker for this queue if it doesn't exist
await utils_1.QueueManager.getOrCreateWorker(queueName, this.workers, this.copilotQueues, this.processRequest.bind(this));
// Prepare job data
const jobData = {
url: request.url,
method: request.method,
headers: request.headers,
body: request.body,
timestamp: Date.now(),
};
// Add job to queue with TTL (similar to WebhookQueueService)
const job = await queue.add("copilot-request", jobData, {
removeOnComplete: { age: 5 * 60 }, // Remove after 5 minutes
removeOnFail: { age: 10 * 60 }, // Remove failed jobs after 10 minutes
attempts: 1, // No retries - execute only once
delay: options?.delay || 0,
priority: options?.priority || 0,
// Use propertyId as job group to ensure FIFO ordering per property
jobId: utils_1.QueueManager.generateJobId(propertyId),
});
(0, config_1.getConfig)().LOGGER.info(`Request queued for property ${propertyId}: ${request.method} ${request.url} (Job ID: ${job.id})`);
return {
jobId: job.id,
queued: true,
};
}
catch (error) {
(0, config_1.getConfig)().LOGGER.error("Failed to add request to queue:", error.message);
throw error;
}
}
async getJobStatus(jobId) {
try {
// Extract propertyId from jobId (format: propertyId-timestamp-random)
const propertyId = utils_1.QueueManager.extractPropertyIdFromJobId(jobId);
const queueName = utils_1.QueueManager.generateQueueName(propertyId);
// Get or create queue
const queue = await utils_1.QueueManager.getOrCreateQueue(queueName, this.copilotQueues);
const job = await queue.getJob(jobId);
if (!job) {
return { exists: false };
}
const state = await job.getState();
return {
exists: true,
id: job.id,
state,
data: job.data,
progress: job.progress,
returnvalue: job.returnvalue,
failedReason: job.failedReason,
processedOn: job.processedOn,
finishedOn: job.finishedOn,
};
}
catch (error) {
(0, config_1.getConfig)().LOGGER.error(`Failed to get job status for ${jobId}:`, error.message);
throw error;
}
}
async shutdown() {
try {
(0, config_1.getConfig)().LOGGER.info("Shutting down CopilotQueue service...");
// Close all workers and queues using QueueManager
await utils_1.QueueManager.closeAllWorkersAndQueues(this.workers, this.copilotQueues);
(0, config_1.getConfig)().LOGGER.info("CopilotQueue service shutdown complete");
}
catch (error) {
(0, config_1.getConfig)().LOGGER.error("Error during CopilotQueue shutdown:", error.message);
throw error;
}
}
};
__setFunctionName(_classThis, "CopilotQueueService");
(() => {
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);
CopilotQueueService = _classThis = _classDescriptor.value;
if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
__runInitializers(_classThis, _classExtraInitializers);
})();
return CopilotQueueService = _classThis;
})();
exports.CopilotQueueService = CopilotQueueService;