UNPKG

dt-common-device

Version:

A secure and robust device management library for IoT applications

354 lines (353 loc) 14.1 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 __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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.initialize = initialize; exports.getConfig = getConfig; exports.getDeviceServiceUrl = getDeviceServiceUrl; exports.getAdminServiceUrl = getAdminServiceUrl; exports.getMonitoringServiceUrl = getMonitoringServiceUrl; exports.getSqsQueueUrl = getSqsQueueUrl; exports.getReservationSqsQueueUrl = getReservationSqsQueueUrl; exports.getHeartbeatSqsQueueUrl = getHeartbeatSqsQueueUrl; exports.getIssueSqsQueueUrl = getIssueSqsQueueUrl; exports.getEventSubscription = getEventSubscription; exports.checkRequiredEnv = checkRequiredEnv; exports.ensureAuditInitialized = ensureAuditInitialized; exports.getLogger = getLogger; exports.getAdminPostgresDbUri = getAdminPostgresDbUri; exports.getAccessPostgresDbUri = getAccessPostgresDbUri; exports.getPmsPostgresDbUri = getPmsPostgresDbUri; exports.getMongoUri = getMongoUri; exports.getDTApiKey = getDTApiKey; exports.getRedisDbHostAndPort = getRedisDbHostAndPort; exports.shutdown = shutdown; const dt_audit_library_1 = require("dt-audit-library"); const db_1 = require("../db/db"); const dotenv_1 = __importDefault(require("dotenv")); const events_1 = require("../events"); const constants_1 = require("./constants"); dotenv_1.default.config(); let config = null; let auditInitialized = false; let eventSubscription = null; let db_keys = null; let sourceKey = null; async function initialize(cfg) { // Check if required env variables are set checkRequiredEnv(constants_1.REQUIRED.env); // Initialize config config = { ...cfg }; if (cfg.SOURCE === "ADMIN_SERVICE") { sourceKey = "ADMIN"; db_keys = constants_1.CONFIG_KEYS.ADMIN.db_keys; await validateServiceConfig(cfg); } if (cfg.SOURCE === "ACCESS_SERVICE") { sourceKey = "ACCESS"; db_keys = constants_1.CONFIG_KEYS.ACCESS.db_keys; await validateServiceConfig(cfg); } if (cfg.SOURCE === "SCHEDULE_SERVICE") { sourceKey = "SCHEDULE"; db_keys = constants_1.CONFIG_KEYS.SCHEDULE.db_keys; await validateServiceConfig(cfg); } if (cfg.SOURCE === "ENERGY_SERVICE") { sourceKey = "ENERGY"; db_keys = constants_1.CONFIG_KEYS.ENERGY.db_keys; await validateServiceConfig(cfg); } if (cfg.SOURCE === "REMOTE_SERVICE") { sourceKey = "REMOTE"; db_keys = constants_1.CONFIG_KEYS.REMOTE.db_keys; await validateServiceConfig(cfg); } if (cfg.SOURCE === "MIGRATION") { sourceKey = "MIGRATION"; db_keys = constants_1.CONFIG_KEYS.MIGRATION.db_keys; await validateServiceConfig(cfg); } if (cfg.SOURCE === "OPERATION_NODE_SERVICE") { sourceKey = "OPERATION_NODE"; db_keys = constants_1.CONFIG_KEYS.OPERATION_NODE.db_keys; await validateServiceConfig(cfg); } if (cfg.SOURCE === "NOTIFICATION_SERVICE") { sourceKey = "NOTIFICATION"; db_keys = constants_1.CONFIG_KEYS.NOTIFICATION.db_keys; await validateServiceConfig(cfg); } // Connect to databases try { await (0, db_1.connectDatabase)(); cfg.LOGGER.info("Database connections established successfully"); } catch (error) { cfg.LOGGER.error("Failed to connect to databases", { error }); throw error; } // Subscribe to events if event subscription is available if (eventSubscription) { try { await eventSubscription.subscribe(); cfg.LOGGER.info("Event subscription started successfully"); } catch (error) { cfg.LOGGER.error(`Failed to start event subscription: ${error.message || error.toString()}`); // Don't throw here as the main setup should continue } } // Initialize audit ensureAuditInitialized(); cfg.LOGGER.info("dt-common-device: Initialization completed successfully"); } async function validateInternalEventHandler(cfg) { // Initialize internal event subscription if handler is provided if (cfg.INTERNAL_EVENT_HANDLER) { try { eventSubscription = new events_1.InternalEventSubscription(cfg.INTERNAL_EVENT_HANDLER); cfg.LOGGER.info("InternalEventSubscription initialized successfully"); } catch (error) { cfg.LOGGER.error("Failed to initialize InternalEventSubscription", { error, }); throw error; } } else { throw new Error("dt-common-device: No internal event handler provided. Please provide an internal event handler in the config."); } } async function validateServiceConfig(cfg) { checkRequiredEnv(constants_1.CONFIG_KEYS[sourceKey].env); if (constants_1.CONFIG_KEYS[sourceKey].INTERNAL_EVENT_HANDLER) { await validateInternalEventHandler(cfg); } } function getConfig() { if (!config) { throw new Error("dt-common-device: Library not initialized. Call initialize() first."); } return config; } function getDeviceServiceUrl() { const deviceServiceUrl = process.env.DEVICE_SERVICE; if (!deviceServiceUrl) { getConfig().LOGGER.error("DEVICE_SERVICE must be set in environment variables"); throw new Error("dt-common-device: DEVICE_SERVICE must be set in environment variables"); } return deviceServiceUrl; } function getAdminServiceUrl() { if (constants_1.CONFIG_KEYS[sourceKey].env.includes("ADMIN_SERVICE")) { const adminServiceUrl = process.env.ADMIN_SERVICE; if (!adminServiceUrl) { getConfig().LOGGER.error("ADMIN_SERVICE must be set in environment variables"); throw new Error("dt-common-device: ADMIN_SERVICE must be set in environment variables"); } return adminServiceUrl; } throw new Error("dt-common-device: ADMIN_SERVICE is not configured for this service"); } function getMonitoringServiceUrl() { const monitoringServiceUrl = process.env.MONITORING_SERVICE_PYTHON; if (!monitoringServiceUrl) { getConfig().LOGGER.error("MONITORING_SERVICE_PYTHON must be set in environment variables"); throw new Error("dt-common-device: MONITORING_SERVICE_PYTHON must be set in environment variables"); } return monitoringServiceUrl; } function getSqsQueueUrl() { if (constants_1.CONFIG_KEYS[sourceKey].env.includes("AWS_SQS_URL")) { const sqsQueueUrl = process.env.AWS_SQS_URL; if (!sqsQueueUrl) { getConfig().LOGGER.error("AWS_SQS_URL must be set in environment variables"); throw new Error("dt-common-device: AWS_SQS_URL must be set in environment variables"); } return sqsQueueUrl; } throw new Error("dt-common-device: AWS_SQS_URL is not configured for this service"); } function getReservationSqsQueueUrl() { if (constants_1.CONFIG_KEYS[sourceKey].env.includes("RESERVATION_SQS_URL")) { const reservationSqsQueueUrl = process.env.RESERVATION_SQS_URL; if (!reservationSqsQueueUrl) { getConfig().LOGGER.error("RESERVATION_SQS_URL must be set in environment variables"); throw new Error("dt-common-device: RESERVATION_SQS_URL must be set in environment variables"); } return reservationSqsQueueUrl; } return ""; } function getHeartbeatSqsQueueUrl() { if (constants_1.CONFIG_KEYS[sourceKey].env.includes("HEARTBEAT_SQS_URL")) { const heartbeatSqsQueueUrl = process.env.HEARTBEAT_SQS_URL; if (!heartbeatSqsQueueUrl) { getConfig().LOGGER.error("HEARTBEAT_SQS_URL must be set in environment variables"); throw new Error("dt-common-device: HEARTBEAT_SQS_URL must be set in environment variables"); } return heartbeatSqsQueueUrl; } return ""; } function getIssueSqsQueueUrl() { if (constants_1.CONFIG_KEYS[sourceKey].env.includes("ISSUE_SQS_URL")) { const issueSqsQueueUrl = process.env.ISSUE_SQS_URL; if (!issueSqsQueueUrl) { getConfig().LOGGER.error("ISSUE_SQS_URL must be set in environment variables"); throw new Error("dt-common-device: ISSUE_SQS_URL must be set in environment variables"); } return issueSqsQueueUrl; } return ""; } function getEventSubscription() { return eventSubscription; } function checkRequiredEnv(requiredEnvs) { const missing = requiredEnvs.filter((key) => !process.env[key]); if (missing.length > 0) { throw new Error(`Missing required environment variables: ${missing.join(", ")}`); } } function ensureAuditInitialized() { if (auditInitialized) return; // const apiKey = process.env.POSTHOG_API_KEY; // const host = process.env.POSTHOG_HOST; const host = process.env.CLICKHOUSE_HOST; const database = process.env.CLICKHOUSE_DATABASE; const username = process.env.CLICKHOUSE_USERNAME; const password = process.env.CLICKHOUSE_PASSWORD; if (!host || !database || !username || !password) { getConfig().LOGGER.error("CLICKHOUSE_HOST, CLICKHOUSE_DATABASE, CLICKHOUSE_USERNAME, CLICKHOUSE_PASSWORD must be set in environment variables"); throw new Error("dt-common-device: CLICKHOUSE_HOST, CLICKHOUSE_DATABASE, CLICKHOUSE_USERNAME, CLICKHOUSE_PASSWORD must be set in environment variables"); } (0, dt_audit_library_1.initializeAudit)({ host, database, username, password, }); auditInitialized = true; } // Direct logger export for easier usage function getLogger() { return getConfig().LOGGER; } /** * Returns the PostgreSQL DB URI from environment variables. * Throws an error if not set. */ function getAdminPostgresDbUri() { const fullUri = process.env[db_keys?.admin]; if (!fullUri) { getConfig().LOGGER.error("ADMIN_DB_URI must be set in environment variables or .env file"); throw new Error("dt-common-device: ADMIN_DB_URI must be set in environment variables or .env file"); } return fullUri; } function getAccessPostgresDbUri() { const fullUri = process.env[db_keys?.access]; if (!fullUri) { getConfig().LOGGER.error("ACCESS_DB_URI must be set in environment variables or .env file"); throw new Error("dt-common-device: ACCESS_DB_URI must be set in environment variables or .env file"); } return fullUri; } function getPmsPostgresDbUri() { const fullUri = process.env[db_keys?.pms]; if (!fullUri) { getConfig().LOGGER.error("PMS_DB_URI must be set in environment variables or .env file"); throw new Error("dt-common-device: PMS_DB_URI must be set in environment variables or .env file"); } return fullUri; } function getMongoUri() { const fullUri = process.env.MONGODB_URI; if (!fullUri) { getConfig().LOGGER.error("MONGODB_URI must be set in environment variables or .env file"); throw new Error("dt-common-device: MONGODB_URI must be set in environment variables or .env file"); } return fullUri; } function getDTApiKey() { const apiKey = process.env.DT_API_KEY; if (!apiKey) { getConfig().LOGGER.error("DT_API_KEY must be set in environment variables"); throw new Error("dt-common-device: DT_API_KEY must be set in environment variables"); } return apiKey; } /** * Returns the Redis DB Host and port from environment variables. * Throws an error if not set. */ function getRedisDbHostAndPort() { const host = process.env.REDIS_HOST; const port = process.env.REDIS_PORT; if (!host || !port) { getConfig().LOGGER.error("REDIS_HOST and REDIS_PORT must be set in environment variables"); throw new Error("dt-common-device: REDIS_HOST and REDIS_PORT must be set in environment variables"); } return { host, port: Number(port) }; } /** * Graceful shutdown function */ async function shutdown() { if (eventSubscription) { try { await eventSubscription.unsubscribe(); getConfig().LOGGER.info("Event subscription stopped successfully"); } catch (error) { getConfig().LOGGER.error("Failed to stop event subscription", { error }); } } // Close notification queue connections try { const { closeNotificationQueue } = await Promise.resolve().then(() => __importStar(require("../notificationQueue/queue.service"))); await closeNotificationQueue(); } catch (error) { getConfig().LOGGER.error("Failed to close notification queue", { error }); } getConfig().LOGGER.info("dt-common-device: Shutdown completed"); }