dt-common-device
Version:
A secure and robust device management library for IoT applications
202 lines (201 loc) • 9.13 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 });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebhookWorker = void 0;
const bullmq_1 = require("bullmq");
const typedi_1 = require("typedi");
let WebhookWorker = (() => {
let _classDecorators = [(0, typedi_1.Service)()];
let _classDescriptor;
let _classExtraInitializers = [];
let _classThis;
var WebhookWorker = _classThis = class {
constructor(redisConnection) {
this.worker = null;
this.webhookProcessor = null;
this.isRunning = false;
this.processedJobs = 0;
this.failedJobs = 0;
this.redisConnection = redisConnection;
}
async startProcessing(queueName) {
if (this.isRunning) {
return;
}
this.worker = new bullmq_1.Worker(queueName, async (job) => {
try {
const startTime = Date.now();
const result = await this.processWebhookJob(job.data);
const processingTime = Date.now() - startTime;
this.processedJobs++;
this.lastProcessedAt = new Date().toISOString();
return {
...result,
processingTime,
};
}
catch (error) {
this.failedJobs++;
await this.handleError(error, job.data);
throw error;
}
}, {
connection: this.redisConnection,
lockDuration: 300000, // 5 minutes lock duration
stalledInterval: 60000, // 1 minute stall check interval
concurrency: 1, // Process one webhook at a time per queue
});
// Set up event handlers
this.worker.on("completed", (job) => {
console.log(`[Webhook Worker] Job ${job.id} completed successfully for queue ${queueName}`);
});
this.worker.on("failed", (job, err) => {
if (job) {
console.error(`[Webhook Worker] Job ${job.id} failed for queue ${queueName} with error: ${err.message}`);
}
else {
console.error(`[Webhook Worker] Unknown job failed for queue ${queueName} with error: ${err.message}`);
}
});
this.worker.on("error", (err) => {
console.error(`[Webhook Worker] Worker error for queue ${queueName}:`, err);
});
this.worker.on("stalled", (jobId) => {
console.warn(`[Webhook Worker] Job ${jobId} stalled in queue ${queueName}`);
});
this.isRunning = true;
console.log(`[Webhook Worker] Started processing queue: ${queueName}`);
}
async stopProcessing() {
if (!this.isRunning || !this.worker) {
return;
}
await this.worker.close();
this.worker = null;
this.isRunning = false;
console.log("[Webhook Worker] Stopped processing");
}
async processWebhookJob(jobData) {
if (!this.webhookProcessor) {
throw new Error("Webhook processor not set");
}
try {
const startTime = Date.now();
// Process the webhook using the provided processor function
await this.webhookProcessor(jobData.webhookData, jobData.pmsType);
const processingTime = Date.now() - startTime;
return {
success: true,
propertyId: jobData.propertyId,
pmsType: jobData.pmsType,
timestamp: jobData.timestamp,
processingTime,
};
}
catch (error) {
const processingTime = Date.now() - Date.parse(jobData.timestamp);
return {
success: false,
propertyId: jobData.propertyId,
pmsType: jobData.pmsType,
timestamp: jobData.timestamp,
error: error.message,
processingTime,
};
}
}
async handleError(error, jobData) {
console.error(`[Webhook Worker] Error processing webhook for property: ${jobData.propertyId}, PMS: ${jobData.pmsType}:`, error);
// Log additional context
console.error(`[Webhook Worker] Job data:`, {
propertyId: jobData.propertyId,
pmsType: jobData.pmsType,
timestamp: jobData.timestamp,
retryCount: jobData.retryCount,
});
// You can add additional error handling here:
// - Send to error monitoring service
// - Create error tickets
// - Notify administrators
// - Log to external logging service
}
async getWorkerStatus() {
return {
isRunning: this.isRunning,
processedJobs: this.processedJobs,
failedJobs: this.failedJobs,
lastProcessedAt: this.lastProcessedAt,
};
}
setWebhookProcessor(processor) {
this.webhookProcessor = processor;
}
/**
* Get the underlying BullMQ worker instance
*/
getWorker() {
return this.worker;
}
/**
* Check if the worker is currently processing
*/
isWorkerRunning() {
return this.isRunning && this.worker !== null;
}
/**
* Reset worker statistics
*/
resetStats() {
this.processedJobs = 0;
this.failedJobs = 0;
this.lastProcessedAt = undefined;
}
};
__setFunctionName(_classThis, "WebhookWorker");
(() => {
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);
WebhookWorker = _classThis = _classDescriptor.value;
if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
__runInitializers(_classThis, _classExtraInitializers);
})();
return WebhookWorker = _classThis;
})();
exports.WebhookWorker = WebhookWorker;