UNPKG

dt-common-device

Version:

A secure and robust device management library for IoT applications

267 lines (266 loc) 13.3 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); 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 __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); 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 }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebhookQueueService = void 0; const typedi_1 = require("typedi"); const redis_1 = require("../../db/redis"); let WebhookQueueService = (() => { let _classDecorators = [(0, typedi_1.Service)()]; let _classDescriptor; let _classExtraInitializers = []; let _classThis; var WebhookQueueService = _classThis = class { constructor() { this.webhookQueues = new Map(); // BullMQ Queue instances } generateQueueName(propertyId, pmsType) { return `${propertyId}_${pmsType}_webhook`; } /** * Add a webhook to the appropriate queue based on propertyId and pmsType * Creates queue if it doesn't exist */ async addWebhookToQueue(propertyId, pmsType, webhookData, options) { const queueName = this.generateQueueName(propertyId, pmsType); // Get or create queue using the static method const queue = await WebhookQueueService.getOrCreateQueue(queueName, this.webhookQueues); // Add job to queue immediately with 5 minute TTL const job = await queue.add("webhook-job", { propertyId, pmsType, webhookData, timestamp: new Date().toISOString(), }, { removeOnComplete: { age: 5 * 60 }, // Remove after 5 minutes removeOnFail: { age: 5 * 60 }, // Remove failed jobs after 5 minutes attempts: 1, // Only try once }); return job.id; } /** * Mark a webhook job as completed (processed successfully) * Note: Jobs are now removed immediately when polled, so this method is for logging purposes */ async markWebhookCompleted(propertyId, pmsType, jobId) { // Jobs are removed immediately when polled, so just log completion console.log(`Webhook job ${jobId} marked as completed for ${propertyId}_${pmsType}`); } /** * Mark a webhook job as failed * Note: Jobs are now removed immediately when polled, so this method is for logging purposes */ async markWebhookFailed(propertyId, pmsType, jobId, error) { // Jobs are removed immediately when polled, so just log failure console.error(`Webhook job ${jobId} marked as failed for ${propertyId}_${pmsType}: ${error || "Unknown error"}`); } /** * Poll available webhook from ANY available webhook queue in Redis * This method will discover all queues in Redis and filter only webhook queues */ async pollWebhookFromQueues() { try { // Get all queue names from Redis (not just local Map) const redisClient = (0, redis_1.getRedisClient)(); const queueKeys = await redisClient.keys("bull:*:id"); // Filter only webhook queues (PropertyId_pmsType_webhook pattern) const webhookQueueKeys = queueKeys .map((key) => key.replace("bull:", "").replace(":id", "")) .filter((queueName) => { const parts = queueName.split("_"); return parts.length === 3 && parts[2] === "webhook"; }); // Check each webhook queue for waiting jobs for (const queueName of webhookQueueKeys) { try { // Create queue instance if not exists locally if (!this.webhookQueues.has(queueName)) { const { Queue } = await Promise.resolve().then(() => __importStar(require("bullmq"))); const queue = new Queue(queueName, { connection: (0, redis_1.getRedisClient)(), }); this.webhookQueues.set(queueName, queue); } const queue = this.webhookQueues.get(queueName); // Get waiting jobs and take the first one const waitingJobs = await queue.getWaiting(0, 1); if (waitingJobs.length > 0) { const job = waitingJobs[0]; // Remove the job from the queue to prevent duplicate processing await job.remove(); // Extract propertyId and pmsType from queue name const parts = queueName.split("_"); const propertyId = parts[0]; const pmsType = parts[1]; return { jobId: job.id, data: job.data, propertyId, pmsType, queueName, }; } } catch (error) { console.error(`Error checking queue ${queueName}:`, error); continue; // Try next queue } } return null; // No jobs available in any webhook queue } catch (error) { console.error("Error discovering queues from Redis:", error); return null; } } /** * Get all available webhook queue names from Redis */ async getAllQueueNames() { try { const redisClient = (0, redis_1.getRedisClient)(); const queueKeys = await redisClient.keys("bull:*:id"); // Filter only webhook queues (PropertyId_pmsType_webhook pattern) return queueKeys .map((key) => key.replace("bull:", "").replace(":id", "")) .filter((queueName) => { const parts = queueName.split("_"); return parts.length === 3 && parts[2] === "webhook"; }); } catch (error) { console.error("Error getting queue names from Redis:", error); return []; } } /** * Get total waiting count across all webhook queues */ async getTotalWaitingCount() { try { const redisClient = (0, redis_1.getRedisClient)(); const queueKeys = await redisClient.keys("bull:*:id"); let totalCount = 0; // Filter only webhook queues and count waiting jobs for (const key of queueKeys) { const queueName = key.replace("bull:", "").replace(":id", ""); const parts = queueName.split("_"); // Only count webhook queues if (parts.length === 3 && parts[2] === "webhook") { try { // Create queue instance if not exists locally if (!this.webhookQueues.has(queueName)) { const { Queue } = await Promise.resolve().then(() => __importStar(require("bullmq"))); const queue = new Queue(queueName, { connection: (0, redis_1.getRedisClient)(), }); this.webhookQueues.set(queueName, queue); } const queue = this.webhookQueues.get(queueName); const waitingJobs = await queue.getWaiting(); totalCount += waitingJobs.length; } catch (error) { console.error(`Error getting count for queue ${queueName}:`, error); } } } return totalCount; } catch (error) { console.error("Error getting total waiting count:", error); return 0; } } static async getOrCreateQueue(queueKey, queues) { if (queues.has(queueKey)) { return queues.get(queueKey); } const { Queue } = await Promise.resolve().then(() => __importStar(require("bullmq"))); const queue = new Queue(queueKey, { connection: (0, redis_1.getRedisClient)(), }); queues.set(queueKey, queue); return queue; } }; __setFunctionName(_classThis, "WebhookQueueService"); (() => { 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); WebhookQueueService = _classThis = _classDescriptor.value; if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); __runInitializers(_classThis, _classExtraInitializers); })(); return WebhookQueueService = _classThis; })(); exports.WebhookQueueService = WebhookQueueService;