@uns-kit/core 3.0.33 → 3.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/MIGRATIONS.md +50 -0
  2. package/dist/config/app-config.d.ts +1 -1
  3. package/dist/config/app-config.d.ts.map +1 -1
  4. package/dist/config/app-config.js.map +1 -1
  5. package/dist/runtime/mqtt-handover-state.d.ts +48 -0
  6. package/dist/runtime/mqtt-handover-state.d.ts.map +1 -0
  7. package/dist/runtime/mqtt-handover-state.js +61 -0
  8. package/dist/runtime/mqtt-handover-state.js.map +1 -0
  9. package/dist/runtime/process-group-authorization.d.ts +72 -0
  10. package/dist/runtime/process-group-authorization.d.ts.map +1 -1
  11. package/dist/runtime/process-group-authorization.js +31 -0
  12. package/dist/runtime/process-group-authorization.js.map +1 -1
  13. package/dist/runtime/process-group-contract.d.ts +1 -0
  14. package/dist/runtime/process-group-contract.d.ts.map +1 -1
  15. package/dist/runtime/process-group-contract.js +2 -1
  16. package/dist/runtime/process-group-contract.js.map +1 -1
  17. package/dist/runtime/process-group-direct-contract.d.ts +181 -0
  18. package/dist/runtime/process-group-direct-contract.d.ts.map +1 -0
  19. package/dist/runtime/process-group-direct-contract.js +151 -0
  20. package/dist/runtime/process-group-direct-contract.js.map +1 -0
  21. package/dist/runtime/process-group-direct-review.d.ts +203 -0
  22. package/dist/runtime/process-group-direct-review.d.ts.map +1 -0
  23. package/dist/runtime/process-group-direct-review.js +263 -0
  24. package/dist/runtime/process-group-direct-review.js.map +1 -0
  25. package/dist/runtime/process-group-direct-runtime.d.ts +18 -0
  26. package/dist/runtime/process-group-direct-runtime.d.ts.map +1 -0
  27. package/dist/runtime/process-group-direct-runtime.js +154 -0
  28. package/dist/runtime/process-group-direct-runtime.js.map +1 -0
  29. package/dist/runtime/process-group-snapshot.mjs +44 -0
  30. package/dist/uns/handover-manager.d.ts +10 -1
  31. package/dist/uns/handover-manager.d.ts.map +1 -1
  32. package/dist/uns/handover-manager.js +113 -5
  33. package/dist/uns/handover-manager.js.map +1 -1
  34. package/dist/uns/uns-interfaces.d.ts +4 -0
  35. package/dist/uns/uns-interfaces.d.ts.map +1 -1
  36. package/dist/uns/uns-interfaces.js.map +1 -1
  37. package/dist/uns/uns-proxy-process.d.ts +1 -0
  38. package/dist/uns/uns-proxy-process.d.ts.map +1 -1
  39. package/dist/uns/uns-proxy-process.js +6 -2
  40. package/dist/uns/uns-proxy-process.js.map +1 -1
  41. package/dist/uns-config/config-schema.d.ts +4 -1
  42. package/dist/uns-config/config-schema.d.ts.map +1 -1
  43. package/dist/uns-config/uns-core-schema.d.ts +4 -1
  44. package/dist/uns-config/uns-core-schema.d.ts.map +1 -1
  45. package/dist/uns-config/uns-core-schema.js +1 -1
  46. package/dist/uns-config/uns-core-schema.js.map +1 -1
  47. package/dist/uns-mqtt/mqtt-proxy.d.ts +1 -0
  48. package/dist/uns-mqtt/mqtt-proxy.d.ts.map +1 -1
  49. package/dist/uns-mqtt/mqtt-proxy.js +5 -0
  50. package/dist/uns-mqtt/mqtt-proxy.js.map +1 -1
  51. package/dist/uns-mqtt/mqtt-worker.d.ts.map +1 -1
  52. package/dist/uns-mqtt/mqtt-worker.js +13 -1
  53. package/dist/uns-mqtt/mqtt-worker.js.map +1 -1
  54. package/dist/uns-mqtt/throttled-queue.d.ts +8 -1
  55. package/dist/uns-mqtt/throttled-queue.d.ts.map +1 -1
  56. package/dist/uns-mqtt/throttled-queue.js +32 -4
  57. package/dist/uns-mqtt/throttled-queue.js.map +1 -1
  58. package/dist/uns-mqtt/uns-mqtt-proxy.d.ts +26 -2
  59. package/dist/uns-mqtt/uns-mqtt-proxy.d.ts.map +1 -1
  60. package/dist/uns-mqtt/uns-mqtt-proxy.js +82 -6
  61. package/dist/uns-mqtt/uns-mqtt-proxy.js.map +1 -1
  62. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"uns-proxy-process.js","sourceRoot":"","sources":["../../src/uns/uns-prox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AAC,WAAW,uBAAuB,CAAC,CAAC;IAC1D,CAAC;;AAKH,eAAe,eAAe,CAAC;AAE/B,OAAO,EAAE,eAAe,EAAE,CAAC","sourcesContent":["import { MQTT_DRAIN_HANDLER, MQTT_DRAIN_READY_EVENT, drainMqttForMigration, type MqttDrainReceipt } from \"../runtime/mqtt-drain.js\";\nimport { randomBytes } from \"crypto\";\n\nimport logger from \"../logger.js\";\nimport { IMqttParameters } from \"../uns-mqtt/mqtt-interfaces.js\";\nimport MqttProxy from \"../uns-mqtt/mqtt-proxy.js\";\nimport { MqttTopicBuilder } from \"../uns-mqtt/mqtt-topic-builder.js\";\nimport UnsMqttProxy from \"../uns-mqtt/uns-mqtt-proxy.js\";\nimport type { UnsMqttProxyStopOptions } from \"../uns-mqtt/uns-mqtt-proxy.js\";\nimport { HandoverManager } from \"./handover-manager.js\";\nimport { validateHandoverShutdown, type HandoverShutdownHooks } from \"./handover-shutdown.js\";\n// Import configuration and initialization modules.\nimport { MQTT_UPDATE_INTERVAL, PACKAGE_INFO } from \"./process-config.js\";\nimport { type UnsServiceMetadata, type UnsServiceMetadataInput, buildUnsServiceMetadata } from \"./service-metadata.js\";\nimport { StatusMonitor } from \"./status-monitor.js\";\nimport { IUnsMessage, IUnsParameters, IUnsProcessParameters, UnsEvents } from \"./uns-interfaces.js\";\nimport { UnsPacket } from \"./uns-packet.js\";\n\n/**\n * UnsProxyProcess is responsible for managing the process lifecycle,\n * configuring MQTT (subscriptions and publishing for status updates), and\n * handling UNS proxy instances.\n *\n * It leverages HandoverManager for handover events and StatusMonitor for health reporting.\n */\nexport type UnsProxyProcessPluginMethod = (this: UnsProxyProcess, ...args: unknown[]) => unknown;\n\nexport type UnsProxyProcessPluginMethods = Record<string, UnsProxyProcessPluginMethod>;\n\nexport interface UnsProxyProcessPluginApi {\n version: number;\n define(methods: UnsProxyProcessPluginMethods): void;\n UnsProxyProcess: typeof UnsProxyProcess;\n}\n\nexport type UnsProxyProcessPlugin = (api: UnsProxyProcessPluginApi) => void;\n\nclass UnsProxyProcess {\n private active: boolean = false;\n private processStatusTopic: string;\n private processName: string;\n private processId: string;\n private handoverId: string | undefined;\n private handoverShutdown: HandoverShutdownHooks | undefined;\n private unsMqttProxies: UnsMqttProxy[];\n private unsApiProxies: unknown[];\n private processMqttProxy: MqttProxy;\n private handoverManager: HandoverManager;\n private statusMonitor: StatusMonitor;\n private serviceMetadataTopic: string;\n private shutdownPromise: Promise<void> | null = null;\n private migrationDrainPromise: Promise<MqttDrainReceipt> | null = null;\n private migrationDrainHandler?: () => Promise<MqttDrainReceipt>;\n\n // Plugin\n static pluginApiVersion = 1;\n private static registered = new Set<UnsProxyProcessPlugin>();\n private static registeredMethodNames = new Set<string>();\n private static applied = false;\n\n static use(plugin: UnsProxyProcessPlugin) {\n if (this.registered.has(plugin)) return this;\n this.registered.add(plugin);\n if (this.applied) this.applyPlugin(plugin);\n return this;\n }\n\n private static applyPlugin(plugin: UnsProxyProcessPlugin) {\n const define: UnsProxyProcessPluginApi[\"define\"] = (methods) => {\n for (const [name, fn] of Object.entries(methods)) {\n if (typeof fn !== \"function\") {\n throw new TypeError(`UnsProxyProcess plugin attempted to register non-function member \\\"${name}\\\".`);\n }\n if (this.registeredMethodNames.has(name) || Reflect.has(this.prototype, name)) {\n throw new Error(`UnsProxyProcess plugin attempted to overwrite existing member \\\"${name}\\\".`);\n }\n Object.defineProperty(this.prototype, name, {\n value: fn,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n this.registeredMethodNames.add(name);\n }\n };\n\n plugin({\n define,\n version: this.pluginApiVersion,\n UnsProxyProcess: this,\n });\n }\n\n private static applyAll() {\n if (this.applied) return;\n this.applied = true;\n for (const p of this.registered) this.applyPlugin(p);\n }\n\n // References for cleanup.\n private mqttInputHandler: (event: any) => void;\n\n constructor(mqttHost: string, unsProxyProcessParameters: IUnsProcessParameters) {\n (this.constructor as typeof UnsProxyProcess).applyAll(); // Activate all the plugins\n\n this.unsMqttProxies = [];\n this.unsApiProxies = [];\n if (!unsProxyProcessParameters?.processName) {\n throw new Error(\"UnsProxyProcess requires a processName in configuration.\");\n }\n validateHandoverShutdown(unsProxyProcessParameters.handoverShutdown);\n this.handoverShutdown = unsProxyProcessParameters.handoverShutdown\n ? { ...unsProxyProcessParameters.handoverShutdown } : undefined;\n this.processName = unsProxyProcessParameters.processName;\n this.processId = randomBytes(16).toString(\"hex\");\n this.handoverId = unsProxyProcessParameters.handoverId ?? process.env[\"UNS_HANDOVER_ID\"];\n const { name: packageName, version } = PACKAGE_INFO;\n\n // Instantiate the topic builder.\n const topicBuilder = new MqttTopicBuilder(\n `uns-infra/${MqttTopicBuilder.sanitizeTopicPart(packageName)}/${MqttTopicBuilder.sanitizeTopicPart(version)}/${MqttTopicBuilder.sanitizeTopicPart(this.processName)}/`,\n );\n\n // Generate topics.\n const processStatusTopic = topicBuilder.getProcessStatusTopic();\n const handoverTopic = topicBuilder.getHandoverTopic();\n const wildcardActiveTopic = topicBuilder.getWildcardActiveTopic();\n const serviceMetadataTopic = topicBuilder.getServiceMetadataTopic();\n\n this.processStatusTopic = processStatusTopic;\n this.serviceMetadataTopic = serviceMetadataTopic;\n\n // Configure MQTT topics for subscription.\n const mqttSubToTopics = unsProxyProcessParameters?.mqttSubToTopics ?? [wildcardActiveTopic, handoverTopic];\n const mqttParameters: IMqttParameters = {\n mqttSubToTopics,\n username: unsProxyProcessParameters?.username ?? \"\",\n password: unsProxyProcessParameters?.password ?? \"\",\n mqttSSL: unsProxyProcessParameters?.mqttSSL ?? false,\n statusTopic: this.processStatusTopic,\n clientId: unsProxyProcessParameters?.clientId ?? `${this.processName}-${this.processId}`,\n hosts: unsProxyProcessParameters?.hosts,\n servers: unsProxyProcessParameters?.servers,\n port: unsProxyProcessParameters?.port,\n protocol: unsProxyProcessParameters?.protocol,\n keepalive: unsProxyProcessParameters?.keepalive,\n clean: unsProxyProcessParameters?.clean,\n connectTimeout: unsProxyProcessParameters?.connectTimeout,\n reconnectPeriod: unsProxyProcessParameters?.reconnectPeriod,\n reconnectOnConnackError: unsProxyProcessParameters?.reconnectOnConnackError,\n resubscribe: unsProxyProcessParameters?.resubscribe,\n queueQoSZero: unsProxyProcessParameters?.queueQoSZero,\n rejectUnauthorized: unsProxyProcessParameters?.rejectUnauthorized ?? false,\n properties: unsProxyProcessParameters?.properties,\n ca: unsProxyProcessParameters?.ca,\n cert: unsProxyProcessParameters?.cert,\n key: unsProxyProcessParameters?.key,\n servername: unsProxyProcessParameters?.servername,\n };\n\n // Initialize MQTT proxy and start connection.\n this.processMqttProxy = new MqttProxy(mqttHost, this.processName, mqttParameters);\n this.processMqttProxy.start();\n\n // Instantiate and start the StatusMonitor for memory and status updates.\n this.statusMonitor = new StatusMonitor(\n this.processMqttProxy,\n this.processStatusTopic,\n () => this.active,\n MQTT_UPDATE_INTERVAL,\n MQTT_UPDATE_INTERVAL,\n { processName: this.processName, processId: this.processId },\n );\n this.statusMonitor.start();\n }\n\n /**\n * Initializes the HandoverManager instance and sets up event listeners for handover and MQTT input events.\n * Determines handover and force start modes based on process arguments.\n */\n private initHandoverManager(instanceMode: string, handover: boolean, handoverId?: string) {\n const handoverRequestEnabled = instanceMode == \"handover\" ? true : false;\n const forceStartEnabled = instanceMode == \"force\" ? true : false;\n\n this.handoverManager = new HandoverManager(\n this.processName,\n this.processId,\n this.processMqttProxy,\n this.unsMqttProxies,\n handoverRequestEnabled,\n handover ?? true,\n forceStartEnabled,\n handoverId,\n this.handoverShutdown,\n );\n\n // Listen for handover events.\n this.handoverManager.event.on(\"handoverManager\", (event) => {\n this.active = event.active;\n });\n\n // Delegate MQTT events to the HandoverManager.\n this.mqttInputHandler = async (event: UnsEvents[\"input\"]) => {\n await this.handoverManager.handleMqttMessage(event);\n };\n this.processMqttProxy.event.on(\"input\", this.mqttInputHandler);\n }\n\n /**\n * Creates a new UNS proxy instance and stores it for future management.\n */\n public async createUnsMqttProxy(\n mqttHost: string,\n instanceName: string,\n instanceMode: string,\n handover: boolean,\n unsParameters?: IUnsParameters,\n ): Promise<UnsMqttProxy> {\n if (unsParameters?.publishQueue && unsParameters.publishQueue.enabled !== false && handover) {\n throw new Error(\"Persistent MQTT output requires handover=false and one owner; legacy RAM handover does not transfer an outbox\");\n }\n // Wait until the MQTT connection is established before proceeding.\n await this.waitForProcessConnection();\n\n // Currently handover manager can handle only mqtt events\n if (!this.handoverManager) {\n this.initHandoverManager(\n instanceMode,\n handover,\n this.handoverId,\n );\n }\n\n const resolvedUnsParameters: IUnsParameters = {\n ...(unsParameters ?? {}),\n clientId: unsParameters?.clientId ?? `${this.processName}-${instanceName}-${this.processId}`,\n };\n const unsMqttProxy = new UnsMqttProxy(mqttHost, this.processName, instanceName, resolvedUnsParameters);\n\n // Listen for UNS proxy producing topics and publish them via MQTT.\n unsMqttProxy.event.on(\"unsProxyProducedTopics\", (event) => {\n this.processMqttProxy.publish(event.statusTopic, JSON.stringify(event.producedTopics));\n });\n\n // Listen for UNS proxy status events and publish them via MQTT.\n unsMqttProxy.event.on(\"mqttProxyStatus\", (event) => {\n const time = UnsPacket.formatToISO8601(new Date());\n const unsMessage: IUnsMessage = { data: { time, value: event.value, uom: event.uom } };\n UnsPacket.unsPacketFromUnsMessage(unsMessage).then((packet) => {\n this.processMqttProxy.publish(event.statusTopic, JSON.stringify(packet));\n });\n });\n\n this.unsMqttProxies.push(unsMqttProxy);\n return unsMqttProxy;\n }\n\n public async waitForProcessConnection(): Promise<void> {\n while (!this.processMqttProxy?.isConnected) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n\n /**\n * Publishes retained product/system service metadata for controller discovery.\n *\n * The payload is intentionally separate from the volatile active/alive status\n * topics. Controllers can combine this retained identity/capability metadata\n * with live process status to decide whether a service is currently healthy.\n */\n public async publishServiceMetadata(metadata: UnsServiceMetadataInput): Promise<UnsServiceMetadata> {\n await this.waitForProcessConnection();\n const resolved = buildUnsServiceMetadata({\n processName: this.processName,\n processId: this.processId,\n metadata,\n });\n await this.processMqttProxy.publish(this.serviceMetadataTopic, JSON.stringify(resolved), { retain: true });\n return resolved;\n }\n\n /** Call after application input handlers and shutdown hooks are prepared. */\n public enableMigrationDrain(): void {\n const registry = globalThis as unknown as Record<symbol, unknown>;\n if (this.migrationDrainHandler) return;\n if (registry[MQTT_DRAIN_HANDLER]) throw Error(\"One migration drain owner is allowed per process\");\n this.migrationDrainHandler = () => this.drainForMigration();\n registry[MQTT_DRAIN_HANDLER] = this.migrationDrainHandler;\n (process as unknown as { emit(event: string, value: unknown): boolean }).emit(MQTT_DRAIN_READY_EVENT, { protocol: 1 });\n }\n\n /** Works without a Controller too; success means confirmed empty output and closed owners. */\n public drainForMigration(timeoutMs = this.handoverShutdown?.timeoutMs ?? 30_000): Promise<MqttDrainReceipt> {\n if (this.migrationDrainPromise) return this.migrationDrainPromise;\n this.migrationDrainPromise = (async () => {\n const receipt = await drainMqttForMigration({\n quiesce: async () => {\n this.handoverShutdown?.onRelease?.();\n await Promise.all(this.unsMqttProxies.map(proxy => proxy.setSubscriberPassiveAndDrainQueue()));\n },\n finishAccepted: async () => { await this.handoverShutdown?.drain(); },\n outputs: this.unsMqttProxies,\n timeoutMs,\n });\n await this.shutdown({ drain: true, timeoutMs });\n return receipt;\n })().catch(error => { this.migrationDrainPromise = null; throw error; });\n return this.migrationDrainPromise;\n }\n\n /** Stop process timers, status publication and all owned MQTT proxies. */\n public shutdown(options: UnsMqttProxyStopOptions = {}): Promise<void> {\n if (this.shutdownPromise) {\n return this.shutdownPromise;\n }\n\n this.shutdownPromise = this.performShutdown(options);\n return this.shutdownPromise;\n }\n\n private async performShutdown(options: UnsMqttProxyStopOptions): Promise<void> {\n logger.info(`${this.processName} - Shutting down UnsProxyProcess...`);\n const shutdownErrors: Error[] = [];\n\n try {\n this.statusMonitor.stop();\n await this.statusMonitor.publishInactiveStatus();\n } catch (e: any) {\n const reason = e instanceof Error ? e : new Error(String(e));\n logger.error(`${this.processName} - Error stopping StatusMonitor or publishing passive state: ${reason.message}`);\n shutdownErrors.push(reason);\n }\n\n if (this.mqttInputHandler) {\n try {\n this.processMqttProxy.event.off(\"input\", this.mqttInputHandler);\n } catch (e: any) {\n const reason = e instanceof Error ? e : new Error(String(e));\n logger.error(`${this.processName} - Error removing MQTT input handler: ${reason.message}`);\n shutdownErrors.push(reason);\n }\n }\n\n const proxyStopResults = await Promise.allSettled(this.unsMqttProxies.map((proxy) => proxy.stop(options)));\n for (const result of proxyStopResults) {\n if (result.status === \"rejected\") {\n const reason = result.reason instanceof Error ? result.reason : new Error(String(result.reason));\n logger.error(`${this.processName} - Error stopping UNS MQTT proxy: ${reason.message}`);\n shutdownErrors.push(reason);\n }\n }\n\n try {\n if (typeof this.processMqttProxy.stop === \"function\") {\n await this.processMqttProxy.stop();\n }\n } catch (e: any) {\n const reason = e instanceof Error ? e : new Error(String(e));\n logger.error(`${this.processName} - Error stopping MQTT proxy: ${reason.message}`);\n shutdownErrors.push(reason);\n }\n\n if (shutdownErrors.length > 0) {\n throw new AggregateError(shutdownErrors, `${this.processName} - Shutdown completed with errors.`);\n }\n\n if (this.migrationDrainHandler) {\n const registry = globalThis as unknown as Record<symbol, unknown>;\n if (registry[MQTT_DRAIN_HANDLER] === this.migrationDrainHandler) delete registry[MQTT_DRAIN_HANDLER];\n process.channel?.unref();\n }\n logger.info(`${this.processName} - Shutdown complete.`);\n }\n}\n\ninterface UnsProxyProcess {}\n\nexport default UnsProxyProcess;\nexport type { UnsServiceMetadata, UnsServiceMetadataInput };\nexport { UnsProxyProcess };\n"]}
1
+ {"version":3,"file":"uns-proxy-process.js","sourceRoot":"","sources":["../../src/uns/uns-proxy-process.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,qBAAqB,EAAyB,MAAM,0BAA0B,CAAC;AACpI,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAErC,OAAO,MAAM,MAAM,cAAc,CAAC;AAElC,OAAO,SAAS,MAAM,2BAA2B,CAAC;AAClD,OAAO,E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AkB,CAAC,CAAC;YACrG,OAAO,CAAC,OAAO,EAAE,KAAK,EAAE,CAAC;QAC3B,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,WAAW,uBAAuB,CAAC,CAAC;IAC1D,CAAC;;AAKH,eAAe,eAAe,CAAC;AAE/B,OAAO,EAAE,eAAe,EAAE,CAAC","sourcesContent":["import { MQTT_DRAIN_HANDLER, MQTT_DRAIN_READY_EVENT, drainMqttForMigration, type MqttDrainReceipt } from \"../runtime/mqtt-drain.js\";\nimport { randomBytes } from \"crypto\";\n\nimport logger from \"../logger.js\";\nimport { IMqttParameters } from \"../uns-mqtt/mqtt-interfaces.js\";\nimport MqttProxy from \"../uns-mqtt/mqtt-proxy.js\";\nimport { MqttTopicBuilder } from \"../uns-mqtt/mqtt-topic-builder.js\";\nimport UnsMqttProxy from \"../uns-mqtt/uns-mqtt-proxy.js\";\nimport type { UnsMqttProxyStopOptions } from \"../uns-mqtt/uns-mqtt-proxy.js\";\nimport { HandoverManager } from \"./handover-manager.js\";\nimport { validateHandoverShutdown, type HandoverShutdownHooks } from \"./handover-shutdown.js\";\n// Import configuration and initialization modules.\nimport { MQTT_UPDATE_INTERVAL, PACKAGE_INFO } from \"./process-config.js\";\nimport { type UnsServiceMetadata, type UnsServiceMetadataInput, buildUnsServiceMetadata } from \"./service-metadata.js\";\nimport { StatusMonitor } from \"./status-monitor.js\";\nimport { IUnsMessage, IUnsParameters, IUnsProcessParameters, UnsEvents } from \"./uns-interfaces.js\";\nimport { UnsPacket } from \"./uns-packet.js\";\n\n/**\n * UnsProxyProcess is responsible for managing the process lifecycle,\n * configuring MQTT (subscriptions and publishing for status updates), and\n * handling UNS proxy instances.\n *\n * It leverages HandoverManager for handover events and StatusMonitor for health reporting.\n */\nexport type UnsProxyProcessPluginMethod = (this: UnsProxyProcess, ...args: unknown[]) => unknown;\n\nexport type UnsProxyProcessPluginMethods = Record<string, UnsProxyProcessPluginMethod>;\n\nexport interface UnsProxyProcessPluginApi {\n version: number;\n define(methods: UnsProxyProcessPluginMethods): void;\n UnsProxyProcess: typeof UnsProxyProcess;\n}\n\nexport type UnsProxyProcessPlugin = (api: UnsProxyProcessPluginApi) => void;\n\nclass UnsProxyProcess {\n private active: boolean = false;\n private processStatusTopic: string;\n private processName: string;\n private processId: string;\n private handoverId: string | undefined;\n private statefulHandover: boolean = false;\n private handoverShutdown: HandoverShutdownHooks | undefined;\n private unsMqttProxies: UnsMqttProxy[];\n private unsApiProxies: unknown[];\n private processMqttProxy: MqttProxy;\n private handoverManager: HandoverManager;\n private statusMonitor: StatusMonitor;\n private serviceMetadataTopic: string;\n private shutdownPromise: Promise<void> | null = null;\n private migrationDrainPromise: Promise<MqttDrainReceipt> | null = null;\n private migrationDrainHandler?: () => Promise<MqttDrainReceipt>;\n\n // Plugin\n static pluginApiVersion = 1;\n private static registered = new Set<UnsProxyProcessPlugin>();\n private static registeredMethodNames = new Set<string>();\n private static applied = false;\n\n static use(plugin: UnsProxyProcessPlugin) {\n if (this.registered.has(plugin)) return this;\n this.registered.add(plugin);\n if (this.applied) this.applyPlugin(plugin);\n return this;\n }\n\n private static applyPlugin(plugin: UnsProxyProcessPlugin) {\n const define: UnsProxyProcessPluginApi[\"define\"] = (methods) => {\n for (const [name, fn] of Object.entries(methods)) {\n if (typeof fn !== \"function\") {\n throw new TypeError(`UnsProxyProcess plugin attempted to register non-function member \\\"${name}\\\".`);\n }\n if (this.registeredMethodNames.has(name) || Reflect.has(this.prototype, name)) {\n throw new Error(`UnsProxyProcess plugin attempted to overwrite existing member \\\"${name}\\\".`);\n }\n Object.defineProperty(this.prototype, name, {\n value: fn,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n this.registeredMethodNames.add(name);\n }\n };\n\n plugin({\n define,\n version: this.pluginApiVersion,\n UnsProxyProcess: this,\n });\n }\n\n private static applyAll() {\n if (this.applied) return;\n this.applied = true;\n for (const p of this.registered) this.applyPlugin(p);\n }\n\n // References for cleanup.\n private mqttInputHandler: (event: any) => void;\n\n constructor(mqttHost: string, unsProxyProcessParameters: IUnsProcessParameters) {\n (this.constructor as typeof UnsProxyProcess).applyAll(); // Activate all the plugins\n\n this.unsMqttProxies = [];\n this.unsApiProxies = [];\n if (!unsProxyProcessParameters?.processName) {\n throw new Error(\"UnsProxyProcess requires a processName in configuration.\");\n }\n validateHandoverShutdown(unsProxyProcessParameters.handoverShutdown);\n this.handoverShutdown = unsProxyProcessParameters.handoverShutdown\n ? { ...unsProxyProcessParameters.handoverShutdown } : undefined;\n this.statefulHandover = unsProxyProcessParameters.handoverProtocol === \"correlated-v2\";\n this.processName = unsProxyProcessParameters.processName;\n this.processId = randomBytes(16).toString(\"hex\");\n this.handoverId = unsProxyProcessParameters.handoverId ?? process.env[\"UNS_HANDOVER_ID\"];\n const { name: packageName, version } = PACKAGE_INFO;\n\n // Instantiate the topic builder.\n const topicBuilder = new MqttTopicBuilder(\n `uns-infra/${MqttTopicBuilder.sanitizeTopicPart(packageName)}/${MqttTopicBuilder.sanitizeTopicPart(version)}/${MqttTopicBuilder.sanitizeTopicPart(this.processName)}/`,\n );\n\n // Generate topics.\n const processStatusTopic = topicBuilder.getProcessStatusTopic();\n const handoverTopic = topicBuilder.getHandoverTopic();\n const wildcardActiveTopic = topicBuilder.getWildcardActiveTopic();\n const serviceMetadataTopic = topicBuilder.getServiceMetadataTopic();\n\n this.processStatusTopic = processStatusTopic;\n this.serviceMetadataTopic = serviceMetadataTopic;\n\n // Configure MQTT topics for subscription.\n const mqttSubToTopics = unsProxyProcessParameters?.mqttSubToTopics ?? [wildcardActiveTopic, handoverTopic];\n const mqttParameters: IMqttParameters = {\n mqttSubToTopics,\n username: unsProxyProcessParameters?.username ?? \"\",\n password: unsProxyProcessParameters?.password ?? \"\",\n mqttSSL: unsProxyProcessParameters?.mqttSSL ?? false,\n statusTopic: this.processStatusTopic,\n clientId: unsProxyProcessParameters?.clientId ?? `${this.processName}-${this.processId}`,\n hosts: unsProxyProcessParameters?.hosts,\n servers: unsProxyProcessParameters?.servers,\n port: unsProxyProcessParameters?.port,\n protocol: unsProxyProcessParameters?.protocol,\n keepalive: unsProxyProcessParameters?.keepalive,\n clean: unsProxyProcessParameters?.clean,\n connectTimeout: unsProxyProcessParameters?.connectTimeout,\n reconnectPeriod: unsProxyProcessParameters?.reconnectPeriod,\n reconnectOnConnackError: unsProxyProcessParameters?.reconnectOnConnackError,\n resubscribe: unsProxyProcessParameters?.resubscribe,\n queueQoSZero: unsProxyProcessParameters?.queueQoSZero,\n rejectUnauthorized: unsProxyProcessParameters?.rejectUnauthorized ?? false,\n properties: unsProxyProcessParameters?.properties,\n ca: unsProxyProcessParameters?.ca,\n cert: unsProxyProcessParameters?.cert,\n key: unsProxyProcessParameters?.key,\n servername: unsProxyProcessParameters?.servername,\n };\n\n // Initialize MQTT proxy and start connection.\n this.processMqttProxy = new MqttProxy(mqttHost, this.processName, mqttParameters);\n this.processMqttProxy.start();\n\n // Instantiate and start the StatusMonitor for memory and status updates.\n this.statusMonitor = new StatusMonitor(\n this.processMqttProxy,\n this.processStatusTopic,\n () => this.active,\n MQTT_UPDATE_INTERVAL,\n MQTT_UPDATE_INTERVAL,\n { processName: this.processName, processId: this.processId },\n );\n this.statusMonitor.start();\n }\n\n /**\n * Initializes the HandoverManager instance and sets up event listeners for handover and MQTT input events.\n * Determines handover and force start modes based on process arguments.\n */\n private initHandoverManager(instanceMode: string, handover: boolean, handoverId?: string) {\n const handoverRequestEnabled = instanceMode == \"handover\" ? true : false;\n const forceStartEnabled = instanceMode == \"force\" ? true : false;\n\n this.handoverManager = new HandoverManager(\n this.processName,\n this.processId,\n this.processMqttProxy,\n this.unsMqttProxies,\n handoverRequestEnabled,\n handover ?? true,\n forceStartEnabled,\n handoverId,\n this.handoverShutdown,\n this.statefulHandover,\n );\n\n // Listen for handover events.\n this.handoverManager.event.on(\"handoverManager\", (event) => {\n this.active = event.active;\n });\n\n // Delegate MQTT events to the HandoverManager.\n this.mqttInputHandler = async (event: UnsEvents[\"input\"]) => {\n await this.handoverManager.handleMqttMessage(event);\n };\n this.processMqttProxy.event.on(\"input\", this.mqttInputHandler);\n }\n\n /**\n * Creates a new UNS proxy instance and stores it for future management.\n */\n public async createUnsMqttProxy(\n mqttHost: string,\n instanceName: string,\n instanceMode: string,\n handover: boolean,\n unsParameters?: IUnsParameters,\n ): Promise<UnsMqttProxy> {\n if (unsParameters?.publishQueue && unsParameters.publishQueue.enabled !== false && handover) {\n throw new Error(\"Persistent MQTT output requires handover=false and one owner; legacy RAM handover does not transfer an outbox\");\n }\n // Wait until the MQTT connection is established before proceeding.\n await this.waitForProcessConnection();\n\n // Currently handover manager can handle only mqtt events\n if (!this.handoverManager) {\n this.initHandoverManager(\n instanceMode,\n handover,\n this.handoverId,\n );\n }\n\n const resolvedUnsParameters: IUnsParameters = {\n ...(unsParameters ?? {}),\n clientId: unsParameters?.clientId ?? `${this.processName}-${instanceName}-${this.processId}`,\n };\n if (this.statefulHandover && !resolvedUnsParameters?.handoverStateContract) throw Error(\"correlated-v2 requires a calculation-state contract for every MQTT proxy\");\n const unsMqttProxy = new UnsMqttProxy(mqttHost, this.processName, instanceName, resolvedUnsParameters);\n\n // Listen for UNS proxy producing topics and publish them via MQTT.\n unsMqttProxy.event.on(\"unsProxyProducedTopics\", (event) => {\n this.processMqttProxy.publish(event.statusTopic, JSON.stringify(event.producedTopics));\n });\n\n // Listen for UNS proxy status events and publish them via MQTT.\n unsMqttProxy.event.on(\"mqttProxyStatus\", (event) => {\n const time = UnsPacket.formatToISO8601(new Date());\n const unsMessage: IUnsMessage = { data: { time, value: event.value, uom: event.uom } };\n UnsPacket.unsPacketFromUnsMessage(unsMessage).then((packet) => {\n this.processMqttProxy.publish(event.statusTopic, JSON.stringify(packet));\n });\n });\n\n this.unsMqttProxies.push(unsMqttProxy);\n return unsMqttProxy;\n }\n\n public async waitForProcessConnection(): Promise<void> {\n while (!this.processMqttProxy?.isConnected) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n\n /**\n * Publishes retained product/system service metadata for controller discovery.\n *\n * The payload is intentionally separate from the volatile active/alive status\n * topics. Controllers can combine this retained identity/capability metadata\n * with live process status to decide whether a service is currently healthy.\n */\n public async publishServiceMetadata(metadata: UnsServiceMetadataInput): Promise<UnsServiceMetadata> {\n await this.waitForProcessConnection();\n const resolved = buildUnsServiceMetadata({\n processName: this.processName,\n processId: this.processId,\n metadata,\n });\n await this.processMqttProxy.publish(this.serviceMetadataTopic, JSON.stringify(resolved), { retain: true });\n return resolved;\n }\n\n /** Call after application input handlers and shutdown hooks are prepared. */\n public enableMigrationDrain(): void {\n const registry = globalThis as unknown as Record<symbol, unknown>;\n if (this.migrationDrainHandler) return;\n if (registry[MQTT_DRAIN_HANDLER]) throw Error(\"One migration drain owner is allowed per process\");\n this.migrationDrainHandler = () => this.drainForMigration();\n registry[MQTT_DRAIN_HANDLER] = this.migrationDrainHandler;\n (process as unknown as { emit(event: string, value: unknown): boolean }).emit(MQTT_DRAIN_READY_EVENT, { protocol: 1, ...(this.statefulHandover ? { handoverProtocol: 2 } : {}) });\n }\n\n /** Works without a Controller too; success means confirmed empty output and closed owners. */\n public drainForMigration(timeoutMs = this.handoverShutdown?.timeoutMs ?? 30_000): Promise<MqttDrainReceipt> {\n if (this.migrationDrainPromise) return this.migrationDrainPromise;\n this.migrationDrainPromise = (async () => {\n const receipt = await drainMqttForMigration({\n quiesce: async () => {\n this.handoverShutdown?.onRelease?.();\n await Promise.all(this.unsMqttProxies.map(proxy => proxy.setSubscriberPassiveAndDrainQueue()));\n },\n finishAccepted: async () => { await this.handoverShutdown?.drain(); },\n outputs: this.unsMqttProxies,\n timeoutMs,\n });\n await this.shutdown({ drain: true, timeoutMs });\n return receipt;\n })().catch(error => { this.migrationDrainPromise = null; throw error; });\n return this.migrationDrainPromise;\n }\n\n /** Stop process timers, status publication and all owned MQTT proxies. */\n public shutdown(options: UnsMqttProxyStopOptions = {}): Promise<void> {\n if (this.shutdownPromise) {\n return this.shutdownPromise;\n }\n\n this.shutdownPromise = this.performShutdown(options);\n return this.shutdownPromise;\n }\n\n private async performShutdown(options: UnsMqttProxyStopOptions): Promise<void> {\n logger.info(`${this.processName} - Shutting down UnsProxyProcess...`);\n const shutdownErrors: Error[] = [];\n\n try {\n this.statusMonitor.stop();\n await this.statusMonitor.publishInactiveStatus();\n } catch (e: any) {\n const reason = e instanceof Error ? e : new Error(String(e));\n logger.error(`${this.processName} - Error stopping StatusMonitor or publishing passive state: ${reason.message}`);\n shutdownErrors.push(reason);\n }\n\n if (this.mqttInputHandler) {\n try {\n this.processMqttProxy.event.off(\"input\", this.mqttInputHandler);\n } catch (e: any) {\n const reason = e instanceof Error ? e : new Error(String(e));\n logger.error(`${this.processName} - Error removing MQTT input handler: ${reason.message}`);\n shutdownErrors.push(reason);\n }\n }\n\n const proxyStopResults = await Promise.allSettled(this.unsMqttProxies.map((proxy) => proxy.stop(options)));\n for (const result of proxyStopResults) {\n if (result.status === \"rejected\") {\n const reason = result.reason instanceof Error ? result.reason : new Error(String(result.reason));\n logger.error(`${this.processName} - Error stopping UNS MQTT proxy: ${reason.message}`);\n shutdownErrors.push(reason);\n }\n }\n\n try {\n if (typeof this.processMqttProxy.stop === \"function\") {\n await this.processMqttProxy.stop();\n }\n } catch (e: any) {\n const reason = e instanceof Error ? e : new Error(String(e));\n logger.error(`${this.processName} - Error stopping MQTT proxy: ${reason.message}`);\n shutdownErrors.push(reason);\n }\n\n if (shutdownErrors.length > 0) {\n throw new AggregateError(shutdownErrors, `${this.processName} - Shutdown completed with errors.`);\n }\n\n if (this.migrationDrainHandler) {\n const registry = globalThis as unknown as Record<symbol, unknown>;\n if (registry[MQTT_DRAIN_HANDLER] === this.migrationDrainHandler) delete registry[MQTT_DRAIN_HANDLER];\n process.channel?.unref();\n }\n logger.info(`${this.processName} - Shutdown complete.`);\n }\n}\n\ninterface UnsProxyProcess {}\n\nexport default UnsProxyProcess;\nexport type { UnsServiceMetadata, UnsServiceMetadataInput };\nexport { UnsProxyProcess };\n"]}
@@ -39,7 +39,10 @@ export declare const baseSchema: z.ZodObject<{
39
39
  }>>;
40
40
  processName: z.ZodString;
41
41
  handover: z.ZodDefault<z.ZodBoolean>;
42
- handoverProtocol: z.ZodOptional<z.ZodLiteral<"correlated-v1">>;
42
+ handoverProtocol: z.ZodOptional<z.ZodEnum<{
43
+ "correlated-v1": "correlated-v1";
44
+ "correlated-v2": "correlated-v2";
45
+ }>>;
43
46
  supervisor: z.ZodOptional<z.ZodObject<{
44
47
  enabled: z.ZodDefault<z.ZodBoolean>;
45
48
  restartOnExit: z.ZodDefault<z.ZodBoolean>;
@@ -1 +1 @@
1
- {"version":3,"file":"config-schema.d.ts","sourceRoot":"","sources":["../../src/uns-config/config-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAMxB,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8CAAmE,CAAC;AAG3F,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,UAAU,CAAC,CAAC"}
1
+ {"version":3,"file":"config-schema.d.ts","sourceRoot":"","sources":["../../src/uns-config/config-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAMxB,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8CAAmE,CAAC;AAG3F,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,UAAU,CAAC,CAAC"}
@@ -269,7 +269,10 @@ export declare const unsCoreSchema: z.ZodObject<{
269
269
  }>>;
270
270
  processName: z.ZodString;
271
271
  handover: z.ZodDefault<z.ZodBoolean>;
272
- handoverProtocol: z.ZodOptional<z.ZodLiteral<"correlated-v1">>;
272
+ handoverProtocol: z.ZodOptional<z.ZodEnum<{
273
+ "correlated-v1": "correlated-v1";
274
+ "correlated-v2": "correlated-v2";
275
+ }>>;
273
276
  supervisor: z.ZodOptional<z.ZodObject<{
274
277
  enabled: z.ZodDefault<z.ZodBoolean>;
275
278
  restartOnExit: z.ZodDefault<z.ZodBoolean>;
@@ -1 +1 @@
1
- {"version":3,"file":"uns-core-schema.d.ts","sourceRoot":"","sources":["../../src/uns-config/uns-core-schema.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AA2DxB,eAAO,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAgC3B,CAAC;AAEJ,wFAAwF;AACxF,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAEzB,CAAC;AAEZ,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA0Cf,CAAC;AAEZ,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC"}
@@ -96,7 +96,7 @@ export const unsCoreSchema = z
96
96
  instanceMode: z.enum(["wait", "force", "handover"]).default("wait"),
97
97
  processName: z.string().min(1).describe("Process name used in MQTT topics and logs."),
98
98
  handover: z.boolean().default(true),
99
- handoverProtocol: z.literal("correlated-v1").optional().describe("Opt-in controller-correlated MQTT handover protocol."),
99
+ handoverProtocol: z.enum(["correlated-v1", "correlated-v2"]).optional().describe("Opt-in controller-correlated MQTT handover protocol."),
100
100
  supervisor: supervisorSchema.optional(),
101
101
  jwksWellKnownUrl: z.string().url().optional(),
102
102
  kidWellKnownUrl: z.string().url().optional(),
@@ -1 +1 @@
1
- {"version":3,"file":"uns-core-schema.js","sourceRoot":"","sources":["../../src/uns-config/uns-core-schema.ts"],"names":[],"mappings":"AAAA,oCAAoC;AACpC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAE/E,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAE7D,4EAA4E;AAC5E,2EAA2E;AAC3E,MAAM,aAAa,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AAErD,MAAM,kBAAkB,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;AAEhF,MAAM,gBAAgB,GAAG,CAAC;KACvB,MAAM,CAAC;IACN,IAAI,EAAE,eAAe;IACrB,IAAI,EAAE,aAAa,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IAC3C,QAAQ,EAAE,kBAAkB,CAAC,QAAQ,EAAE;CACxC,CAAC;KACD,MAAM,EAAE,CAAC;AAEZ,MAAM,2BAA2B,GAAG,CAAC;KAClC,MAAM,CAAC;IACN,qBAAqB,EAAE,aAAa,EAAE,CAAC,WAAW,EAAE,CAAC,QAAQ,EAAE;IAC/D,cAAc,EAAE,aAAa,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IACrD,iBAAiB,EAAE,aAAa,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE;IACxD,iBAAiB,EAAE,aAAa,EAAE,CAAC,WAAW,EAAE,CAAC,QAAQ,EAAE;IAC3D,0BAA0B,EAAE,CAAC,CAAC,O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IACnC,MAAM,EAAE,uBAAuB,CAAC,QAAQ,EAAE;IAC1C,KAAK,EAAE,iBAAiB;IACxB,MAAM,EAAE,CAAC;SACN,MAAM,CAAC;QACN,QAAQ,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC;QAC1D,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;QAC/B,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE;KACtC,CAAC;SACD,MAAM,EAAE;SACR,QAAQ,EAAE;CACd,CAAC;KACD,MAAM,EAAE,CAAC","sourcesContent":["// src/uns-config/uns-core-schema.ts\nimport { z } from \"zod\";\nimport { mqttPublishQueueSchema } from \"../uns-mqtt/publish-queue-contract.js\";\n\nimport { hostValueSchema } from \"./host-placeholders.js\";\nimport { secretValueSchema } from \"./secret-placeholders.js\";\n\n// Zod 4's .int() also enforces Number.isSafeInteger(). Zod 3 accepted every\n// finite integer, so multipleOf(1) preserves the existing config contract.\nconst integerSchema = () => z.number().multipleOf(1);\n\nconst mqttProtocolSchema = z.enum([\"mqtt\", \"mqtts\", \"ws\", \"wss\", \"tcp\", \"ssl\"]);\n\nconst mqttServerSchema = z\n .object({\n host: hostValueSchema,\n port: integerSchema().positive().optional(),\n protocol: mqttProtocolSchema.optional(),\n })\n .strict();\n\nconst mqttConnectPropertiesSchema = z\n .object({\n sessionExpiryInterval: integerSchema().nonnegative().optional(),\n receiveMaximum: integerSchema().positive().optional(),\n maximumPacketSize: integerSchema().positive().optional(),\n topicAliasMaximum: integerSchema().nonnegative().optional(),\n requestResponseInformation: z.boolean().optional(),\n requestProblemInformation: z.boolean().optional(),\n userProperties: z.record(z.string(), z.string()).optional(),\n })\n .strict();\n\nconst loggingLevelSchema = z.enum([\"error\", \"warn\", \"info\", \"http\", \"verbose\", \"debug\", \"silly\"]);\n\nconst supervisorSchema = z\n .object({\n enabled: z.boolean().default(false).describe(\"Enable controller/PM2 supervisor handling for this RTT instance.\"),\n restartOnExit: z.boolean().default(false).describe(\"Let PM2 restart the process when it exits unexpectedly.\"),\n maxMemoryMb: z.number().multipleOf(1).positive().optional().describe(\"Optional PM2 memory restart limit in megabytes.\"),\n restartOnUnhealthy: z\n .boolean()\n .default(false)\n .describe(\"Let the controller auto-start this instance when required system-service runtime signals are absent.\"),\n unhealthyAfterMs: z\n .number()\n .multipleOf(1)\n .positive()\n .default(60_000)\n .describe(\"How long runtime signals must stay unhealthy before the controller supervisor can act.\"),\n restartCooldownMs: z\n .number()\n .multipleOf(1)\n .positive()\n .default(300_000)\n .describe(\"Minimum time between controller supervisor restart attempts for this instance.\"),\n })\n .strict()\n .describe(\"Optional PM2/controller supervisor guard settings for this RTT instance.\");\n\nexport const mqttChannelSchema = z\n .object({\n host: hostValueSchema.optional(),\n hosts: z.array(hostValueSchema).optional(),\n servers: z.array(mqttServerSchema).optional(),\n port: integerSchema().positive().optional(),\n protocol: mqttProtocolSchema.optional(),\n username: z.string().optional(),\n password: secretValueSchema.optional(),\n clientId: z.string().optional(),\n clean: z.boolean().optional(),\n keepalive: integerSchema().nonnegative().optional(),\n connectTimeout: integerSchema().nonnegative().optional(),\n reconnectPeriod: integerSchema().nonnegative().optional(),\n reconnectOnConnackError: z.boolean().optional(),\n resubscribe: z.boolean().optional(),\n queueQoSZero: z.boolean().optional(),\n rejectUnauthorized: z.boolean().optional(),\n properties: mqttConnectPropertiesSchema.optional(),\n ca: z.string().optional(),\n cert: z.string().optional(),\n key: z.string().optional(),\n servername: z.string().optional(),\n })\n .strict()\n .refine(\n (value) => {\n return !!value.host || (Array.isArray(value.hosts) && value.hosts.length > 0) || (Array.isArray(value.servers) && value.servers.length > 0);\n },\n {\n message: \"One of host, hosts, or servers must be provided.\",\n },\n );\n\n/** Publishing options belong to output, never to the infra/control or input channel. */\nexport const mqttOutputChannelSchema = mqttChannelSchema.extend({\n publishQueue: mqttPublishQueueSchema.optional().describe(\"Opt-in MQTT output persistence; does not persist input subscriptions.\"),\n}).strict();\n\nexport const unsCoreSchema = z\n .object({\n uns: z\n .object({\n graphql: z.string().url(),\n rest: z.string().url(),\n token: secretValueSchema.optional().describe(\"Bearer token used for service-to-service access to the UNS instance.\"),\n email: z.string().email().optional().describe(\"Email used when authenticating to graphql endpoint of the UNS instance.\"),\n password: secretValueSchema.optional().describe(\"Password or secret value paired with the UNS email.\"),\n instanceMode: z.enum([\"wait\", \"force\", \"handover\"]).default(\"wait\"),\n processName: z.string().min(1).describe(\"Process name used in MQTT topics and logs.\"),\n handover: z.boolean().default(true),\n handoverProtocol: z.literal(\"correlated-v1\").optional().describe(\"Opt-in controller-correlated MQTT handover protocol.\"),\n supervisor: supervisorSchema.optional(),\n jwksWellKnownUrl: z.string().url().optional(),\n kidWellKnownUrl: z.string().url().optional(),\n env: z.enum([\"dev\", \"staging\", \"test\", \"prod\"]).default(\"dev\"),\n })\n .strict(),\n\n logging: z\n .object({\n adapter: z.string().min(1).default(\"udp\"),\n host: hostValueSchema,\n port: integerSchema().positive().default(12201),\n level: loggingLevelSchema.default(\"info\"),\n })\n .strict()\n .optional(),\n\n input: mqttChannelSchema.optional(),\n output: mqttOutputChannelSchema.optional(),\n infra: mqttChannelSchema,\n devops: z\n .object({\n provider: z.enum([\"azure-devops\"]).default(\"azure-devops\"),\n organization: z.string().min(1),\n project: z.string().min(1).optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nexport type UnsCore = z.infer<typeof unsCoreSchema>;\n"]}
1
+ {"version":3,"file":"uns-core-schema.js","sourceRoot":"","sources":["../../src/uns-config/uns-core-schema.ts"],"names":[],"mappings":"AAAA,oCAAoC;AACpC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAE/E,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAA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AC/B,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE;KACtC,CAAC;SACD,MAAM,EAAE;SACR,QAAQ,EAAE;CACd,CAAC;KACD,MAAM,EAAE,CAAC","sourcesContent":["// src/uns-config/uns-core-schema.ts\nimport { z } from \"zod\";\nimport { mqttPublishQueueSchema } from \"../uns-mqtt/publish-queue-contract.js\";\n\nimport { hostValueSchema } from \"./host-placeholders.js\";\nimport { secretValueSchema } from \"./secret-placeholders.js\";\n\n// Zod 4's .int() also enforces Number.isSafeInteger(). Zod 3 accepted every\n// finite integer, so multipleOf(1) preserves the existing config contract.\nconst integerSchema = () => z.number().multipleOf(1);\n\nconst mqttProtocolSchema = z.enum([\"mqtt\", \"mqtts\", \"ws\", \"wss\", \"tcp\", \"ssl\"]);\n\nconst mqttServerSchema = z\n .object({\n host: hostValueSchema,\n port: integerSchema().positive().optional(),\n protocol: mqttProtocolSchema.optional(),\n })\n .strict();\n\nconst mqttConnectPropertiesSchema = z\n .object({\n sessionExpiryInterval: integerSchema().nonnegative().optional(),\n receiveMaximum: integerSchema().positive().optional(),\n maximumPacketSize: integerSchema().positive().optional(),\n topicAliasMaximum: integerSchema().nonnegative().optional(),\n requestResponseInformation: z.boolean().optional(),\n requestProblemInformation: z.boolean().optional(),\n userProperties: z.record(z.string(), z.string()).optional(),\n })\n .strict();\n\nconst loggingLevelSchema = z.enum([\"error\", \"warn\", \"info\", \"http\", \"verbose\", \"debug\", \"silly\"]);\n\nconst supervisorSchema = z\n .object({\n enabled: z.boolean().default(false).describe(\"Enable controller/PM2 supervisor handling for this RTT instance.\"),\n restartOnExit: z.boolean().default(false).describe(\"Let PM2 restart the process when it exits unexpectedly.\"),\n maxMemoryMb: z.number().multipleOf(1).positive().optional().describe(\"Optional PM2 memory restart limit in megabytes.\"),\n restartOnUnhealthy: z\n .boolean()\n .default(false)\n .describe(\"Let the controller auto-start this instance when required system-service runtime signals are absent.\"),\n unhealthyAfterMs: z\n .number()\n .multipleOf(1)\n .positive()\n .default(60_000)\n .describe(\"How long runtime signals must stay unhealthy before the controller supervisor can act.\"),\n restartCooldownMs: z\n .number()\n .multipleOf(1)\n .positive()\n .default(300_000)\n .describe(\"Minimum time between controller supervisor restart attempts for this instance.\"),\n })\n .strict()\n .describe(\"Optional PM2/controller supervisor guard settings for this RTT instance.\");\n\nexport const mqttChannelSchema = z\n .object({\n host: hostValueSchema.optional(),\n hosts: z.array(hostValueSchema).optional(),\n servers: z.array(mqttServerSchema).optional(),\n port: integerSchema().positive().optional(),\n protocol: mqttProtocolSchema.optional(),\n username: z.string().optional(),\n password: secretValueSchema.optional(),\n clientId: z.string().optional(),\n clean: z.boolean().optional(),\n keepalive: integerSchema().nonnegative().optional(),\n connectTimeout: integerSchema().nonnegative().optional(),\n reconnectPeriod: integerSchema().nonnegative().optional(),\n reconnectOnConnackError: z.boolean().optional(),\n resubscribe: z.boolean().optional(),\n queueQoSZero: z.boolean().optional(),\n rejectUnauthorized: z.boolean().optional(),\n properties: mqttConnectPropertiesSchema.optional(),\n ca: z.string().optional(),\n cert: z.string().optional(),\n key: z.string().optional(),\n servername: z.string().optional(),\n })\n .strict()\n .refine(\n (value) => {\n return !!value.host || (Array.isArray(value.hosts) && value.hosts.length > 0) || (Array.isArray(value.servers) && value.servers.length > 0);\n },\n {\n message: \"One of host, hosts, or servers must be provided.\",\n },\n );\n\n/** Publishing options belong to output, never to the infra/control or input channel. */\nexport const mqttOutputChannelSchema = mqttChannelSchema.extend({\n publishQueue: mqttPublishQueueSchema.optional().describe(\"Opt-in MQTT output persistence; does not persist input subscriptions.\"),\n}).strict();\n\nexport const unsCoreSchema = z\n .object({\n uns: z\n .object({\n graphql: z.string().url(),\n rest: z.string().url(),\n token: secretValueSchema.optional().describe(\"Bearer token used for service-to-service access to the UNS instance.\"),\n email: z.string().email().optional().describe(\"Email used when authenticating to graphql endpoint of the UNS instance.\"),\n password: secretValueSchema.optional().describe(\"Password or secret value paired with the UNS email.\"),\n instanceMode: z.enum([\"wait\", \"force\", \"handover\"]).default(\"wait\"),\n processName: z.string().min(1).describe(\"Process name used in MQTT topics and logs.\"),\n handover: z.boolean().default(true),\n handoverProtocol: z.enum([\"correlated-v1\", \"correlated-v2\"]).optional().describe(\"Opt-in controller-correlated MQTT handover protocol.\"),\n supervisor: supervisorSchema.optional(),\n jwksWellKnownUrl: z.string().url().optional(),\n kidWellKnownUrl: z.string().url().optional(),\n env: z.enum([\"dev\", \"staging\", \"test\", \"prod\"]).default(\"dev\"),\n })\n .strict(),\n\n logging: z\n .object({\n adapter: z.string().min(1).default(\"udp\"),\n host: hostValueSchema,\n port: integerSchema().positive().default(12201),\n level: loggingLevelSchema.default(\"info\"),\n })\n .strict()\n .optional(),\n\n input: mqttChannelSchema.optional(),\n output: mqttOutputChannelSchema.optional(),\n infra: mqttChannelSchema,\n devops: z\n .object({\n provider: z.enum([\"azure-devops\"]).default(\"azure-devops\"),\n organization: z.string().min(1),\n project: z.string().min(1).optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nexport type UnsCore = z.infer<typeof unsCoreSchema>;\n"]}
@@ -43,6 +43,7 @@ export default class MqttProxy {
43
43
  private resolveDefaultPort;
44
44
  private ensureStatusUpdateInterval;
45
45
  private ensureTransformationStatsInterval;
46
+ private lastTransportConnected;
46
47
  private emitSubscriptionReadiness;
47
48
  private subscribeToTopics;
48
49
  private buildServers;
@@ -1 +1 @@
1
- {"version":3,"file":"mqtt-proxy.d.ts","sourceRoot":"","sources":["../../src/uns-mqtt/mqtt-proxy.ts"],"names":[],"mappings":"AACA,OAAO,IAAoC,MAAM,MAAM,CAAC;AAExD,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,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CAAkC;IAK1C,OAAO,CAAC,gBAAgB;YAsCV,4BAA4B;CAwC3C;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,aAAa,CAY7D"}
@@ -70,7 +70,12 @@ export default class MqttProxy {
70
70
  }, 60000);
71
71
  }
72
72
  }
73
+ lastTransportConnected;
73
74
  emitSubscriptionReadiness(force = false) {
75
+ if (force || this.lastTransportConnected !== this.isConnected) {
76
+ this.lastTransportConnected = this.isConnected;
77
+ this.event.emit("mqttProxyStatus", { event: "mqtt-connected", value: this.isConnected ? 1 : 0, uom: DataSizeMeasurements.Bit, statusTopic: this.statusTopic + "mqtt-connected" });
78
+ }
74
79
  const ready = this.subscriptionReadiness.ready();
75
80
  if (!force && ready === this.lastSubscriptionReady)
76
81
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"mqtt-proxy.js","sourceRoot":"","sources":["../../src/uns-mqtt/mqtt-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,IAAoC,MAAM,MAAM,CAAC;AACxD,OAAO,MAAM,MAAM,cAAc,CAAC;AAElC,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAG9D,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAaxF,MAAM,CAAC,OAAO,OAAO,SAAS;IACrB,KAAK,GAA+B,IAAI,eAAe,EAAa,CAAC;IACrE,WAAW,CAAS;IACpB,YAAY,CAAS;IACpB,QAAQ,CAAS;IACjB,eAAe,CAAoB;IACnC,OAAO,CAAU;IACjB,UAAU,CAAa;IACvB,SAAS,CAAO;IAChB,cAAc,CAAkB;IAChC,oBAAoB,CAAiC;IACrD,2BAA2B,GAA0B,IAAI,CAAC;IAC1D,qBAAqB,GAAG,CAAC,CAAC;IAC1B,qBAAqB,GAAG,CAAC,CAAC;IAC1B,sBAAsB,GAAG,CAAC,CAAC;IAC3B,sBAA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,KAAK,EAAE,KAAK,CAAC,CAAC;IACpD,CAAC;AACH,CAAC","sourcesContent":["import { SubscriptionReadiness } from \"./subscription-readiness.js\";\nimport mqtt, { IClientOptions, MqttClient } from \"mqtt\";\nimport logger from \"../logger.js\";\nimport { UnsEvents } from \"../uns/uns-interfaces.js\";\nimport { UnsEventEmitter } from \"../uns/uns-event-emitter.js\";\nimport { IMqttParameters } from \"./mqtt-interfaces.js\";\nimport { MqttWorker } from \"./mqtt-worker.js\";\nimport { DataSizeMeasurements, PhysicalMeasurements } from \"../uns/uns-measurements.js\";\n\nexport type MqttStopOptions = {\n silent?: boolean;\n force?: boolean;\n reason?: \"retry\" | \"shutdown\";\n};\n\ntype MqttErrorInfo = {\n code: string | number;\n message: string;\n};\n\nexport default class MqttProxy {\n public event: UnsEventEmitter<UnsEvents> = new UnsEventEmitter<UnsEvents>();\n public statusTopic: string;\n public instanceName: string;\n private mqttHost: string;\n private mqttSubToTopics: string | string[];\n private mqttSSL: boolean;\n private mqttClient: MqttClient;\n private startDate: Date;\n private mqttParameters: IMqttParameters;\n private statusUpdateInterval: ReturnType<typeof setInterval>;\n private transformationStatsInterval: NodeJS.Timeout | null = null;\n private publishedMessageCount = 0;\n private publishedMessageBytes = 0;\n private subscribedMessageCount = 0;\n private subscribedMessageBytes = 0;\n private mqttWorker: MqttWorker;\n public isConnected = false;\n private subscriptionReadiness = new SubscriptionReadiness();\n private lastSubscriptionReady: boolean | null = null;\n private rejectUnauthorized: boolean;\n private pendingReconnectWait: Promise<void> | null = null;\n private hasEstablishedConnection = false;\n private startupSettled = false;\n private startupResolve: (() => void) | null = null;\n private startupReject: ((error: unknown) => void) | null = null;\n\n constructor(mqttHost: string, instanceName: string, mqttParameters: IMqttParameters, mqttWorker?: MqttWorker) {\n this.mqttSSL = mqttParameters?.mqttSSL ?? false;\n this.rejectUnauthorized = mqttParameters.rejectUnauthorized ?? false;\n this.mqttSubToTopics = mqttParameters?.mqttSubToTopics ?? [];\n this.mqttHost = mqttHost;\n this.startDate = new Date();\n this.instanceName = instanceName ?? \"process\";\n this.statusTopic = `${mqttParameters?.statusTopic}`;\n this.mqttParameters = mqttParameters ?? {};\n this.mqttWorker = mqttWorker;\n }\n\n private resolveProtocol(): IMqttParameters[\"protocol\"] {\n return this.mqttParameters.protocol ?? (this.mqttSSL ? \"mqtts\" : \"mqtt\");\n }\n\n private resolveDefaultPort(protocol: IMqttParameters[\"protocol\"]): number {\n switch (protocol) {\n case \"mqtts\":\n case \"ssl\":\n return 8883;\n case \"wss\":\n return 443;\n case \"ws\":\n return 80;\n case \"tcp\":\n case \"mqtt\":\n default:\n return 1883;\n }\n }\n\n private ensureStatusUpdateInterval(): void {\n if (this.statusTopic && !this.statusUpdateInterval) {\n this.statusUpdateInterval = setInterval(() => this.emitStatusUpdates(), 10000);\n }\n }\n\n private ensureTransformationStatsInterval(): void {\n if (!this.transformationStatsInterval) {\n this.transformationStatsInterval = setInterval(() => {\n this.emitTransformationStatistics();\n }, 60000);\n }\n }\n\n private emitSubscriptionReadiness(force = false): void {\n const ready = this.subscriptionReadiness.ready();\n if (!force && ready === this.lastSubscriptionReady) return;\n this.lastSubscriptionReady = ready;\n this.event.emit(\"mqttProxyStatus\", {event: \"mqtt-subscriptions-ready\", value: ready ? 1 : 0,\n uom: DataSizeMeasurements.Bit, statusTopic: this.statusTopic + \"mqtt-subscriptions-ready\"});\n }\n\n private subscribeToTopics(): void {\n if (this.mqttSubToTopics && this.mqttSubToTopics.length > 0) {\n logger.debug(`${this.instanceName} - Subscribed to ${this.mqttSubToTopics.length} topics.`);\n this.mqttClient.subscribe(this.mqttSubToTopics, { qos: 0 });\n }\n }\n\n private buildServers(defaultProtocol: IMqttParameters[\"protocol\"]): IClientOptions[\"servers\"] | undefined {\n const servers: IClientOptions[\"servers\"] = [];\n const { port } = this.mqttParameters;\n const protocol = this.mqttParameters.protocol ?? defaultProtocol;\n\n if (Array.isArray(this.mqttParameters.servers) && this.mqttParameters.servers.length > 0) {\n for (const server of this.mqttParameters.servers) {\n if (!server?.host) continue;\n const resolvedProtocol = server.protocol ?? protocol;\n const resolvedPort =\n typeof server.port === \"number\"\n ? server.port\n : typeof port === \"number\"\n ? port\n : this.resolveDefaultPort(resolvedProtocol);\n const entry: { host: string; port: number; protocol?: IMqttParameters[\"protocol\"] } = {\n host: server.host,\n port: resolvedPort,\n };\n if (resolvedProtocol) {\n entry.protocol = resolvedProtocol;\n }\n servers.push(entry);\n }\n } else if (Array.isArray(this.mqttParameters.hosts) && this.mqttParameters.hosts.length > 0) {\n for (const host of this.mqttParameters.hosts) {\n if (!host) continue;\n const resolvedPort = typeof port === \"number\" ? port : this.resolveDefaultPort(protocol);\n const entry: { host: string; port: number; protocol?: IMqttParameters[\"protocol\"] } = {\n host,\n port: resolvedPort,\n };\n if (protocol) {\n entry.protocol = protocol;\n }\n servers.push(entry);\n }\n }\n\n return servers.length > 0 ? servers : undefined;\n }\n\n public async start(): Promise<void> {\n logger.debug(`${this.instanceName} - Connecting to MQTT broker...`);\n this.startupSettled = false;\n\n return new Promise<void>((resolve, reject) => {\n this.startupResolve = resolve;\n this.startupReject = reject;\n try {\n const username = this.mqttParameters.username;\n const password = this.mqttParameters.password;\n const clientId = this.mqttParameters.clientId ?? this.instanceName;\n const protocol = this.resolveProtocol();\n\n const options: IClientOptions = {\n username,\n password,\n protocolVersion: 5,\n rejectUnauthorized: this.rejectUnauthorized,\n keepalive: this.mqttParameters.keepalive,\n clean: this.mqttParameters.clean ?? true,\n connectTimeout: this.mqttParameters.connectTimeout,\n reconnectPeriod: this.mqttParameters.reconnectPeriod,\n reconnectOnConnackError: this.mqttParameters.reconnectOnConnackError,\n resubscribe: this.mqttParameters.resubscribe,\n queueQoSZero: this.mqttParameters.queueQoSZero,\n properties: this.mqttParameters.properties,\n ca: this.mqttParameters.ca,\n cert: this.mqttParameters.cert,\n key: this.mqttParameters.key,\n servername: this.mqttParameters.servername,\n \n will: {\n topic: `${this.statusTopic}alive`,\n payload: Buffer.from(\"\"),\n qos: 0,\n retain: true,\n properties: { messageExpiryInterval: 3600 },\n },\n clientId,\n };\n\n const servers = this.buildServers(protocol);\n if (servers) {\n options.servers = servers;\n options.protocol = protocol;\n this.mqttClient = mqtt.connect(options);\n } else {\n options.host = this.mqttHost;\n options.port = this.mqttParameters.port;\n options.protocol = protocol;\n this.mqttClient = mqtt.connect(options);\n }\n\n const onConnect = () => this.handleMqttConnect();\n\n this.mqttClient.on(\"connect\", onConnect);\n this.mqttClient.on(\"packetsend\", packet => {\n this.subscriptionReadiness.sent(packet as Parameters<SubscriptionReadiness[\"sent\"]>[0]);\n this.emitSubscriptionReadiness();\n });\n this.mqttClient.on(\"packetreceive\", packet => {\n this.subscriptionReadiness.received(packet as Parameters<SubscriptionReadiness[\"received\"]>[0]);\n this.emitSubscriptionReadiness();\n });\n\n this.mqttClient.on(\"message\", (topic: string, message: Buffer, packet: mqtt.IPublishPacket) => {\n try {\n logger.debug(`${this.instanceName} - Message received on topic ${topic}`);\n this.event.emit(\"input\", {\n message: message.toString(),\n topic: topic,\n packet: packet,\n });\n this.updateSubscribeTransformationStats(message.length);\n } catch (error) {\n logger.error(`${this.instanceName} - Error in MQTT message handler: ${error.message}`);\n }\n });\n\n this.mqttClient.on(\"error\", (error) => {\n const errorInfo = formatMqttError(error);\n logger.error(`${this.instanceName} - MQTT client error: ${errorInfo.message}`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n this.event.emit(\"error\", {\n code: typeof errorInfo.code === \"number\" ? errorInfo.code : 0,\n message: errorInfo.message,\n });\n reject(error);\n });\n\n this.mqttClient.on(\"reconnect\", () => {\n logger.debug(`${this.instanceName} - Attempting to reconnect to MQTT broker...`);\n });\n\n this.mqttClient.on(\"close\", () => {\n logger.debug(`${this.instanceName} - MQTT connection closed.`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n });\n\n this.mqttClient.on(\"offline\", () => {\n logger.debug(`${this.instanceName} - MQTT client is offline.`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n });\n\n this.mqttClient.on(\"end\", () => {\n logger.debug(`${this.instanceName} - MQTT client connection ended.`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n });\n\n this.mqttClient.on(\"disconnect\", (packet) => {\n logger.debug(`${this.instanceName} - MQTT client disconnected. Reason: ${packet?.reasonCode}`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n });\n } catch (error) {\n logger.error(`${this.instanceName} - Error starting MQTT proxy: ${formatMqttError(error).message}`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n reject(error);\n }\n });\n }\n\n public async publish(topic: string, message: string | Buffer, options?: mqtt.IClientPublishOptions): Promise<void> {\n this.updatePublishTransformationStats(JSON.stringify(message).length);\n const client = this.mqttClient;\n if (!client) {\n throw new Error(`${this.instanceName} - MQTT client missing; cannot publish to ${topic}`);\n }\n\n if (!client.connected) {\n // Wait briefly for reconnection before giving up.\n await this.waitForReconnect(client, 5000);\n }\n\n if (!client.connected) {\n throw new Error(`${this.instanceName} - MQTT client still disconnected; publish failed for ${topic}`);\n }\n\n return new Promise((resolve, reject) => {\n client.publish(topic, message, options || {}, (err) => {\n if (err) {\n logger.error(`${this.instanceName} - Error publishing to topic ${topic}: ${err.message}`);\n return reject(err);\n }\n logger.debug(`${this.instanceName} - Published message to topic ${topic}`);\n resolve();\n });\n });\n }\n\n /** A bounded delivery attempt for the SDK outbox. Expired attempts retire their socket. */\n public async publishConfirmed(topic: string, message: string, options: mqtt.IClientPublishOptions, timeoutMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout>;\n let timedOut = false;\n try {\n await Promise.race([\n this.publish(topic, message, options),\n new Promise<never>((_, reject) => { timer = setTimeout(() => {\n timedOut = true;\n reject(new Error(\"MQTT broker acknowledgement timed out; delivery outcome unknown\"));\n }, timeoutMs); }),\n ]);\n } finally {\n clearTimeout(timer);\n if (timedOut) {\n // Do not retry alongside mqtt.js's old in-flight operation. A late PUBACK may\n // already have followed delivery: the outbox deliberately permits replay.\n await this.stop({ silent: true, reason: \"retry\", force: true });\n void this.start().catch((): void => {});\n }\n }\n }\n\n public async subscribeAsync(topic: string | string[], options?: mqtt.IClientSubscribeOptions): Promise<mqtt.ISubscriptionGrant[]> {\n return this.mqttClient.subscribeAsync(topic, options);\n }\n\n public async unsubscribeAsync(topic: string | string[]): Promise<mqtt.Packet | undefined> {\n const topics = Array.isArray(topic) ? topic.filter((t) => typeof t === \"string\" && t.length > 0) : [topic].filter((t): t is string => typeof t === \"string\" && t.length > 0);\n if (topics.length === 0) {\n logger.warn(`${this.instanceName} - unsubscribeAsync called with empty topic list; skipping.`);\n return Promise.resolve(undefined);\n }\n return this.mqttClient.unsubscribeAsync(topics);\n }\n\n public stop(options: MqttStopOptions = {}): Promise<void> {\n const silent = options.silent === true || options.reason === \"retry\";\n const shouldLogDisconnect = !silent && this.hasEstablishedConnection;\n\n if (shouldLogDisconnect) {\n logger.debug(`${this.instanceName} - Disconnecting from MQTT broker...`);\n }\n\n return new Promise((resolve, reject) => {\n const resetState = () => {\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n this.pendingReconnectWait = null;\n this.startupSettled = false;\n this.hasEstablishedConnection = false;\n this.startupResolve = null;\n this.startupReject = null;\n };\n\n try {\n if (this.statusUpdateInterval) {\n clearInterval(this.statusUpdateInterval);\n this.statusUpdateInterval = null;\n }\n if (this.transformationStatsInterval) {\n clearInterval(this.transformationStatsInterval);\n this.transformationStatsInterval = null;\n }\n if (this.mqttClient) {\n this.mqttClient.end(options.force ?? false, () => {\n resetState();\n if (shouldLogDisconnect) {\n logger.debug(`${this.instanceName} - Disconnected from MQTT broker.`);\n }\n resolve();\n });\n } else {\n resetState();\n resolve();\n }\n } catch (error) {\n resetState();\n const reason = error instanceof Error ? error : new Error(String(error));\n if (!silent) {\n logger.error(`${this.instanceName} - Error during stop: ${formatMqttError(reason).message}`);\n }\n reject(reason);\n }\n });\n }\n\n private handleMqttConnect(): void {\n const resolve = this.startupResolve;\n const reject = this.startupReject;\n if (!resolve || !reject) {\n return;\n }\n\n try {\n this.mqttClient.stream.setMaxListeners(0);\n const isFirstConnect = !this.startupSettled;\n this.startupSettled = true;\n this.hasEstablishedConnection = true;\n this.isConnected = true;\n this.subscriptionReadiness.connection(true);\n this.emitSubscriptionReadiness();\n\n if (isFirstConnect) {\n logger.info(`${this.instanceName} - Connected to MQTT broker at ${this.mqttHost}`);\n this.subscribeToTopics();\n this.ensureStatusUpdateInterval();\n this.ensureTransformationStatsInterval();\n resolve();\n return;\n }\n\n logger.info(`${this.instanceName} - Reconnected to MQTT broker at ${this.mqttHost}`);\n if (this.mqttParameters.resubscribe === false) {\n this.subscribeToTopics();\n }\n this.ensureStatusUpdateInterval();\n this.ensureTransformationStatsInterval();\n } catch (error) {\n logger.error(`${this.instanceName} - Error in MQTT connect handler: ${formatMqttError(error).message}`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n reject(error);\n }\n }\n\n private emitStatusUpdates() {\n try {\n this.emitSubscriptionReadiness(true);\n const uptime = Math.round((new Date().getTime() - this.startDate.getTime()) / 60000);\n this.event.emit(\"mqttProxyStatus\", { event: \"uptime\", value: uptime, uom: PhysicalMeasurements.Minute, statusTopic: this.statusTopic + \"uptime\" });\n this.event.emit(\"mqttProxyStatus\", { event: \"alive\", value: 1, uom: DataSizeMeasurements.Bit, statusTopic: this.statusTopic + \"alive\" });\n\n if (this.mqttWorker !== undefined) {\n const tpValue = this.mqttWorker.getPublisherState() ? 1 : 0;\n this.event.emit(\"mqttProxyStatus\", { event: \"t-publisher-active\", value: tpValue, uom: DataSizeMeasurements.Bit, statusTopic: this.statusTopic + \"t-publisher-active\" });\n const tsValue = this.mqttWorker.getSubscriberState() ? 1 : 0;\n this.event.emit(\"mqttProxyStatus\", { event: \"t-subscriber-active\", value: tsValue, uom: DataSizeMeasurements.Bit, statusTopic: this.statusTopic + \"t-subscriber-active\" });\n }\n } catch (error) {\n logger.error(`${this.instanceName} - Error publishing MQTT status: ${error.message}`);\n }\n }\n\n private updatePublishTransformationStats(messageSizeOut: number): void {\n this.publishedMessageCount += 1;\n this.publishedMessageBytes += messageSizeOut;\n }\n\n private updateSubscribeTransformationStats(messageSizeIn: number): void {\n this.subscribedMessageCount += 1;\n this.subscribedMessageBytes += messageSizeIn;\n }\n\n private waitForReconnect(client: mqtt.MqttClient, timeoutMs: number): Promise<void> {\n if (client.connected) {\n return Promise.resolve();\n }\n\n if (this.pendingReconnectWait) {\n return this.pendingReconnectWait;\n }\n\n this.pendingReconnectWait = new Promise<void>((resolve) => {\n if (client.connected) return resolve();\n\n const onConnect = () => {\n cleanup();\n resolve();\n };\n const onClose = () => {\n // stay waiting; close is expected during reconnect attempts\n };\n const cleanup = () => {\n client.off(\"connect\", onConnect);\n client.off(\"close\", onClose);\n };\n\n client.on(\"connect\", onConnect);\n client.on(\"close\", onClose);\n\n setTimeout(() => {\n cleanup();\n resolve();\n }, timeoutMs).unref?.();\n }).finally(() => {\n this.pendingReconnectWait = null;\n });\n\n return this.pendingReconnectWait;\n }\n\n private async emitTransformationStatistics(): Promise<void> {\n if (this.statusTopic !== \"\") {\n try {\n this.event.emit(\"mqttProxyStatus\", {\n event: \"published-message-count\",\n value: this.publishedMessageCount,\n uom: \"\",\n statusTopic: this.statusTopic + \"published-message-count\",\n });\n this.event.emit(\"mqttProxyStatus\", {\n event: \"published-message-bytes\",\n value: Math.round(this.publishedMessageBytes / 1024),\n uom: DataSizeMeasurements.KiloByte,\n statusTopic: this.statusTopic + \"published-message-bytes\",\n });\n this.event.emit(\"mqttProxyStatus\", {\n event: \"subscribed-message-count\",\n value: this.subscribedMessageCount,\n uom: \"\",\n statusTopic: this.statusTopic + \"subscribed-message-count\",\n });\n this.event.emit(\"mqttProxyStatus\", {\n event: \"subscribed-message-bytes\",\n value: Math.round(this.subscribedMessageBytes / 1024),\n uom: DataSizeMeasurements.KiloByte,\n statusTopic: this.statusTopic + \"subscribed-message-bytes\",\n });\n this.publishedMessageCount = 0;\n this.publishedMessageBytes = 0;\n this.subscribedMessageCount = 0;\n this.subscribedMessageBytes = 0;\n } catch (error: any) {\n this.publishedMessageCount = 0;\n this.publishedMessageBytes = 0;\n this.subscribedMessageCount = 0;\n this.subscribedMessageBytes = 0;\n logger.error(`${this.instanceName} - Error emitting transformation statistics: ${error.message}`);\n }\n }\n }\n}\n\nexport function formatMqttError(error: unknown): MqttErrorInfo {\n const parts: string[] = [];\n const codes: Array<string | number> = [];\n collectMqttErrorParts(error, parts, codes);\n\n const uniqueParts = Array.from(new Set(parts.map((part) => part.trim()).filter(Boolean)));\n const message = uniqueParts.join(\"; \") || \"Unknown MQTT error\";\n\n return {\n code: codes[0] ?? 0,\n message,\n };\n}\n\nfunction collectMqttErrorParts(\n error: unknown,\n parts: string[],\n codes: Array<string | number>,\n): void {\n if (error instanceof AggregateError) {\n if (typeof error.message === \"string\" && error.message.trim()) {\n parts.push(error.message.trim());\n }\n for (const nested of error.errors) {\n collectMqttErrorParts(nested, parts, codes);\n }\n return;\n }\n\n if (typeof error === \"string\") {\n if (error.trim()) {\n parts.push(error.trim());\n }\n return;\n }\n\n if (!error || typeof error !== \"object\") {\n return;\n }\n\n const record = error as {\n message?: unknown;\n name?: unknown;\n code?: unknown;\n address?: unknown;\n port?: unknown;\n cause?: unknown;\n };\n\n const code =\n typeof record.code === \"string\" || typeof record.code === \"number\"\n ? record.code\n : undefined;\n if (code !== undefined) {\n codes.push(code);\n }\n\n const message =\n typeof record.message === \"string\" && record.message.trim()\n ? record.message.trim()\n : undefined;\n const address =\n typeof record.address === \"string\" && record.address.trim()\n ? record.address.trim()\n : undefined;\n const port = typeof record.port === \"number\" ? record.port : undefined;\n const endpoint =\n address || port !== undefined\n ? `${address ?? \"\"}${address && port !== undefined ? \":\" : \"\"}${port ?? \"\"}`.trim()\n : undefined;\n\n const detailParts = [\n code !== undefined && !message?.includes(String(code)) ? String(code) : undefined,\n message,\n endpoint && !message?.includes(endpoint) ? endpoint : undefined,\n ].filter((part): part is string => typeof part === \"string\" && part.length > 0);\n\n if (detailParts.length > 0) {\n parts.push(detailParts.join(\" \"));\n } else if (typeof record.name === \"string\" && record.name.trim()) {\n parts.push(record.name.trim());\n }\n\n if (record.cause !== undefined) {\n collectMqttErrorParts(record.cause, parts, codes);\n }\n}\n"]}
1
+ {"version":3,"file":"mqtt-proxy.js","sourceRoot":"","sources":["../../src/uns-mqtt/mqtt-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,IAAoC,MAAM,MAAM,CAAC;AACxD,OAAO,MAAM,MAAM,cAAc,CAAC;AAElC,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAG9D,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAaxF,MAAM,CAAC,OAAO,OAAO,SAAS;IACrB,KAAK,GAA+B,IAAI,eAAe,EAAa,CAAC;IACrE,WAAW,CAAS;IACpB,YAAY,CAAS;IACpB,QAAQ,CAAS;IACjB,eAAe,CAAoB;IACnC,OAAO,CAAU;IACjB,UAAU,CAAa;IACvB,SAAS,CAAO;IAChB,cAAc,CAAkB;IAChC,oBAAoB,CAAiC;IACrD,2BAA2B,GAA0B,IAAI,CAAC;IAC1D,qBAAqB,GAAG,CAAC,CAAC;IAC1B,qBAAqB,GAAG,CAAC,CAAC;IAC1B,sBAAsB,GAAG,CAAC,CAAC;IAC3B,sBAAsB,GAAG,CAAC,CAAC;IAC3B,UAAU,CAAa;IACxB,WAAW,GAAG,KAAK,CAAC;IACnB,qBAAqB,GAAG,IAAI,qBAAqB,EAAE,CAAC;IACpD,qBAAqB,GAAmB,IAAI,CAAC;IAC7C,k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M,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,CAAC;QACjE,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IACjC,CAAC;IAED,IAAI,MAAM,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;QAC/B,qBAAqB,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;IACpD,CAAC;AACH,CAAC","sourcesContent":["import { SubscriptionReadiness } from \"./subscription-readiness.js\";\nimport mqtt, { IClientOptions, MqttClient } from \"mqtt\";\nimport logger from \"../logger.js\";\nimport { UnsEvents } from \"../uns/uns-interfaces.js\";\nimport { UnsEventEmitter } from \"../uns/uns-event-emitter.js\";\nimport { IMqttParameters } from \"./mqtt-interfaces.js\";\nimport { MqttWorker } from \"./mqtt-worker.js\";\nimport { DataSizeMeasurements, PhysicalMeasurements } from \"../uns/uns-measurements.js\";\n\nexport type MqttStopOptions = {\n silent?: boolean;\n force?: boolean;\n reason?: \"retry\" | \"shutdown\";\n};\n\ntype MqttErrorInfo = {\n code: string | number;\n message: string;\n};\n\nexport default class MqttProxy {\n public event: UnsEventEmitter<UnsEvents> = new UnsEventEmitter<UnsEvents>();\n public statusTopic: string;\n public instanceName: string;\n private mqttHost: string;\n private mqttSubToTopics: string | string[];\n private mqttSSL: boolean;\n private mqttClient: MqttClient;\n private startDate: Date;\n private mqttParameters: IMqttParameters;\n private statusUpdateInterval: ReturnType<typeof setInterval>;\n private transformationStatsInterval: NodeJS.Timeout | null = null;\n private publishedMessageCount = 0;\n private publishedMessageBytes = 0;\n private subscribedMessageCount = 0;\n private subscribedMessageBytes = 0;\n private mqttWorker: MqttWorker;\n public isConnected = false;\n private subscriptionReadiness = new SubscriptionReadiness();\n private lastSubscriptionReady: boolean | null = null;\n private rejectUnauthorized: boolean;\n private pendingReconnectWait: Promise<void> | null = null;\n private hasEstablishedConnection = false;\n private startupSettled = false;\n private startupResolve: (() => void) | null = null;\n private startupReject: ((error: unknown) => void) | null = null;\n\n constructor(mqttHost: string, instanceName: string, mqttParameters: IMqttParameters, mqttWorker?: MqttWorker) {\n this.mqttSSL = mqttParameters?.mqttSSL ?? false;\n this.rejectUnauthorized = mqttParameters.rejectUnauthorized ?? false;\n this.mqttSubToTopics = mqttParameters?.mqttSubToTopics ?? [];\n this.mqttHost = mqttHost;\n this.startDate = new Date();\n this.instanceName = instanceName ?? \"process\";\n this.statusTopic = `${mqttParameters?.statusTopic}`;\n this.mqttParameters = mqttParameters ?? {};\n this.mqttWorker = mqttWorker;\n }\n\n private resolveProtocol(): IMqttParameters[\"protocol\"] {\n return this.mqttParameters.protocol ?? (this.mqttSSL ? \"mqtts\" : \"mqtt\");\n }\n\n private resolveDefaultPort(protocol: IMqttParameters[\"protocol\"]): number {\n switch (protocol) {\n case \"mqtts\":\n case \"ssl\":\n return 8883;\n case \"wss\":\n return 443;\n case \"ws\":\n return 80;\n case \"tcp\":\n case \"mqtt\":\n default:\n return 1883;\n }\n }\n\n private ensureStatusUpdateInterval(): void {\n if (this.statusTopic && !this.statusUpdateInterval) {\n this.statusUpdateInterval = setInterval(() => this.emitStatusUpdates(), 10000);\n }\n }\n\n private ensureTransformationStatsInterval(): void {\n if (!this.transformationStatsInterval) {\n this.transformationStatsInterval = setInterval(() => {\n this.emitTransformationStatistics();\n }, 60000);\n }\n }\n\n private lastTransportConnected: boolean | undefined;\n private emitSubscriptionReadiness(force = false): void {\n if(force || this.lastTransportConnected!==this.isConnected){\n this.lastTransportConnected=this.isConnected;\n this.event.emit(\"mqttProxyStatus\",{event:\"mqtt-connected\",value:this.isConnected?1:0,uom:DataSizeMeasurements.Bit,statusTopic:this.statusTopic+\"mqtt-connected\"});\n }\n const ready = this.subscriptionReadiness.ready();\n if (!force && ready === this.lastSubscriptionReady) return;\n this.lastSubscriptionReady = ready;\n this.event.emit(\"mqttProxyStatus\", {event: \"mqtt-subscriptions-ready\", value: ready ? 1 : 0,\n uom: DataSizeMeasurements.Bit, statusTopic: this.statusTopic + \"mqtt-subscriptions-ready\"});\n }\n\n private subscribeToTopics(): void {\n if (this.mqttSubToTopics && this.mqttSubToTopics.length > 0) {\n logger.debug(`${this.instanceName} - Subscribed to ${this.mqttSubToTopics.length} topics.`);\n this.mqttClient.subscribe(this.mqttSubToTopics, { qos: 0 });\n }\n }\n\n private buildServers(defaultProtocol: IMqttParameters[\"protocol\"]): IClientOptions[\"servers\"] | undefined {\n const servers: IClientOptions[\"servers\"] = [];\n const { port } = this.mqttParameters;\n const protocol = this.mqttParameters.protocol ?? defaultProtocol;\n\n if (Array.isArray(this.mqttParameters.servers) && this.mqttParameters.servers.length > 0) {\n for (const server of this.mqttParameters.servers) {\n if (!server?.host) continue;\n const resolvedProtocol = server.protocol ?? protocol;\n const resolvedPort =\n typeof server.port === \"number\"\n ? server.port\n : typeof port === \"number\"\n ? port\n : this.resolveDefaultPort(resolvedProtocol);\n const entry: { host: string; port: number; protocol?: IMqttParameters[\"protocol\"] } = {\n host: server.host,\n port: resolvedPort,\n };\n if (resolvedProtocol) {\n entry.protocol = resolvedProtocol;\n }\n servers.push(entry);\n }\n } else if (Array.isArray(this.mqttParameters.hosts) && this.mqttParameters.hosts.length > 0) {\n for (const host of this.mqttParameters.hosts) {\n if (!host) continue;\n const resolvedPort = typeof port === \"number\" ? port : this.resolveDefaultPort(protocol);\n const entry: { host: string; port: number; protocol?: IMqttParameters[\"protocol\"] } = {\n host,\n port: resolvedPort,\n };\n if (protocol) {\n entry.protocol = protocol;\n }\n servers.push(entry);\n }\n }\n\n return servers.length > 0 ? servers : undefined;\n }\n\n public async start(): Promise<void> {\n logger.debug(`${this.instanceName} - Connecting to MQTT broker...`);\n this.startupSettled = false;\n\n return new Promise<void>((resolve, reject) => {\n this.startupResolve = resolve;\n this.startupReject = reject;\n try {\n const username = this.mqttParameters.username;\n const password = this.mqttParameters.password;\n const clientId = this.mqttParameters.clientId ?? this.instanceName;\n const protocol = this.resolveProtocol();\n\n const options: IClientOptions = {\n username,\n password,\n protocolVersion: 5,\n rejectUnauthorized: this.rejectUnauthorized,\n keepalive: this.mqttParameters.keepalive,\n clean: this.mqttParameters.clean ?? true,\n connectTimeout: this.mqttParameters.connectTimeout,\n reconnectPeriod: this.mqttParameters.reconnectPeriod,\n reconnectOnConnackError: this.mqttParameters.reconnectOnConnackError,\n resubscribe: this.mqttParameters.resubscribe,\n queueQoSZero: this.mqttParameters.queueQoSZero,\n properties: this.mqttParameters.properties,\n ca: this.mqttParameters.ca,\n cert: this.mqttParameters.cert,\n key: this.mqttParameters.key,\n servername: this.mqttParameters.servername,\n \n will: {\n topic: `${this.statusTopic}alive`,\n payload: Buffer.from(\"\"),\n qos: 0,\n retain: true,\n properties: { messageExpiryInterval: 3600 },\n },\n clientId,\n };\n\n const servers = this.buildServers(protocol);\n if (servers) {\n options.servers = servers;\n options.protocol = protocol;\n this.mqttClient = mqtt.connect(options);\n } else {\n options.host = this.mqttHost;\n options.port = this.mqttParameters.port;\n options.protocol = protocol;\n this.mqttClient = mqtt.connect(options);\n }\n\n const onConnect = () => this.handleMqttConnect();\n\n this.mqttClient.on(\"connect\", onConnect);\n this.mqttClient.on(\"packetsend\", packet => {\n this.subscriptionReadiness.sent(packet as Parameters<SubscriptionReadiness[\"sent\"]>[0]);\n this.emitSubscriptionReadiness();\n });\n this.mqttClient.on(\"packetreceive\", packet => {\n this.subscriptionReadiness.received(packet as Parameters<SubscriptionReadiness[\"received\"]>[0]);\n this.emitSubscriptionReadiness();\n });\n\n this.mqttClient.on(\"message\", (topic: string, message: Buffer, packet: mqtt.IPublishPacket) => {\n try {\n logger.debug(`${this.instanceName} - Message received on topic ${topic}`);\n this.event.emit(\"input\", {\n message: message.toString(),\n topic: topic,\n packet: packet,\n });\n this.updateSubscribeTransformationStats(message.length);\n } catch (error) {\n logger.error(`${this.instanceName} - Error in MQTT message handler: ${error.message}`);\n }\n });\n\n this.mqttClient.on(\"error\", (error) => {\n const errorInfo = formatMqttError(error);\n logger.error(`${this.instanceName} - MQTT client error: ${errorInfo.message}`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n this.event.emit(\"error\", {\n code: typeof errorInfo.code === \"number\" ? errorInfo.code : 0,\n message: errorInfo.message,\n });\n reject(error);\n });\n\n this.mqttClient.on(\"reconnect\", () => {\n logger.debug(`${this.instanceName} - Attempting to reconnect to MQTT broker...`);\n });\n\n this.mqttClient.on(\"close\", () => {\n logger.debug(`${this.instanceName} - MQTT connection closed.`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n });\n\n this.mqttClient.on(\"offline\", () => {\n logger.debug(`${this.instanceName} - MQTT client is offline.`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n });\n\n this.mqttClient.on(\"end\", () => {\n logger.debug(`${this.instanceName} - MQTT client connection ended.`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n });\n\n this.mqttClient.on(\"disconnect\", (packet) => {\n logger.debug(`${this.instanceName} - MQTT client disconnected. Reason: ${packet?.reasonCode}`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n });\n } catch (error) {\n logger.error(`${this.instanceName} - Error starting MQTT proxy: ${formatMqttError(error).message}`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n reject(error);\n }\n });\n }\n\n public async publish(topic: string, message: string | Buffer, options?: mqtt.IClientPublishOptions): Promise<void> {\n this.updatePublishTransformationStats(JSON.stringify(message).length);\n const client = this.mqttClient;\n if (!client) {\n throw new Error(`${this.instanceName} - MQTT client missing; cannot publish to ${topic}`);\n }\n\n if (!client.connected) {\n // Wait briefly for reconnection before giving up.\n await this.waitForReconnect(client, 5000);\n }\n\n if (!client.connected) {\n throw new Error(`${this.instanceName} - MQTT client still disconnected; publish failed for ${topic}`);\n }\n\n return new Promise((resolve, reject) => {\n client.publish(topic, message, options || {}, (err) => {\n if (err) {\n logger.error(`${this.instanceName} - Error publishing to topic ${topic}: ${err.message}`);\n return reject(err);\n }\n logger.debug(`${this.instanceName} - Published message to topic ${topic}`);\n resolve();\n });\n });\n }\n\n /** A bounded delivery attempt for the SDK outbox. Expired attempts retire their socket. */\n public async publishConfirmed(topic: string, message: string, options: mqtt.IClientPublishOptions, timeoutMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout>;\n let timedOut = false;\n try {\n await Promise.race([\n this.publish(topic, message, options),\n new Promise<never>((_, reject) => { timer = setTimeout(() => {\n timedOut = true;\n reject(new Error(\"MQTT broker acknowledgement timed out; delivery outcome unknown\"));\n }, timeoutMs); }),\n ]);\n } finally {\n clearTimeout(timer);\n if (timedOut) {\n // Do not retry alongside mqtt.js's old in-flight operation. A late PUBACK may\n // already have followed delivery: the outbox deliberately permits replay.\n await this.stop({ silent: true, reason: \"retry\", force: true });\n void this.start().catch((): void => {});\n }\n }\n }\n\n public async subscribeAsync(topic: string | string[], options?: mqtt.IClientSubscribeOptions): Promise<mqtt.ISubscriptionGrant[]> {\n return this.mqttClient.subscribeAsync(topic, options);\n }\n\n public async unsubscribeAsync(topic: string | string[]): Promise<mqtt.Packet | undefined> {\n const topics = Array.isArray(topic) ? topic.filter((t) => typeof t === \"string\" && t.length > 0) : [topic].filter((t): t is string => typeof t === \"string\" && t.length > 0);\n if (topics.length === 0) {\n logger.warn(`${this.instanceName} - unsubscribeAsync called with empty topic list; skipping.`);\n return Promise.resolve(undefined);\n }\n return this.mqttClient.unsubscribeAsync(topics);\n }\n\n public stop(options: MqttStopOptions = {}): Promise<void> {\n const silent = options.silent === true || options.reason === \"retry\";\n const shouldLogDisconnect = !silent && this.hasEstablishedConnection;\n\n if (shouldLogDisconnect) {\n logger.debug(`${this.instanceName} - Disconnecting from MQTT broker...`);\n }\n\n return new Promise((resolve, reject) => {\n const resetState = () => {\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n this.pendingReconnectWait = null;\n this.startupSettled = false;\n this.hasEstablishedConnection = false;\n this.startupResolve = null;\n this.startupReject = null;\n };\n\n try {\n if (this.statusUpdateInterval) {\n clearInterval(this.statusUpdateInterval);\n this.statusUpdateInterval = null;\n }\n if (this.transformationStatsInterval) {\n clearInterval(this.transformationStatsInterval);\n this.transformationStatsInterval = null;\n }\n if (this.mqttClient) {\n this.mqttClient.end(options.force ?? false, () => {\n resetState();\n if (shouldLogDisconnect) {\n logger.debug(`${this.instanceName} - Disconnected from MQTT broker.`);\n }\n resolve();\n });\n } else {\n resetState();\n resolve();\n }\n } catch (error) {\n resetState();\n const reason = error instanceof Error ? error : new Error(String(error));\n if (!silent) {\n logger.error(`${this.instanceName} - Error during stop: ${formatMqttError(reason).message}`);\n }\n reject(reason);\n }\n });\n }\n\n private handleMqttConnect(): void {\n const resolve = this.startupResolve;\n const reject = this.startupReject;\n if (!resolve || !reject) {\n return;\n }\n\n try {\n this.mqttClient.stream.setMaxListeners(0);\n const isFirstConnect = !this.startupSettled;\n this.startupSettled = true;\n this.hasEstablishedConnection = true;\n this.isConnected = true;\n this.subscriptionReadiness.connection(true);\n this.emitSubscriptionReadiness();\n\n if (isFirstConnect) {\n logger.info(`${this.instanceName} - Connected to MQTT broker at ${this.mqttHost}`);\n this.subscribeToTopics();\n this.ensureStatusUpdateInterval();\n this.ensureTransformationStatsInterval();\n resolve();\n return;\n }\n\n logger.info(`${this.instanceName} - Reconnected to MQTT broker at ${this.mqttHost}`);\n if (this.mqttParameters.resubscribe === false) {\n this.subscribeToTopics();\n }\n this.ensureStatusUpdateInterval();\n this.ensureTransformationStatsInterval();\n } catch (error) {\n logger.error(`${this.instanceName} - Error in MQTT connect handler: ${formatMqttError(error).message}`);\n this.isConnected = false;\n this.subscriptionReadiness.connection(false);\n this.emitSubscriptionReadiness();\n reject(error);\n }\n }\n\n private emitStatusUpdates() {\n try {\n this.emitSubscriptionReadiness(true);\n const uptime = Math.round((new Date().getTime() - this.startDate.getTime()) / 60000);\n this.event.emit(\"mqttProxyStatus\", { event: \"uptime\", value: uptime, uom: PhysicalMeasurements.Minute, statusTopic: this.statusTopic + \"uptime\" });\n this.event.emit(\"mqttProxyStatus\", { event: \"alive\", value: 1, uom: DataSizeMeasurements.Bit, statusTopic: this.statusTopic + \"alive\" });\n\n if (this.mqttWorker !== undefined) {\n const tpValue = this.mqttWorker.getPublisherState() ? 1 : 0;\n this.event.emit(\"mqttProxyStatus\", { event: \"t-publisher-active\", value: tpValue, uom: DataSizeMeasurements.Bit, statusTopic: this.statusTopic + \"t-publisher-active\" });\n const tsValue = this.mqttWorker.getSubscriberState() ? 1 : 0;\n this.event.emit(\"mqttProxyStatus\", { event: \"t-subscriber-active\", value: tsValue, uom: DataSizeMeasurements.Bit, statusTopic: this.statusTopic + \"t-subscriber-active\" });\n }\n } catch (error) {\n logger.error(`${this.instanceName} - Error publishing MQTT status: ${error.message}`);\n }\n }\n\n private updatePublishTransformationStats(messageSizeOut: number): void {\n this.publishedMessageCount += 1;\n this.publishedMessageBytes += messageSizeOut;\n }\n\n private updateSubscribeTransformationStats(messageSizeIn: number): void {\n this.subscribedMessageCount += 1;\n this.subscribedMessageBytes += messageSizeIn;\n }\n\n private waitForReconnect(client: mqtt.MqttClient, timeoutMs: number): Promise<void> {\n if (client.connected) {\n return Promise.resolve();\n }\n\n if (this.pendingReconnectWait) {\n return this.pendingReconnectWait;\n }\n\n this.pendingReconnectWait = new Promise<void>((resolve) => {\n if (client.connected) return resolve();\n\n const onConnect = () => {\n cleanup();\n resolve();\n };\n const onClose = () => {\n // stay waiting; close is expected during reconnect attempts\n };\n const cleanup = () => {\n client.off(\"connect\", onConnect);\n client.off(\"close\", onClose);\n };\n\n client.on(\"connect\", onConnect);\n client.on(\"close\", onClose);\n\n setTimeout(() => {\n cleanup();\n resolve();\n }, timeoutMs).unref?.();\n }).finally(() => {\n this.pendingReconnectWait = null;\n });\n\n return this.pendingReconnectWait;\n }\n\n private async emitTransformationStatistics(): Promise<void> {\n if (this.statusTopic !== \"\") {\n try {\n this.event.emit(\"mqttProxyStatus\", {\n event: \"published-message-count\",\n value: this.publishedMessageCount,\n uom: \"\",\n statusTopic: this.statusTopic + \"published-message-count\",\n });\n this.event.emit(\"mqttProxyStatus\", {\n event: \"published-message-bytes\",\n value: Math.round(this.publishedMessageBytes / 1024),\n uom: DataSizeMeasurements.KiloByte,\n statusTopic: this.statusTopic + \"published-message-bytes\",\n });\n this.event.emit(\"mqttProxyStatus\", {\n event: \"subscribed-message-count\",\n value: this.subscribedMessageCount,\n uom: \"\",\n statusTopic: this.statusTopic + \"subscribed-message-count\",\n });\n this.event.emit(\"mqttProxyStatus\", {\n event: \"subscribed-message-bytes\",\n value: Math.round(this.subscribedMessageBytes / 1024),\n uom: DataSizeMeasurements.KiloByte,\n statusTopic: this.statusTopic + \"subscribed-message-bytes\",\n });\n this.publishedMessageCount = 0;\n this.publishedMessageBytes = 0;\n this.subscribedMessageCount = 0;\n this.subscribedMessageBytes = 0;\n } catch (error: any) {\n this.publishedMessageCount = 0;\n this.publishedMessageBytes = 0;\n this.subscribedMessageCount = 0;\n this.subscribedMessageBytes = 0;\n logger.error(`${this.instanceName} - Error emitting transformation statistics: ${error.message}`);\n }\n }\n }\n}\n\nexport function formatMqttError(error: unknown): MqttErrorInfo {\n const parts: string[] = [];\n const codes: Array<string | number> = [];\n collectMqttErrorParts(error, parts, codes);\n\n const uniqueParts = Array.from(new Set(parts.map((part) => part.trim()).filter(Boolean)));\n const message = uniqueParts.join(\"; \") || \"Unknown MQTT error\";\n\n return {\n code: codes[0] ?? 0,\n message,\n };\n}\n\nfunction collectMqttErrorParts(\n error: unknown,\n parts: string[],\n codes: Array<string | number>,\n): void {\n if (error instanceof AggregateError) {\n if (typeof error.message === \"string\" && error.message.trim()) {\n parts.push(error.message.trim());\n }\n for (const nested of error.errors) {\n collectMqttErrorParts(nested, parts, codes);\n }\n return;\n }\n\n if (typeof error === \"string\") {\n if (error.trim()) {\n parts.push(error.trim());\n }\n return;\n }\n\n if (!error || typeof error !== \"object\") {\n return;\n }\n\n const record = error as {\n message?: unknown;\n name?: unknown;\n code?: unknown;\n address?: unknown;\n port?: unknown;\n cause?: unknown;\n };\n\n const code =\n typeof record.code === \"string\" || typeof record.code === \"number\"\n ? record.code\n : undefined;\n if (code !== undefined) {\n codes.push(code);\n }\n\n const message =\n typeof record.message === \"string\" && record.message.trim()\n ? record.message.trim()\n : undefined;\n const address =\n typeof record.address === \"string\" && record.address.trim()\n ? record.address.trim()\n : undefined;\n const port = typeof record.port === \"number\" ? record.port : undefined;\n const endpoint =\n address || port !== undefined\n ? `${address ?? \"\"}${address && port !== undefined ? \":\" : \"\"}${port ?? \"\"}`.trim()\n : undefined;\n\n const detailParts = [\n code !== undefined && !message?.includes(String(code)) ? String(code) : undefined,\n message,\n endpoint && !message?.includes(endpoint) ? endpoint : undefined,\n ].filter((part): part is string => typeof part === \"string\" && part.length > 0);\n\n if (detailParts.length > 0) {\n parts.push(detailParts.join(\" \"));\n } else if (typeof record.name === \"string\" && record.name.trim()) {\n parts.push(record.name.trim());\n }\n\n if (record.cause !== undefined) {\n collectMqttErrorParts(record.cause, parts, codes);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"mqtt-worker.d.ts","sourceRoot":"","sources":["../../src/uns-mqtt/mqtt-worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAOtD,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEvD,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAE/E,qBAAa,UAAU;IACrB,OAAO,CAAC,SAAS,CAAY;IAC7B,SAAS,CAAC,SAAS,EAAE,kBAAkB,GAAG,gBAAgB,CAAC;IAC3D,SAAS,CAAC,UAAU,EAAE,mBAAmB,CAAC;IAC1C,OAAO,CAAC,qBAAqB,CAAC,CAAwB;gBAE1C,UAAU,EAAE,eAAe;IAyFvC;;OAEG;IACH,OAAO,CAAC,yBAAyB;IA6EjC;;OAEG;IACI,iBAAiB,IAAI,OAAO;IAGnC;;OAEG;IACI,kBAAkB,IAAI,OAAO;CAIrC"}
1
+ {"version":3,"file":"mqtt-worker.d.ts","sourceRoot":"","sources":["../../src/uns-mqtt/mqtt-worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAOtD,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEvD,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAE/E,qBAAa,UAAU;IACrB,OAAO,CAAC,SAAS,CAAY;IAC7B,SAAS,CAAC,SAAS,EAAE,kBAAkB,GAAG,gBAAgB,CAAC;IAC3D,SAAS,CAAC,UAAU,EAAE,mBAAmB,CAAC;IAC1C,OAAO,CAAC,qBAAqB,CAAC,CAAwB;gBAE1C,UAAU,EAAE,eAAe;IAyFvC;;OAEG;IACH,OAAO,CAAC,yBAAyB;IAqFjC;;OAEG;IACI,iBAAiB,IAAI,OAAO;IAGnC;;OAEG;IACI,kBAAkB,IAAI,OAAO;CAIrC"}
@@ -142,6 +142,18 @@ export class MqttWorker {
142
142
  else if (msg && msg.command === "unsubscribeAsync" && msg.topics) {
143
143
  this.mqttProxy.unsubscribeAsync(msg.topics);
144
144
  }
145
+ else if (msg?.command === "prepareSubscriberResume" || msg?.command === "activatePreparedSubscriber") {
146
+ try {
147
+ if (msg.command === "prepareSubscriberResume")
148
+ this.subscriber.prepareResume(msg.cursor);
149
+ else
150
+ this.subscriber.activatePreparedResume();
151
+ parentPort?.postMessage({ command: "publishQueueReply", id: msg.id, status: "success" });
152
+ }
153
+ catch {
154
+ parentPort?.postMessage({ command: "publishQueueReply", id: msg.id, status: "error", error: "MQTT subscriber resume not proven" });
155
+ }
156
+ }
145
157
  else if (msg && msg.command === "setPublisherActive") {
146
158
  try {
147
159
  this.publisher.becomeActive({ batchSize: msg?.batchSize, referenceHash: msg?.referenceHash });
@@ -161,7 +173,7 @@ export class MqttWorker {
161
173
  this.subscriber.becomeActive({ batchSize: msg?.batchSize, referenceHash: msg?.referenceHash });
162
174
  }
163
175
  else if (msg && msg.command === "setSubscriberPassive") {
164
- const snapshot = await this.subscriber.becomePassive(3);
176
+ const snapshot = await this.subscriber.becomePassive(3, msg.strict === true);
165
177
  parentPort?.postMessage({
166
178
  command: "handover_subscriber",
167
179
  ...snapshot