@uns-kit/core 3.0.10 → 3.0.13

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.
package/MIGRATIONS.md CHANGED
@@ -9,6 +9,84 @@ Agents must inspect the application's existing ownership and shutdown flow
9
9
  before editing it. The examples below describe the intended behavior, not a
10
10
  mechanical search-and-replace operation.
11
11
 
12
+ ## 3.0.13 - Optional controller-correlated handovers
13
+
14
+ `UnsProxyProcess` accepts an optional `handoverId` parameter or
15
+ `UNS_HANDOVER_ID` environment variable. When supplied, it adds that opaque id
16
+ to handover MQTT payloads and MQTT 5 user properties. A new target includes
17
+ the id in its final `handover_ack`, even when its source still runs an older
18
+ uns-kit that does not echo the id.
19
+
20
+ Existing applications need no configuration or source change: without this
21
+ value their MQTT messages remain byte-for-byte compatible with the legacy
22
+ handover protocol. To opt an RTT target into controller-coordinated hot
23
+ migration, set `uns.handoverProtocol: "correlated-v1"` alongside
24
+ `uns.instanceMode: "handover"` and `uns.handover: true`. A controller should
25
+ inject the value only for a durable, operator-initiated migration and must
26
+ still accept an acknowledgement without the id from a legacy target. The value
27
+ is correlation metadata, not a secret; do not use it as an authorization or
28
+ fencing token.
29
+
30
+ ## 3.0.12 - Expiring retained handover heartbeats
31
+
32
+ `UnsProxyProcess` now publishes its `active` heartbeat as an MQTT 5 retained
33
+ message with a 30-second expiry, refreshed every 10 seconds. A newly started
34
+ process can therefore see a live predecessor immediately rather than racing a
35
+ single non-retained heartbeat. On normal `UnsProxyProcess.shutdown()`, it
36
+ publishes short-lived `active=0` before disconnecting.
37
+
38
+ The handover manager treats a retained `active=1` as a possibly stale snapshot
39
+ and waits for a fresh heartbeat before requesting a handover. If the retained
40
+ process has crashed, no fresh heartbeat arrives, so the new process activates
41
+ after its normal active timeout; the stale retained message expires shortly
42
+ afterwards. Keep the `uns.instanceMode: "handover"` and
43
+ `uns.handover: true` settings on both sides of a handover.
44
+
45
+ Applications that stop an individual process-owned `UnsMqttProxy` rather than
46
+ calling `UnsProxyProcess.shutdown()` still rely on the 30-second expiry. Migrate
47
+ those applications to the process-level shutdown API when practical.
48
+
49
+ ## 3.0.11 - OpenHub runtime profiles and add-on compatibility
50
+
51
+ Apply this migration when upgrading from `@uns-kit/cli` or `@uns-kit/core`
52
+ `<3.0.11` to `>=3.0.11` for an application that is deployed by an OpenHub 2.x
53
+ controller.
54
+
55
+ New TypeScript and Python projects now use `controllerCompatibility: ">=2 <3"`
56
+ and receive three credential-free profiles:
57
+
58
+ - `config-development-host.json` for a directly started host process;
59
+ - `config-development-podman.json` for a process deployed through a local
60
+ Podman controller; and
61
+ - `config-production.json` for a production controller instance.
62
+
63
+ Keep only the selected copy as the untracked `config.json`. Do not commit a
64
+ token, user email/password, MQTT password, or customer endpoint in any tracked
65
+ profile. Direct host development uses `UNS_SERVICE_TOKEN` and the local
66
+ controller identity in `.env`; controller-managed instances receive
67
+ `UNS_SERVICE_TOKEN_FILE` and `UNS_CONTROLLER_*` from PM2. Use
68
+ `ServiceTokenProvider` for any controller or controller-proxied API call so a
69
+ mounted token rotation is used without restarting the service.
70
+
71
+ Existing applications remain valid, but their old `>=7.1 <8` manifests are not
72
+ deployable by an OpenHub 2.x controller. Update that range only when the
73
+ application is compatible with the 2.x runtime API, regenerate its
74
+ configuration schema, and validate each selected profile before release.
75
+
76
+ ## 3.0.10 - Managed RTT service registration
77
+
78
+ Apply this migration when upgrading from `@uns-kit/core` `<3.0.10` to
79
+ `>=3.0.10` for an RTT service that must prove it started under the controller
80
+ that manages its instance.
81
+
82
+ After the service has successfully started its MQTT/API runtime, construct an
83
+ `UnsClient` with `ServiceTokenProvider` and call `registerService`. Use the
84
+ controller-injected `RTT_NODE` and `RTT_INSTANCE_ID` only through that helper;
85
+ the helper verifies the descriptor id and sends no credentials. A directly
86
+ started development process has neither variable, so `registerService` is a
87
+ deliberate no-op. Do not synthesize those variables or create an identity in
88
+ application configuration.
89
+
12
90
  ## 3.0.9 - MQTT channel inheritance
13
91
 
14
92
  Apply this migration when upgrading from `@uns-kit/core` `<3.0.9` to
@@ -1,8 +1,8 @@
1
- import { UnsEvents } from "./uns-interfaces.js";
2
- import { HandoverManagerEventEmitter } from "./handover-manager-event-emitter.js";
3
1
  import { HandoverManagerEvents } from "../uns-mqtt/mqtt-interfaces.js";
4
2
  import MqttProxy from "../uns-mqtt/mqtt-proxy.js";
5
3
  import UnsMqttProxy from "../uns-mqtt/uns-mqtt-proxy.js";
4
+ import { HandoverManagerEventEmitter } from "./handover-manager-event-emitter.js";
5
+ import { UnsEvents } from "./uns-interfaces.js";
6
6
  /**
7
7
  * HandoverManager is responsible for all handover-related logic,
8
8
  * including handling incoming MQTT messages, issuing handover requests,
@@ -1 +1 @@
1
- {"version":3,"file":"handover-manager.d.ts","sourceRoot":"","sources":["../../src/uns/handover-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAEhD,OAAO,EAAE,2BAA2B,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,SAAS,MAAM,2BAA2B,CAAC;AAGlD,OAAO,YAAY,MAAM,+BAA+B,CAAC;AAEzD;;;;GAIG;AACH,qBAAa,eAAe;IACnB,KAAK,EAAE,2BAA2B,CAAC,qBAAqB,CAAC,CAA4D;IAC5H,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,SAAS,CAAY;IAC7B,OAAO,CAAC,cAAc,CAAiB;IACvC,OAAO,CAAC,kBAAkB,CAAkB;IAC5C,OAAO,CAAC,kBAAkB,CAAkB;IAC5C,OAAO,CAAC,YAAY,CAAmB;IACvC,OAAO,CAAC,aAAa,CAA6B;IAClD,OAAO,CAAC,MAAM,CAAkB;IACzB,sBAAsB,EAAE,OAAO,CAAS;IACxC,eAAe,EAAE,OAAO,CAAQ;IAChC,iBAAiB,EAAE,OAAO,C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,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,SAAS,EACpB,cAAc,EAAE,YAAY,EAAE,EAC9B,sBAAsB,EAAE,OAAO,EAC/B,eAAe,EAAE,OAAO,EACxB,iBAAiB,EAAE,OAAO;IA8B5B,OAAO,CAAC,iBAAiB;IAOzB,OAAO,CAAC,kBAAkB;IAI1B,OAAO,CAAC,gBAAgB;IAgBxB,OAAO,CAAC,oBAAoB;IAU5B;;;OAGG;IACU,iBAAiB,CAAC,KAAK,EAAE,SAAS,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAoFxE;;OAEG;YACW,cAAc;CAiI7B"}
@@ -1,6 +1,6 @@
1
1
  import logger from "../logger.js";
2
- import { HandoverManagerEventEmitter } from "./handover-manager-event-emitter.js";
3
2
  import { MqttTopicBuilder } from "../uns-mqtt/mqtt-topic-builder.js";
3
+ import { HandoverManagerEventEmitter } from "./handover-manager-event-emitter.js";
4
4
  import { ACTIVE_TIMEOUT, PACKAGE_INFO } from "./process-config.js";
5
5
  /**
6
6
  * HandoverManager is responsible for all handover-related logic,
@@ -88,10 +88,7 @@ export class HandoverManager {
88
88
  async handleMqttMessage(event) {
89
89
  try {
90
90
  // Check if the packet is active messages from other processes and this process is not active.
91
- if (this.isProcessActiveTopic(event.topic) &&
92
- this.requestingHandover === false &&
93
- this.active === false &&
94
- this.handoverInProgress === false) {
91
+ if (this.isProcessActiveTopic(event.topic) && this.requestingHandover === false && this.active === false && this.handoverInProgress === false) {
95
92
  const sourceProcessId = this.getSourceProcessId(event);
96
93
  if (sourceProcessId === this.processId) {
97
94
  return;
@@ -102,6 +99,14 @@ export class HandoverManager {
102
99
  }
103
100
  const sourceInfo = sourceProcessId ? ` (processId=${sourceProcessId})` : "";
104
101
  logger.info(`${this.processName} - Another process is active${sourceInfo} on ${event.topic}.`);
102
+ if (event.packet?.retain === true) {
103
+ // A retained heartbeat can belong to a process that crashed before its
104
+ // expiry. Wait for a fresh non-retained heartbeat before asking it to
105
+ // hand over; otherwise a stale retained message would block startup.
106
+ logger.info(`${this.processName} - Retained active heartbeat observed; waiting for a fresh heartbeat.`);
107
+ this.activeTimeout?.refresh();
108
+ return;
109
+ }
105
110
  if (this.handoverRequestEnabled && this.handoverEnabled) {
106
111
  // Requester process
107
112
  // Publish a handover request message after 10 seconds to the handover topic.
@@ -1 +1 @@
1
- {"version":3,"file":"handover-manager.js","sourceRoot":"","sources":["../../src/uns/handover-manager.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,2BAA2B,EAAE,MAAM,qCAAqC,CAAC;AAGlF,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGnE;;;;GAIG;AACH,MAAM,OAAO,eAAe;IACnB,KAAK,GAAuD,IAAI,2BAA2B,EAAyB,CAAC;IACpH,WAAW,CAAS;IACpB,SAAS,CAAS;IAClB,SAAS,CAAY;IACrB,cAAc,CAAiB;IAC/B,kBAAkB,GAAY,KAAK,CAAC;IACpC,kBAAkB,GAAY,KAAK,CAAC;IACpC,YAAY,CAAmB;IAC/B,aAAa,CAA6B;IAC1C,MAAM,GAAY,KAAK,CAAC;IACzB,sBAAsB,GAAY,KAAK,CAAC;IACxC,eAAe,GAAY,IAAI,CAAC;IAChC,iBAAiB,GAAY,KAAK,CAAC;IAE1C,YAAY,WAAmB,EAAE,SAAiB,EAAE,SAAoB,EAAE,cAA8B,EAAE,sBAA+B,EAAE,eAAwB,EAAE,iBAA0B;QAC7L,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QACrC,IAAI,CAAC,sBAAsB,GAAG,sBA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AAC,iBAAiB,EAAE;qBACzC;iBACF,CACF,CAAC;gBACF,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,WAAW,+BAA+B,CAAC,CAAC;YAClE,CAAC;YAED,oBAAoB;YACpB,6EAA6E;YAC7E,IAAI,QAAQ,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;gBACrC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,WAAW,iCAAiC,KAAK,CAAC,MAAM,EAAE,UAAU,EAAE,cAAc,EAAE,WAAW,GAAG,CAAC,CAAC;gBAC1H,IAAI,CAAC,kBAAkB,GAAG,KAAK,CAAC;gBAChC,IAAI,CAAC,kBAAkB,GAAG,KAAK,CAAC;gBAEhC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,WAAW,yCAAyC,CAAC,CAAC;gBAC1E,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,WAAW,0CAA0C,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QAC7F,CAAC;IACH,CAAC;CACF","sourcesContent":["import { UnsEvents } from \"./uns-interfaces.js\";\nimport logger from \"../logger.js\";\nimport { HandoverManagerEventEmitter } from \"./handover-manager-event-emitter.js\";\nimport { HandoverManagerEvents } from \"../uns-mqtt/mqtt-interfaces.js\";\nimport MqttProxy from \"../uns-mqtt/mqtt-proxy.js\";\nimport { MqttTopicBuilder } from \"../uns-mqtt/mqtt-topic-builder.js\";\nimport { ACTIVE_TIMEOUT, PACKAGE_INFO } from \"./process-config.js\";\nimport UnsMqttProxy from \"../uns-mqtt/uns-mqtt-proxy.js\";\n\n/**\n * HandoverManager is responsible for all handover-related logic,\n * including handling incoming MQTT messages, issuing handover requests,\n * and processing handover responses.\n */\nexport class HandoverManager {\n public event: HandoverManagerEventEmitter<HandoverManagerEvents> = new HandoverManagerEventEmitter<HandoverManagerEvents>();\n private processName: string;\n private processId: string;\n private mqttProxy: MqttProxy;\n private unsMqttProxies: UnsMqttProxy[];\n private requestingHandover: boolean = false;\n private handoverInProgress: boolean = false;\n private topicBuilder: MqttTopicBuilder;\n private activeTimeout: NodeJS.Timeout | undefined;\n private active: boolean = false;\n public handoverRequestEnabled: boolean = false;\n public handoverEnabled: boolean = true;\n public forceStartEnabled: boolean = false;\n\n constructor(processName: string, processId: string, mqttProxy: MqttProxy, unsMqttProxies: UnsMqttProxy[], handoverRequestEnabled: boolean, handoverEnabled: boolean, forceStartEnabled: boolean) {\n this.processName = processName;\n this.processId = processId;\n this.mqttProxy = mqttProxy;\n this.unsMqttProxies = unsMqttProxies;\n this.handoverRequestEnabled = handoverRequestEnabled;\n this.handoverEnabled = handoverEnabled;\n this.forceStartEnabled = forceStartEnabled;\n\n // Instantiate the topic builder.\n const packageName = PACKAGE_INFO.name;\n const version = PACKAGE_INFO.version;\n this.topicBuilder = new MqttTopicBuilder(`uns-infra/${MqttTopicBuilder.sanitizeTopicPart(packageName)}/${MqttTopicBuilder.sanitizeTopicPart(version)}/${MqttTopicBuilder.sanitizeTopicPart(this.processName)}/`);\n\n // Set status as active after a timeout if no other active process are detected.\n this.activeTimeout = setTimeout(() => {\n logger.info(`${this.processName} - No active message received within timeout. Assuming no other process is running.`);\n this.active = true;\n this.event.emit(\"handoverManager\", { active: this.active });\n // Activate all UNS proxy instance publishers and subscribers.\n this.unsMqttProxies.forEach((unsProxy) => {\n unsProxy.setPublisherActive();\n unsProxy.setSubscriberActive();\n });\n }, ACTIVE_TIMEOUT);\n }\n\n private getUserProperties(): Record<string, string> {\n return {\n processName: this.processName,\n processId: this.processId,\n };\n }\n\n private getSourceProcessId(event: UnsEvents[\"input\"]): string | undefined {\n return event.packet?.properties?.userProperties?.processId;\n }\n\n private parseActiveValue(message: string): boolean | null {\n try {\n const parsed = JSON.parse(message);\n const value = parsed?.message?.data?.value ?? parsed?.data?.value;\n if (value === 1 || value === \"1\" || value === true || value === \"true\") {\n return true;\n }\n if (value === 0 || value === \"0\" || value === false || value === \"false\") {\n return false;\n }\n return null;\n } catch {\n return null;\n }\n }\n\n private isProcessActiveTopic(topic: string): boolean {\n const parts = topic.split(\"/\");\n if (parts.length !== 5) return false;\n const [root, pkg, , process, tail] = parts;\n if (root !== \"uns-infra\" || tail !== \"active\") return false;\n const expectedPackage = MqttTopicBuilder.sanitizeTopicPart(PACKAGE_INFO.name);\n const expectedProcess = MqttTopicBuilder.sanitizeTopicPart(this.processName);\n return pkg === expectedPackage && process === expectedProcess;\n }\n\n /**\n * Main entry point for handling incoming MQTT messages.\n * It checks the topic and delegates to the corresponding handler.\n */\n public async handleMqttMessage(event: UnsEvents[\"input\"]): Promise<void> {\n try {\n // Check if the packet is active messages from other processes and this process is not active.\n if (\n this.isProcessActiveTopic(event.topic) &&\n this.requestingHandover === false &&\n this.active === false &&\n this.handoverInProgress === false\n ) {\n const sourceProcessId = this.getSourceProcessId(event);\n if (sourceProcessId === this.processId) {\n return;\n }\n const activeValue = this.parseActiveValue(event.message.toString());\n if (activeValue !== true) {\n return;\n }\n const sourceInfo = sourceProcessId ? ` (processId=${sourceProcessId})` : \"\";\n logger.info(`${this.processName} - Another process is active${sourceInfo} on ${event.topic}.`);\n\n if (this.handoverRequestEnabled && this.handoverEnabled) {\n // Requester process\n // Publish a handover request message after 10 seconds to the handover topic.\n clearTimeout(this.activeTimeout); // Clear the active timeout if it exists - prevent this process from becoming active after a timeout.\n this.activeTimeout = undefined;\n this.event.emit(\"handoverManager\", { active: this.active });\n this.requestingHandover = true;\n const eventHandoverTopic = new MqttTopicBuilder(MqttTopicBuilder.extractBaseTopic(event.topic)).getHandoverTopic();\n await this.mqttProxy.publish(eventHandoverTopic, JSON.stringify({ type: \"handover_intent\" }), {\n retain: false,\n properties: {\n userProperties: this.getUserProperties(),\n },\n });\n logger.info(`${this.processName} - Requesting handover in 10 seconds.`);\n setTimeout(async () => {\n logger.info(`${this.processName} - Requesting handover ${eventHandoverTopic}.`);\n this.handoverInProgress = true;\n await this.mqttProxy.publish(eventHandoverTopic, JSON.stringify({ type: \"handover_request\" }), {\n retain: false,\n properties: {\n responseTopic: this.topicBuilder.getHandoverTopic(),\n userProperties: this.getUserProperties(),\n },\n });\n }, 10000);\n } else {\n if (this.forceStartEnabled) {\n // Force start the process even if another process is active.\n logger.info(`${this.processName} - Force starting the process.`);\n logger.warn(`${this.processName} - Warning: Source and destination being the same may lead to duplicate messages.`);\n clearTimeout(this.activeTimeout); // Clear the active timeout if it exists - prevent this process from becoming active after a timeout.\n this.activeTimeout = undefined;\n this.active = true;\n this.event.emit(\"handoverManager\", { active: this.active });\n // Activate all UNS proxy instance publishers and subscribers.\n this.unsMqttProxies.forEach((unsProxy) => {\n unsProxy.setPublisherActive();\n unsProxy.setSubscriberActive();\n }\n );\n }\n else {\n logger.info(`${this.processName} - Waiting for the other process on topic ${event.topic} to become passive.`);\n this.activeTimeout?.refresh();\n }\n }\n }\n\n // Check if the packet is an handover message, sent to a handover topic.\n if (event.topic === this.topicBuilder.getHandoverTopic() && this.handoverEnabled) {\n const sourceProcessId = this.getSourceProcessId(event);\n if (sourceProcessId !== this.processId) {\n await this.handleHandover(event);\n }\n }\n } catch (error) {\n logger.error(`${this.processName} - Error processing MQTT message: ${error.message}`);\n return;\n }\n }\n\n /**\n * Handles handovers.\n */\n private async handleHandover(event: UnsEvents[\"input\"]): Promise<void> {\n try {\n const response = JSON.parse(event.message.toString());\n // Responder process\n // Check if the message is a handover request and publish MULTIPLE handover_subscriber messages\n if (response.type === \"handover_request\") {\n logger.info(\n `${this.processName} - Received handover request from ${event.packet?.properties?.userProperties?.processName}. Accepting handover.`,\n );\n\n // Set all UNS proxy instance subscribers to passive and drain the queue.\n const mqttWorkerData: UnsEvents[\"mqttWorker\"][] = [];\n for (let i = 0; i < this.unsMqttProxies.length; i++) {\n const unsProxy = this.unsMqttProxies[i];\n const workerData = await unsProxy.setSubscriberPassiveAndDrainQueue();\n mqttWorkerData.push(workerData);\n }\n logger.info(`${this.processName} - Handover request accepted. Sending handover_subscriber messages.`);\n\n // Publish handover_subscriber messages for each instance that has processed some data.\n for (let i = 0; i < mqttWorkerData.length; i++) {\n const workerData = mqttWorkerData[i];\n if (workerData.batchSize > 0) {\n await this.mqttProxy.publish(\n event.packet.properties?.responseTopic ?? \"\",\n JSON.stringify({\n type: \"handover_subscriber\",\n batchSize: workerData.batchSize,\n referenceHash: workerData.referenceHash,\n instanceName: workerData.instanceName,\n }),\n {\n retain: false,\n properties: {\n responseTopic: this.topicBuilder.getHandoverTopic(),\n userProperties: this.getUserProperties(),\n },\n },\n );\n }\n }\n logger.info(`${this.processName} - Handover subscriber messages sent.`);\n\n // Publish a single handover acknowledgment only when all\n // handover_subscriber messages have been sent\n this.active = false;\n this.event.emit(\"handoverManager\", { active: this.active });\n await this.mqttProxy.publish(\n event.packet.properties?.responseTopic ?? \"\",\n JSON.stringify({\n type: \"handover_fin\",\n }),\n {\n retain: false,\n properties: {\n responseTopic: this.topicBuilder.getHandoverTopic(),\n userProperties: this.getUserProperties(),\n },\n },\n );\n logger.info(`${this.processName} - Handover fin message sent.`);\n\n this.handoverInProgress = false;\n this.requestingHandover = false;\n\n await Promise.all(this.unsMqttProxies.map((unsProxy: UnsMqttProxy) => unsProxy.stop()));\n }\n\n // Requestor process\n // Check if the message is one of the handover_subscriber message in response to handover_request\n // and publish a handover_ack message\n if (response.type === \"handover_subscriber\") {\n // Find correct unsProxy instance for handover_subscriber and set it active\n this.unsMqttProxies.forEach((unsProxy: UnsMqttProxy) => {\n if (unsProxy.instanceName === response.instanceName) {\n unsProxy.setSubscriberActive(response.batchSize, response.referenceHash);\n }\n });\n }\n\n // Requestor process\n // Check if the message is a handover_fin at the end of handover_subscriber messages\n if (response.type === \"handover_fin\") {\n logger.info(`${this.processName} - Received handover fin from ${event.packet?.properties?.userProperties?.processName}.`);\n\n // Maybe we should count the number of requests that were allrady made TODO\n // this.handoverInProgress = false;\n // this.requestingHandover = false;\n\n this.active = true;\n this.event.emit(\"handoverManager\", { active: this.active });\n logger.info(`${this.processName} - Handover completed.`);\n // Activate all UNS proxy instance publishers and subscribers.\n this.unsMqttProxies.forEach((unsProxy) => {\n unsProxy.setPublisherActive();\n unsProxy.setSubscriberActive();\n });\n\n // Maybe we should reply with handover_ack.\n await this.mqttProxy.publish(\n event.packet.properties?.responseTopic ?? \"\",\n JSON.stringify({\n type: \"handover_ack\",\n }),\n {\n retain: false,\n properties: {\n responseTopic: this.topicBuilder.getHandoverTopic(),\n userProperties: this.getUserProperties(),\n },\n },\n );\n logger.info(`${this.processName} - Handover ack message sent.`);\n }\n\n // Responder process\n // Check if the message is a handover_ack at the end of handover_fin messages\n if (response.type === \"handover_ack\") {\n logger.info(`${this.processName} - Received handover ack from ${event.packet?.properties?.userProperties?.processName}.`);\n this.handoverInProgress = false;\n this.requestingHandover = false;\n\n logger.info(`${this.processName} - Handover completed. Exiting process.`);\n process.exit(0);\n }\n } catch (error) {\n logger.error(`${this.processName} - Error processing handover response: ${error.message}`);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"handover-manager.js","sourceRoot":"","sources":["../../src/uns/handover-manager.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAGlC,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAErE,OAAO,EAAE,2BAA2B,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGnE;;;;GAIG;AACH,MAAM,OAAO,eAAe;IACnB,KAAK,GAAuD,IAAI,2BAA2B,EAAyB,CAAC;IACpH,WAAW,CAAS;IACpB,SAAS,CAAS;IAClB,SAAS,CAAY;IACrB,cAAc,CAAiB;IAC/B,kBAAkB,GAAY,KAAK,CAAC;IACpC,kBAAkB,GAAY,KAAK,CAAC;IACpC,YAAY,CAAmB;IAC/B,aAAa,CAA6B;IAC1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CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,WAAW,0CAA0C,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QAC7F,CAAC;IACH,CAAC;CACF","sourcesContent":["import logger from \"../logger.js\";\nimport { HandoverManagerEvents } 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 { HandoverManagerEventEmitter } from \"./handover-manager-event-emitter.js\";\nimport { ACTIVE_TIMEOUT, PACKAGE_INFO } from \"./process-config.js\";\nimport { UnsEvents } from \"./uns-interfaces.js\";\n\n/**\n * HandoverManager is responsible for all handover-related logic,\n * including handling incoming MQTT messages, issuing handover requests,\n * and processing handover responses.\n */\nexport class HandoverManager {\n public event: HandoverManagerEventEmitter<HandoverManagerEvents> = new HandoverManagerEventEmitter<HandoverManagerEvents>();\n private processName: string;\n private processId: string;\n private mqttProxy: MqttProxy;\n private unsMqttProxies: UnsMqttProxy[];\n private requestingHandover: boolean = false;\n private handoverInProgress: boolean = false;\n private topicBuilder: MqttTopicBuilder;\n private activeTimeout: NodeJS.Timeout | undefined;\n private active: boolean = false;\n public handoverRequestEnabled: boolean = false;\n public handoverEnabled: boolean = true;\n public forceStartEnabled: boolean = false;\n\n constructor(\n processName: string,\n processId: string,\n mqttProxy: MqttProxy,\n unsMqttProxies: UnsMqttProxy[],\n handoverRequestEnabled: boolean,\n handoverEnabled: boolean,\n forceStartEnabled: boolean,\n ) {\n this.processName = processName;\n this.processId = processId;\n this.mqttProxy = mqttProxy;\n this.unsMqttProxies = unsMqttProxies;\n this.handoverRequestEnabled = handoverRequestEnabled;\n this.handoverEnabled = handoverEnabled;\n this.forceStartEnabled = forceStartEnabled;\n\n // Instantiate the topic builder.\n const packageName = PACKAGE_INFO.name;\n const version = PACKAGE_INFO.version;\n this.topicBuilder = new MqttTopicBuilder(\n `uns-infra/${MqttTopicBuilder.sanitizeTopicPart(packageName)}/${MqttTopicBuilder.sanitizeTopicPart(version)}/${MqttTopicBuilder.sanitizeTopicPart(this.processName)}/`,\n );\n\n // Set status as active after a timeout if no other active process are detected.\n this.activeTimeout = setTimeout(() => {\n logger.info(`${this.processName} - No active message received within timeout. Assuming no other process is running.`);\n this.active = true;\n this.event.emit(\"handoverManager\", { active: this.active });\n // Activate all UNS proxy instance publishers and subscribers.\n this.unsMqttProxies.forEach((unsProxy) => {\n unsProxy.setPublisherActive();\n unsProxy.setSubscriberActive();\n });\n }, ACTIVE_TIMEOUT);\n }\n\n private getUserProperties(): Record<string, string> {\n return {\n processName: this.processName,\n processId: this.processId,\n };\n }\n\n private getSourceProcessId(event: UnsEvents[\"input\"]): string | undefined {\n return event.packet?.properties?.userProperties?.processId;\n }\n\n private parseActiveValue(message: string): boolean | null {\n try {\n const parsed = JSON.parse(message);\n const value = parsed?.message?.data?.value ?? parsed?.data?.value;\n if (value === 1 || value === \"1\" || value === true || value === \"true\") {\n return true;\n }\n if (value === 0 || value === \"0\" || value === false || value === \"false\") {\n return false;\n }\n return null;\n } catch {\n return null;\n }\n }\n\n private isProcessActiveTopic(topic: string): boolean {\n const parts = topic.split(\"/\");\n if (parts.length !== 5) return false;\n const [root, pkg, , process, tail] = parts;\n if (root !== \"uns-infra\" || tail !== \"active\") return false;\n const expectedPackage = MqttTopicBuilder.sanitizeTopicPart(PACKAGE_INFO.name);\n const expectedProcess = MqttTopicBuilder.sanitizeTopicPart(this.processName);\n return pkg === expectedPackage && process === expectedProcess;\n }\n\n /**\n * Main entry point for handling incoming MQTT messages.\n * It checks the topic and delegates to the corresponding handler.\n */\n public async handleMqttMessage(event: UnsEvents[\"input\"]): Promise<void> {\n try {\n // Check if the packet is active messages from other processes and this process is not active.\n if (this.isProcessActiveTopic(event.topic) && this.requestingHandover === false && this.active === false && this.handoverInProgress === false) {\n const sourceProcessId = this.getSourceProcessId(event);\n if (sourceProcessId === this.processId) {\n return;\n }\n const activeValue = this.parseActiveValue(event.message.toString());\n if (activeValue !== true) {\n return;\n }\n const sourceInfo = sourceProcessId ? ` (processId=${sourceProcessId})` : \"\";\n logger.info(`${this.processName} - Another process is active${sourceInfo} on ${event.topic}.`);\n\n if (event.packet?.retain === true) {\n // A retained heartbeat can belong to a process that crashed before its\n // expiry. Wait for a fresh non-retained heartbeat before asking it to\n // hand over; otherwise a stale retained message would block startup.\n logger.info(`${this.processName} - Retained active heartbeat observed; waiting for a fresh heartbeat.`);\n this.activeTimeout?.refresh();\n return;\n }\n\n if (this.handoverRequestEnabled && this.handoverEnabled) {\n // Requester process\n // Publish a handover request message after 10 seconds to the handover topic.\n clearTimeout(this.activeTimeout); // Clear the active timeout if it exists - prevent this process from becoming active after a timeout.\n this.activeTimeout = undefined;\n this.event.emit(\"handoverManager\", { active: this.active });\n this.requestingHandover = true;\n const eventHandoverTopic = new MqttTopicBuilder(MqttTopicBuilder.extractBaseTopic(event.topic)).getHandoverTopic();\n await this.mqttProxy.publish(eventHandoverTopic, JSON.stringify({ type: \"handover_intent\" }), {\n retain: false,\n properties: {\n userProperties: this.getUserProperties(),\n },\n });\n logger.info(`${this.processName} - Requesting handover in 10 seconds.`);\n setTimeout(async () => {\n logger.info(`${this.processName} - Requesting handover ${eventHandoverTopic}.`);\n this.handoverInProgress = true;\n await this.mqttProxy.publish(eventHandoverTopic, JSON.stringify({ type: \"handover_request\" }), {\n retain: false,\n properties: {\n responseTopic: this.topicBuilder.getHandoverTopic(),\n userProperties: this.getUserProperties(),\n },\n });\n }, 10000);\n } else {\n if (this.forceStartEnabled) {\n // Force start the process even if another process is active.\n logger.info(`${this.processName} - Force starting the process.`);\n logger.warn(`${this.processName} - Warning: Source and destination being the same may lead to duplicate messages.`);\n clearTimeout(this.activeTimeout); // Clear the active timeout if it exists - prevent this process from becoming active after a timeout.\n this.activeTimeout = undefined;\n this.active = true;\n this.event.emit(\"handoverManager\", { active: this.active });\n // Activate all UNS proxy instance publishers and subscribers.\n this.unsMqttProxies.forEach((unsProxy) => {\n unsProxy.setPublisherActive();\n unsProxy.setSubscriberActive();\n });\n } else {\n logger.info(`${this.processName} - Waiting for the other process on topic ${event.topic} to become passive.`);\n this.activeTimeout?.refresh();\n }\n }\n }\n\n // Check if the packet is an handover message, sent to a handover topic.\n if (event.topic === this.topicBuilder.getHandoverTopic() && this.handoverEnabled) {\n const sourceProcessId = this.getSourceProcessId(event);\n if (sourceProcessId !== this.processId) {\n await this.handleHandover(event);\n }\n }\n } catch (error) {\n logger.error(`${this.processName} - Error processing MQTT message: ${error.message}`);\n return;\n }\n }\n\n /**\n * Handles handovers.\n */\n private async handleHandover(event: UnsEvents[\"input\"]): Promise<void> {\n try {\n const response = JSON.parse(event.message.toString());\n // Responder process\n // Check if the message is a handover request and publish MULTIPLE handover_subscriber messages\n if (response.type === \"handover_request\") {\n logger.info(\n `${this.processName} - Received handover request from ${event.packet?.properties?.userProperties?.processName}. Accepting handover.`,\n );\n\n // Set all UNS proxy instance subscribers to passive and drain the queue.\n const mqttWorkerData: UnsEvents[\"mqttWorker\"][] = [];\n for (let i = 0; i < this.unsMqttProxies.length; i++) {\n const unsProxy = this.unsMqttProxies[i];\n const workerData = await unsProxy.setSubscriberPassiveAndDrainQueue();\n mqttWorkerData.push(workerData);\n }\n logger.info(`${this.processName} - Handover request accepted. Sending handover_subscriber messages.`);\n\n // Publish handover_subscriber messages for each instance that has processed some data.\n for (let i = 0; i < mqttWorkerData.length; i++) {\n const workerData = mqttWorkerData[i];\n if (workerData.batchSize > 0) {\n await this.mqttProxy.publish(\n event.packet.properties?.responseTopic ?? \"\",\n JSON.stringify({\n type: \"handover_subscriber\",\n batchSize: workerData.batchSize,\n referenceHash: workerData.referenceHash,\n instanceName: workerData.instanceName,\n }),\n {\n retain: false,\n properties: {\n responseTopic: this.topicBuilder.getHandoverTopic(),\n userProperties: this.getUserProperties(),\n },\n },\n );\n }\n }\n logger.info(`${this.processName} - Handover subscriber messages sent.`);\n\n // Publish a single handover acknowledgment only when all\n // handover_subscriber messages have been sent\n this.active = false;\n this.event.emit(\"handoverManager\", { active: this.active });\n await this.mqttProxy.publish(\n event.packet.properties?.responseTopic ?? \"\",\n JSON.stringify({\n type: \"handover_fin\",\n }),\n {\n retain: false,\n properties: {\n responseTopic: this.topicBuilder.getHandoverTopic(),\n userProperties: this.getUserProperties(),\n },\n },\n );\n logger.info(`${this.processName} - Handover fin message sent.`);\n\n this.handoverInProgress = false;\n this.requestingHandover = false;\n\n await Promise.all(this.unsMqttProxies.map((unsProxy: UnsMqttProxy) => unsProxy.stop()));\n }\n\n // Requestor process\n // Check if the message is one of the handover_subscriber message in response to handover_request\n // and publish a handover_ack message\n if (response.type === \"handover_subscriber\") {\n // Find correct unsProxy instance for handover_subscriber and set it active\n this.unsMqttProxies.forEach((unsProxy: UnsMqttProxy) => {\n if (unsProxy.instanceName === response.instanceName) {\n unsProxy.setSubscriberActive(response.batchSize, response.referenceHash);\n }\n });\n }\n\n // Requestor process\n // Check if the message is a handover_fin at the end of handover_subscriber messages\n if (response.type === \"handover_fin\") {\n logger.info(`${this.processName} - Received handover fin from ${event.packet?.properties?.userProperties?.processName}.`);\n\n // Maybe we should count the number of requests that were allrady made TODO\n // this.handoverInProgress = false;\n // this.requestingHandover = false;\n\n this.active = true;\n this.event.emit(\"handoverManager\", { active: this.active });\n logger.info(`${this.processName} - Handover completed.`);\n // Activate all UNS proxy instance publishers and subscribers.\n this.unsMqttProxies.forEach((unsProxy) => {\n unsProxy.setPublisherActive();\n unsProxy.setSubscriberActive();\n });\n\n // Maybe we should reply with handover_ack.\n await this.mqttProxy.publish(\n event.packet.properties?.responseTopic ?? \"\",\n JSON.stringify({\n type: \"handover_ack\",\n }),\n {\n retain: false,\n properties: {\n responseTopic: this.topicBuilder.getHandoverTopic(),\n userProperties: this.getUserProperties(),\n },\n },\n );\n logger.info(`${this.processName} - Handover ack message sent.`);\n }\n\n // Responder process\n // Check if the message is a handover_ack at the end of handover_fin messages\n if (response.type === \"handover_ack\") {\n logger.info(`${this.processName} - Received handover ack from ${event.packet?.properties?.userProperties?.processName}.`);\n this.handoverInProgress = false;\n this.requestingHandover = false;\n\n logger.info(`${this.processName} - Handover completed. Exiting process.`);\n process.exit(0);\n }\n } catch (error) {\n logger.error(`${this.processName} - Error processing handover response: ${error.message}`);\n }\n }\n}\n"]}
@@ -5,6 +5,14 @@ interface PackageInfo {
5
5
  }
6
6
  export declare const PACKAGE_INFO: PackageInfo;
7
7
  export declare const MQTT_UPDATE_INTERVAL = 10000;
8
- export declare const ACTIVE_TIMEOUT = 10000;
8
+ /**
9
+ * A fresh active heartbeat is published every 10 seconds. Leave enough time
10
+ * for a just-subscribed process to receive a complete heartbeat interval.
11
+ */
12
+ export declare const ACTIVE_TIMEOUT = 25000;
13
+ /** Retained active heartbeats expire automatically when a process disappears. */
14
+ export declare const ACTIVE_STATUS_EXPIRY_SECONDS = 30;
15
+ /** A normal shutdown should briefly advertise passive state, then clear it. */
16
+ export declare const INACTIVE_STATUS_EXPIRY_SECONDS = 1;
9
17
  export {};
10
18
  //# sourceMappingURL=process-config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"process-config.d.ts","sourceRoot":"","sources":["../../src/uns/process-config.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,iBAAiB,QAAsC,CAAC;AAGrE,UAAU,WAAW;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAID,eAAO,MAAM,YAAY,EAAE,WAG1B,CAAC;AAGF,eAAO,MAAM,oBAAoB,QAAQ,CAAC;AAC1C,eAAO,MAAM,cAAc,QAAQ,CAAC"}
1
+ {"version":3,"file":"process-config.d.ts","sourceRoot":"","sources":["../../src/uns/process-config.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,iBAAiB,QAAsC,CAAC;AAGrE,UAAU,WAAW;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAID,eAAO,MAAM,YAAY,EAAE,WAG1B,CAAC;AAGF,eAAO,MAAM,oBAAoB,QAAQ,CAAC;AAC1C;;;GAGG;AACH,eAAO,MAAM,cAAc,QAAQ,CAAC;AACpC,iFAAiF;AACjF,eAAO,MAAM,4BAA4B,KAAK,CAAC;AAC/C,+EAA+E;AAC/E,eAAO,MAAM,8BAA8B,IAAI,CAAC"}
@@ -1,15 +1,23 @@
1
1
  // process-config.ts
2
- import * as path from "path";
3
2
  import { readFileSync } from "fs";
3
+ import * as path from "path";
4
4
  import { basePath } from "../base-path.js";
5
5
  // Path to package.json to retrieve package name and version
6
6
  export const PACKAGE_JSON_PATH = path.join(basePath, "package.json");
7
7
  const rawPackageInfo = JSON.parse(readFileSync(PACKAGE_JSON_PATH, "utf8"));
8
8
  export const PACKAGE_INFO = {
9
9
  ...rawPackageInfo,
10
- name: rawPackageInfo.name
10
+ name: rawPackageInfo.name,
11
11
  };
12
12
  // Other configuration values (update intervals, timeouts, etc.)
13
13
  export const MQTT_UPDATE_INTERVAL = 10000; // in milliseconds
14
- export const ACTIVE_TIMEOUT = 10000; // in milliseconds
14
+ /**
15
+ * A fresh active heartbeat is published every 10 seconds. Leave enough time
16
+ * for a just-subscribed process to receive a complete heartbeat interval.
17
+ */
18
+ export const ACTIVE_TIMEOUT = 25000; // in milliseconds
19
+ /** Retained active heartbeats expire automatically when a process disappears. */
20
+ export const ACTIVE_STATUS_EXPIRY_SECONDS = 30;
21
+ /** A normal shutdown should briefly advertise passive state, then clear it. */
22
+ export const INACTIVE_STATUS_EXPIRY_SECONDS = 1;
15
23
  //# sourceMappingURL=process-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"process-config.js","sourceRoot":"","sources":["../../src/uns/process-config.ts"],"names":[],"mappings":"AAAA,oBAAoB;AACpB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,4DAA4D;AAC5D,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;AAQrE,MAAM,cAAc,GAAgB,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,iBAAiB,EAAE,MAAM,CAAC,CAAC,CAAC;AAExF,MAAM,CAAC,MAAM,YAAY,GAAgB;IACvC,GAAG,cAAc;IACjB,IAAI,EAAE,cAAc,CAAC,IAAI;CAC1B,CAAC;AAEF,gEAAgE;AAChE,MAAM,CAAC,MAAM,oBAAoB,GAAG,KAAK,CAAC,CAAC,kBAAkB;AAC7D,MAAM,CAAC,MAAM,cAAc,GAAG,KAAK,CAAC,CAAC,kBAAkB","sourcesContent":["// process-config.ts\nimport * as path from \"path\";\nimport { readFileSync } from \"fs\";\nimport { basePath } from \"../base-path.js\";\n\n// Path to package.json to retrieve package name and version\nexport const PACKAGE_JSON_PATH = path.join(basePath, \"package.json\");\n\n// Read package.json and export as an object\ninterface PackageInfo {\n name: string;\n version: string;\n}\n\nconst rawPackageInfo: PackageInfo = JSON.parse(readFileSync(PACKAGE_JSON_PATH, \"utf8\"));\n\nexport const PACKAGE_INFO: PackageInfo = {\n ...rawPackageInfo,\n name: rawPackageInfo.name\n};\n\n// Other configuration values (update intervals, timeouts, etc.)\nexport const MQTT_UPDATE_INTERVAL = 10000; // in milliseconds\nexport const ACTIVE_TIMEOUT = 10000; // in milliseconds\n"]}
1
+ {"version":3,"file":"process-config.js","sourceRoot":"","sources":["../../src/uns/process-config.ts"],"names":[],"mappings":"AAAA,oBAAoB;AACpB,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAClC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,4DAA4D;AAC5D,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;AAQrE,MAAM,cAAc,GAAgB,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,iBAAiB,EAAE,MAAM,CAAC,CAAC,CAAC;AAExF,MAAM,CAAC,MAAM,YAAY,GAAgB;IACvC,GAAG,cAAc;IACjB,IAAI,EAAE,cAAc,CAAC,IAAI;CAC1B,CAAC;AAEF,gEAAgE;AAChE,MAAM,CAAC,MAAM,oBAAoB,GAAG,KAAK,CAAC,CAAC,kBAAkB;AAC7D;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,KAAK,CAAC,CAAC,kBAAkB;AACvD,iFAAiF;AACjF,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAC/C,+EAA+E;AAC/E,MAAM,CAAC,MAAM,8BAA8B,GAAG,CAAC,CAAC","sourcesContent":["// process-config.ts\nimport { readFileSync } from \"fs\";\nimport * as path from \"path\";\n\nimport { basePath } from \"../base-path.js\";\n\n// Path to package.json to retrieve package name and version\nexport const PACKAGE_JSON_PATH = path.join(basePath, \"package.json\");\n\n// Read package.json and export as an object\ninterface PackageInfo {\n name: string;\n version: string;\n}\n\nconst rawPackageInfo: PackageInfo = JSON.parse(readFileSync(PACKAGE_JSON_PATH, \"utf8\"));\n\nexport const PACKAGE_INFO: PackageInfo = {\n ...rawPackageInfo,\n name: rawPackageInfo.name,\n};\n\n// Other configuration values (update intervals, timeouts, etc.)\nexport const MQTT_UPDATE_INTERVAL = 10000; // in milliseconds\n/**\n * A fresh active heartbeat is published every 10 seconds. Leave enough time\n * for a just-subscribed process to receive a complete heartbeat interval.\n */\nexport const ACTIVE_TIMEOUT = 25000; // in milliseconds\n/** Retained active heartbeats expire automatically when a process disappears. */\nexport const ACTIVE_STATUS_EXPIRY_SECONDS = 30;\n/** A normal shutdown should briefly advertise passive state, then clear it. */\nexport const INACTIVE_STATUS_EXPIRY_SECONDS = 1;\n"]}
@@ -37,5 +37,12 @@ export declare class StatusMonitor {
37
37
  * Publishes the process active status via MQTT.
38
38
  */
39
39
  private publishStatusUpdates;
40
+ /**
41
+ * Replaces a retained active heartbeat during a graceful process shutdown.
42
+ * The short expiry means a stopped process cannot look active to a later
43
+ * handover candidate, while existing subscribers can still observe passive.
44
+ */
45
+ publishInactiveStatus(): Promise<void>;
46
+ private publishActiveStatus;
40
47
  }
41
48
  //# sourceMappingURL=status-monitor.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"status-monitor.d.ts","sourceRoot":"","sources":["../../src/uns/status-monitor.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,SAAS,MAAM,2BAA2B,CAAC;AAEvD,qBAAa,aAAa;IAatB,OAAO,CAAC,SAAS;IACjB,OAAO,CAAC,kBAAkB;IAC1B,OAAO,CAAC,cAAc;IACtB,OAAO,CAAC,gBAAgB;IACxB,OAAO,CAAC,gBAAgB;IACxB,OAAO,CAAC,eAAe,CAAC;IAjB1B,OAAO,CAAC,cAAc,CAAC,CAAiB;IACxC,OAAO,CAAC,cAAc,CAAC,CAAiB;IAExC;;;;;;;OAOG;gBAEO,SAAS,EAAE,SAAS,EACpB,kBAAkB,EAAE,MAAM,EAC1B,cAAc,EAAE,MAAM,OAAO,EAC7B,gBAAgB,EAAE,MAAM,EACxB,gBAAgB,EAAE,MAAM,EACxB,eAAe,CAAC,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE;IAGtE;;OAEG;IACI,KAAK,IAAI,IAAI;IAKpB;;OAEG;IACI,IAAI,IAAI,IAAI;IAWnB;;;OAGG;YACW,oBAAoB;IAuBlC;;OAEG;YACW,oBAAoB;CA0BnC"}
1
+ {"version":3,"file":"status-monitor.d.ts","sourceRoot":"","sources":["../../src/uns/status-monitor.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,SAAS,MAAM,2BAA2B,CAAC;AAMvD,qBAAa,aAAa;IAatB,OAAO,CAAC,SAAS;IACjB,OAAO,CAAC,kBAAkB;IAC1B,OAAO,CAAC,cAAc;IACtB,OAAO,CAAC,gBAAgB;IACxB,OAAO,CAAC,gBAAgB;IACxB,OAAO,CAAC,eAAe,CAAC;IAjB1B,OAAO,CAAC,cAAc,CAAC,CAAiB;IACxC,OAAO,CAAC,cAAc,CAAC,CAAiB;IAExC;;;;;;;OAOG;gBAEO,SAAS,EAAE,SAAS,EACpB,kBAAkB,EAAE,MAAM,EAC1B,cAAc,EAAE,MAAM,OAAO,EAC7B,gBAAgB,EAAE,MAAM,EACxB,gBAAgB,EAAE,MAAM,EACxB,eAAe,CAAC,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE;IAGtE;;OAEG;IACI,KAAK,IAAI,IAAI;IAKpB;;OAEG;IACI,IAAI,IAAI,IAAI;IAWnB;;;OAGG;YACW,oBAAoB;IAkBlC;;OAEG;YACW,oBAAoB;IAIlC;;;;OAIG;IACU,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC;YAIrC,mBAAmB;CAuBlC"}
@@ -1,5 +1,6 @@
1
1
  // status-monitor.ts
2
2
  import logger from "../logger.js";
3
+ import { ACTIVE_STATUS_EXPIRY_SECONDS, INACTIVE_STATUS_EXPIRY_SECONDS } from "./process-config.js";
3
4
  import { DataSizeMeasurements } from "./uns-measurements.js";
4
5
  import { UnsPacket } from "./uns-packet.js";
5
6
  export class StatusMonitor {
@@ -58,7 +59,9 @@ export class StatusMonitor {
58
59
  const heapUsedMessage = { data: { time, value: Math.round(memoryUsage.heapUsed / 1048576), uom: DataSizeMeasurements.MegaByte } };
59
60
  let packet = await UnsPacket.unsPacketFromUnsMessage(heapUsedMessage);
60
61
  this.mqttProxy.publish(`${this.processStatusTopic}heap-used`, JSON.stringify(packet));
61
- const heapTotalMessage = { data: { time, value: Math.round(memoryUsage.heapTotal / 1048576), uom: DataSizeMeasurements.MegaByte } };
62
+ const heapTotalMessage = {
63
+ data: { time, value: Math.round(memoryUsage.heapTotal / 1048576), uom: DataSizeMeasurements.MegaByte },
64
+ };
62
65
  packet = await UnsPacket.unsPacketFromUnsMessage(heapTotalMessage);
63
66
  this.mqttProxy.publish(`${this.processStatusTopic}heap-total`, JSON.stringify(packet));
64
67
  }
@@ -70,22 +73,34 @@ export class StatusMonitor {
70
73
  * Publishes the process active status via MQTT.
71
74
  */
72
75
  async publishStatusUpdates() {
76
+ await this.publishActiveStatus(this.activeSupplier(), ACTIVE_STATUS_EXPIRY_SECONDS);
77
+ }
78
+ /**
79
+ * Replaces a retained active heartbeat during a graceful process shutdown.
80
+ * The short expiry means a stopped process cannot look active to a later
81
+ * handover candidate, while existing subscribers can still observe passive.
82
+ */
83
+ async publishInactiveStatus() {
84
+ await this.publishActiveStatus(false, INACTIVE_STATUS_EXPIRY_SECONDS);
85
+ }
86
+ async publishActiveStatus(active, messageExpiryInterval) {
73
87
  try {
74
88
  const time = UnsPacket.formatToISO8601(new Date());
75
89
  const activeMessage = {
76
- data: { time, value: Number(this.activeSupplier()) },
90
+ data: { time, value: Number(active) },
77
91
  };
78
92
  const packet = await UnsPacket.unsPacketFromUnsMessage(activeMessage);
79
- this.mqttProxy.publish(`${this.processStatusTopic}active`, JSON.stringify(packet), {
80
- retain: false,
93
+ await this.mqttProxy.publish(`${this.processStatusTopic}active`, JSON.stringify(packet), {
94
+ retain: true,
81
95
  properties: this.processIdentity
82
96
  ? {
97
+ messageExpiryInterval,
83
98
  userProperties: {
84
99
  processName: this.processIdentity.processName,
85
100
  processId: this.processIdentity.processId,
86
101
  },
87
102
  }
88
- : undefined,
103
+ : { messageExpiryInterval },
89
104
  });
90
105
  }
91
106
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"status-monitor.js","sourceRoot":"","sources":["../../src/uns/status-monitor.ts"],"names":[],"mappings":"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B;gBACjC,IAAI,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC,EAAE;aACrD,CAAC;YACF,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,uBAAuB,CAAC,aAAa,CAAC,CAAC;YACtE,IAAI,CAAC,SAAS,CAAC,OAAO,CACpB,GAAG,IAAI,CAAC,kBAAkB,QAAQ,EAClC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EACtB;gBACE,MAAM,EAAE,KAAK;gBACb,UAAU,EAAE,IAAI,CAAC,eAAe;oBAC9B,CAAC,CAAC;wBACA,cAAc,EAAE;4BACd,WAAW,EAAE,IAAI,CAAC,eAAe,CAAC,WAAW;4BAC7C,SAAS,EAAE,IAAI,CAAC,eAAe,CAAC,SAAS;yBAC1C;qBACF;oBACD,CAAC,CAAC,SAAS;aACd,CACF,CAAC;QACJ,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,MAAM,CAAC,KAAK,CAAC,oDAAoD,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACpF,CAAC;IACH,CAAC;CACF","sourcesContent":["// status-monitor.ts\nimport logger from \"../logger.js\";\nimport { IUnsMessage } from \"./uns-interfaces.js\";\nimport { DataSizeMeasurements } from \"./uns-measurements.js\";\nimport { UnsPacket } from \"./uns-packet.js\";\nimport type MqttProxy from \"../uns-mqtt/mqtt-proxy.js\";\n\nexport class StatusMonitor {\n private memoryInterval?: NodeJS.Timeout;\n private statusInterval?: NodeJS.Timeout;\n\n /**\n * @param mqttProxy The MQTT proxy used to publish messages.\n * @param processStatusTopic The base topic for the process (ending with a slash).\n * @param activeSupplier A function returning the current active state (boolean).\n * @param memoryIntervalMs Interval in milliseconds for publishing memory status.\n * @param statusIntervalMs Interval in milliseconds for publishing active status.\n * @param processIdentity Optional identity to attach to active status messages.\n */\n constructor(\n private mqttProxy: MqttProxy,\n private processStatusTopic: string,\n private activeSupplier: () => boolean,\n private memoryIntervalMs: number,\n private statusIntervalMs: number,\n private processIdentity?: { processName: string; processId: string },\n ) {}\n\n /**\n * Starts the periodic memory and status updates.\n */\n public start(): void {\n this.memoryInterval = setInterval(() => this.publishMemoryUpdates(), this.memoryIntervalMs);\n this.statusInterval = setInterval(() => this.publishStatusUpdates(), this.statusIntervalMs);\n }\n\n /**\n * Stops the periodic updates.\n */\n public stop(): void {\n if (this.memoryInterval) {\n clearInterval(this.memoryInterval);\n this.memoryInterval = undefined;\n }\n if (this.statusInterval) {\n clearInterval(this.statusInterval);\n this.statusInterval = undefined;\n }\n }\n\n /**\n * Publishes memory usage updates via MQTT.\n * In this example, only the `heapUsed` metric is published.\n */\n private async publishMemoryUpdates(): Promise<void> {\n try {\n const time = UnsPacket.formatToISO8601(new Date());\n const memoryUsage = process.memoryUsage();\n const heapUsedMessage: IUnsMessage = { data: { time, value: Math.round(memoryUsage.heapUsed/1048576), uom: DataSizeMeasurements.MegaByte } };\n let packet = await UnsPacket.unsPacketFromUnsMessage(heapUsedMessage);\n this.mqttProxy.publish(\n `${this.processStatusTopic}heap-used`,\n JSON.stringify(packet)\n );\n\n const heapTotalMessage: IUnsMessage = { data: { time, value: Math.round(memoryUsage.heapTotal/1048576), uom: DataSizeMeasurements.MegaByte } };\n packet = await UnsPacket.unsPacketFromUnsMessage(heapTotalMessage);\n this.mqttProxy.publish(\n `${this.processStatusTopic}heap-total`,\n JSON.stringify(packet)\n );\n\n } catch (error: any) {\n logger.error(`StatusMonitor - Error publishing memory updates: ${error.message}`);\n }\n }\n\n /**\n * Publishes the process active status via MQTT.\n */\n private async publishStatusUpdates(): Promise<void> {\n try {\n const time = UnsPacket.formatToISO8601(new Date());\n const activeMessage: IUnsMessage = {\n data: { time, value: Number(this.activeSupplier()) },\n };\n const packet = await UnsPacket.unsPacketFromUnsMessage(activeMessage);\n this.mqttProxy.publish(\n `${this.processStatusTopic}active`,\n JSON.stringify(packet),\n {\n retain: false,\n properties: this.processIdentity\n ? {\n userProperties: {\n processName: this.processIdentity.processName,\n processId: this.processIdentity.processId,\n },\n }\n : undefined,\n },\n );\n } catch (error: any) {\n logger.error(`StatusMonitor - Error publishing status updates: ${error.message}`);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"status-monitor.js","sourceRoot":"","sources":["../../src/uns/status-monitor.ts"],"names":[],"mappings":"AAAA,oBAAoB;AACpB,OAAO,MAAM,MAAM,cAAc,CAAC;AAElC,OAAO,EAAE,4BAA4B,EAAE,8BAA8B,EAAE,MAAM,qBAAqB,CAAC;AAEnG,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,MAAM,OAAO,aAAa;IAad;IACA;IACA;IACA;IACA;IACA;IAjBF,cAAc,CAAkB;IAChC,cAAc,CAAkB;IAExC;;;;;;;OAOG;IACH,YACU,SAAoB,EACpB,kBAA0B,EAC1B,cAA6B,EAC7B,gBAAwB,EACxB,gBAAwB,EACxB,eAA4D;QAL5D,cAAS,GAAT,SAAS,CAAW;QACpB,uBAAkB,GAAlB,kBAAkB,CAAQ;QAC1B,mBAAc,GAAd,cAAc,CAAe;QAC7B,qBAAgB,GAAhB,gBAAgB,CAAQ;QACxB,qBAAgB,GAAhB,gBAAgB,CAAQ;QACxB,oBAAe,GAAf,eAAe,CAA6C;IACnE,CAAC;IAEJ;;OAEG;IACI,KAAK;QACV,IAAI,CAAC,cAAc,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,oBAAoB,EAAE,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAAC;QAC5F,IAAI,CAAC,cAAc,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,oBAAoB,EAAE,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAAC;IAC9F,CAAC;IAED;;OAEG;IACI,IAAI;QACT,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACxB,aAAa,CAAC,IAAI,CA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,EAAE,CAAC,CAAC;QACpF,CAAC;IACH,CAAC;CACF","sourcesContent":["// status-monitor.ts\nimport logger from \"../logger.js\";\nimport type MqttProxy from \"../uns-mqtt/mqtt-proxy.js\";\nimport { ACTIVE_STATUS_EXPIRY_SECONDS, INACTIVE_STATUS_EXPIRY_SECONDS } from \"./process-config.js\";\nimport { IUnsMessage } from \"./uns-interfaces.js\";\nimport { DataSizeMeasurements } from \"./uns-measurements.js\";\nimport { UnsPacket } from \"./uns-packet.js\";\n\nexport class StatusMonitor {\n private memoryInterval?: NodeJS.Timeout;\n private statusInterval?: NodeJS.Timeout;\n\n /**\n * @param mqttProxy The MQTT proxy used to publish messages.\n * @param processStatusTopic The base topic for the process (ending with a slash).\n * @param activeSupplier A function returning the current active state (boolean).\n * @param memoryIntervalMs Interval in milliseconds for publishing memory status.\n * @param statusIntervalMs Interval in milliseconds for publishing active status.\n * @param processIdentity Optional identity to attach to active status messages.\n */\n constructor(\n private mqttProxy: MqttProxy,\n private processStatusTopic: string,\n private activeSupplier: () => boolean,\n private memoryIntervalMs: number,\n private statusIntervalMs: number,\n private processIdentity?: { processName: string; processId: string },\n ) {}\n\n /**\n * Starts the periodic memory and status updates.\n */\n public start(): void {\n this.memoryInterval = setInterval(() => this.publishMemoryUpdates(), this.memoryIntervalMs);\n this.statusInterval = setInterval(() => this.publishStatusUpdates(), this.statusIntervalMs);\n }\n\n /**\n * Stops the periodic updates.\n */\n public stop(): void {\n if (this.memoryInterval) {\n clearInterval(this.memoryInterval);\n this.memoryInterval = undefined;\n }\n if (this.statusInterval) {\n clearInterval(this.statusInterval);\n this.statusInterval = undefined;\n }\n }\n\n /**\n * Publishes memory usage updates via MQTT.\n * In this example, only the `heapUsed` metric is published.\n */\n private async publishMemoryUpdates(): Promise<void> {\n try {\n const time = UnsPacket.formatToISO8601(new Date());\n const memoryUsage = process.memoryUsage();\n const heapUsedMessage: IUnsMessage = { data: { time, value: Math.round(memoryUsage.heapUsed / 1048576), uom: DataSizeMeasurements.MegaByte } };\n let packet = await UnsPacket.unsPacketFromUnsMessage(heapUsedMessage);\n this.mqttProxy.publish(`${this.processStatusTopic}heap-used`, JSON.stringify(packet));\n\n const heapTotalMessage: IUnsMessage = {\n data: { time, value: Math.round(memoryUsage.heapTotal / 1048576), uom: DataSizeMeasurements.MegaByte },\n };\n packet = await UnsPacket.unsPacketFromUnsMessage(heapTotalMessage);\n this.mqttProxy.publish(`${this.processStatusTopic}heap-total`, JSON.stringify(packet));\n } catch (error: any) {\n logger.error(`StatusMonitor - Error publishing memory updates: ${error.message}`);\n }\n }\n\n /**\n * Publishes the process active status via MQTT.\n */\n private async publishStatusUpdates(): Promise<void> {\n await this.publishActiveStatus(this.activeSupplier(), ACTIVE_STATUS_EXPIRY_SECONDS);\n }\n\n /**\n * Replaces a retained active heartbeat during a graceful process shutdown.\n * The short expiry means a stopped process cannot look active to a later\n * handover candidate, while existing subscribers can still observe passive.\n */\n public async publishInactiveStatus(): Promise<void> {\n await this.publishActiveStatus(false, INACTIVE_STATUS_EXPIRY_SECONDS);\n }\n\n private async publishActiveStatus(active: boolean, messageExpiryInterval: number): Promise<void> {\n try {\n const time = UnsPacket.formatToISO8601(new Date());\n const activeMessage: IUnsMessage = {\n data: { time, value: Number(active) },\n };\n const packet = await UnsPacket.unsPacketFromUnsMessage(activeMessage);\n await this.mqttProxy.publish(`${this.processStatusTopic}active`, JSON.stringify(packet), {\n retain: true,\n properties: this.processIdentity\n ? {\n messageExpiryInterval,\n userProperties: {\n processName: this.processIdentity.processName,\n processId: this.processIdentity.processId,\n },\n }\n : { messageExpiryInterval },\n });\n } catch (error: any) {\n logger.error(`StatusMonitor - Error publishing status updates: ${error.message}`);\n }\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
- import { IUnsParameters, IUnsProcessParameters } from "./uns-interfaces.js";
2
1
  import UnsMqttProxy from "../uns-mqtt/uns-mqtt-proxy.js";
3
2
  import type { UnsMqttProxyStopOptions } from "../uns-mqtt/uns-mqtt-proxy.js";
4
3
  import { type UnsServiceMetadata, type UnsServiceMetadataInput } from "./service-metadata.js";
4
+ import { IUnsParameters, IUnsProcessParameters } from "./uns-interfaces.js";
5
5
  /**
6
6
  * UnsProxyProcess is responsible for managing the process lifecycle,
7
7
  * configuring MQTT (subscriptions and publishing for status updates), and
@@ -1 +1 @@
1
- {"version":3,"file":"uns-proxy-process.d.ts","sourceRoot":"","sources":["../../src/uns/uns-proxy-process.ts"],"names":[],"mappings":"AAEA,OAAO,EAAe,cAAc,EAAE,qBAAqB,EAAa,MAAM,qBAAqB,CAAC;AAGpG,OAAO,YAAY,MAAM,+BAA+B,CAAC;AAQzD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AAC7E,OAAO,EAEL,KAAK,kBAAkB,EACvB,KAAK,uBAAuB,EAC7B,MAAM,uBAAuB,CAAC;AAG/B;;;;;;GAMG;AACH,MAAM,MAAM,2BAA2B,GAAG,CAAC,IAAI,EAAE,eAAe,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC;AAEjG,MAAM,MAAM,4BAA4B,GAAG,MAAM,CAAC,MAAM,EAAE,2BAA2B,CAAC,CAAC;AAEvF,MAAM,WAAW,wBAAwB;IACvC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,OAAO,EAAE,4BAA4B,GAAG,IAAI,CAAC;IACpD,eAAe,EAAE,OAAO,eAAe,CAAC;CACzC;AAED,MAAM,MAAM,qBAAqB,GAAG,CAAC,GAAG,EAAE,wBAAwB,KAAK,IAAI,CAAC;AAE5E,cAAM,eAAe;IACnB,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,kBAAkB,CAAS;IACnC,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,cAAc,CAAiB;IACvC,OAAO,CAAC,aAAa,CAAY;IACjC,OAAO,CAAC,gBAAgB,CAAY;IACpC,OAAO,CAAC,e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B;IAOxC,OAAO,CAAC,MAAM,CAAC,WAAW;IA0B1B,OAAO,CAAC,MAAM,CAAC,QAAQ;IAOvB,OAAO,CAAC,gBAAgB,CAAuB;gBAEnC,QAAQ,EAAE,MAAM,EAAE,yBAAyB,EAAE,qBAAqB;IAsE9E;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IA0B3B;;OAEG;IACU,kBAAkB,CAC7B,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,MAAM,EACpB,YAAY,EAAE,MAAM,EACpB,QAAQ,EAAE,OAAO,EACjB,aAAa,CAAC,EAAE,cAAc,GAC7B,OAAO,CAAC,YAAY,CAAC;IAiCX,wBAAwB,IAAI,OAAO,CAAC,IAAI,CAAC;IAMtD;;;;;;OAMG;IACU,sBAAsB,CAAC,QAAQ,EAAE,uBAAuB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAWnG;;;OAGG;IACI,QAAQ,CAAC,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,IAAI,CAAC;YASvD,eAAe;CAgD9B;AAED,UAAU,eAAe;CAAG;AAE5B,eAAe,eAAe,CAAC;AAC/B,YAAY,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,CAAC"}
@@ -1,14 +1,14 @@
1
- import logger from "../logger.js";
2
1
  import { randomBytes } from "crypto";
2
+ import logger from "../logger.js";
3
3
  import MqttProxy from "../uns-mqtt/mqtt-proxy.js";
4
+ import { MqttTopicBuilder } from "../uns-mqtt/mqtt-topic-builder.js";
4
5
  import UnsMqttProxy from "../uns-mqtt/uns-mqtt-proxy.js";
5
6
  import { HandoverManager } from "./handover-manager.js";
6
7
  // Import configuration and initialization modules.
7
- import { PACKAGE_INFO, MQTT_UPDATE_INTERVAL } from "./process-config.js";
8
- import { MqttTopicBuilder } from "../uns-mqtt/mqtt-topic-builder.js";
8
+ import { MQTT_UPDATE_INTERVAL, PACKAGE_INFO } from "./process-config.js";
9
+ import { buildUnsServiceMetadata } from "./service-metadata.js";
9
10
  import { StatusMonitor } from "./status-monitor.js";
10
11
  import { UnsPacket } from "./uns-packet.js";
11
- import { buildUnsServiceMetadata, } from "./service-metadata.js";
12
12
  class UnsProxyProcess {
13
13
  active = false;
14
14
  processStatusTopic;
@@ -87,10 +87,7 @@ class UnsProxyProcess {
87
87
  this.processStatusTopic = processStatusTopic;
88
88
  this.serviceMetadataTopic = serviceMetadataTopic;
89
89
  // Configure MQTT topics for subscription.
90
- const mqttSubToTopics = unsProxyProcessParameters?.mqttSubToTopics ?? [
91
- wildcardActiveTopic,
92
- handoverTopic,
93
- ];
90
+ const mqttSubToTopics = unsProxyProcessParameters?.mqttSubToTopics ?? [wildcardActiveTopic, handoverTopic];
94
91
  const mqttParameters = {
95
92
  mqttSubToTopics,
96
93
  username: unsProxyProcessParameters?.username ?? "",
@@ -209,10 +206,11 @@ class UnsProxyProcess {
209
206
  const shutdownErrors = [];
210
207
  try {
211
208
  this.statusMonitor.stop();
209
+ await this.statusMonitor.publishInactiveStatus();
212
210
  }
213
211
  catch (e) {
214
212
  const reason = e instanceof Error ? e : new Error(String(e));
215
- logger.error(`${this.processName} - Error stopping StatusMonitor: ${reason.message}`);
213
+ logger.error(`${this.processName} - Error stopping StatusMonitor or publishing passive state: ${reason.message}`);
216
214
  shutdownErrors.push(reason);
217
215
  }
218
216
  if (this.mqttInputHandler) {
@@ -1 +1 @@
1
- {"version":3,"file":"uns-proxy-process.js","sourceRoot":"","sources":["../../src/uns/uns-proxy-process.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAGrC,OAAO,SAAS,MAAM,2BAA2B,CAAC;AAClD,OAAO,YAAY,MAAM,+BAA+B,CAAC;AACzD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,mDAAmD;AACnD,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,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K,CAAC,GAAG,IAAI,CAAC,WAAW,qCAAqC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC;gBACvF,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC9B,CAAC;QACH,CAAC;QAED,IAAI,CAAC;YACH,IAAI,OAAO,IAAI,CAAC,gBAAgB,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;gBACrD,MAAM,IAAI,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAC;YACrC,CAAC;QACH,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,MAAM,MAAM,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAC7D,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,WAAW,iCAAiC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC;YACnF,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC9B,CAAC;QAED,IAAI,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC9B,MAAM,IAAI,cAAc,CAAC,cAAc,EAAE,GAAG,IAAI,CAAC,WAAW,oCAAoC,CAAC,CAAC;QACpG,CAAC;QAED,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,WAAW,uBAAuB,CAAC,CAAC;IAC1D,CAAC;;AAMH,eAAe,eAAe,CAAC;AAE/B,OAAO,EAAE,eAAe,EAAE,CAAC","sourcesContent":["import logger from \"../logger.js\";\nimport { randomBytes } from \"crypto\";\nimport { IUnsMessage, IUnsParameters, IUnsProcessParameters, UnsEvents } from \"./uns-interfaces.js\";\nimport { IMqttParameters } from \"../uns-mqtt/mqtt-interfaces.js\";\nimport MqttProxy from \"../uns-mqtt/mqtt-proxy.js\";\nimport UnsMqttProxy from \"../uns-mqtt/uns-mqtt-proxy.js\";\nimport { HandoverManager } from \"./handover-manager.js\";\n\n// Import configuration and initialization modules.\nimport { PACKAGE_INFO, MQTT_UPDATE_INTERVAL } from \"./process-config.js\";\nimport { MqttTopicBuilder } from \"../uns-mqtt/mqtt-topic-builder.js\";\nimport { StatusMonitor } from \"./status-monitor.js\";\nimport { UnsPacket } from \"./uns-packet.js\";\nimport type { UnsMqttProxyStopOptions } from \"../uns-mqtt/uns-mqtt-proxy.js\";\nimport {\n buildUnsServiceMetadata,\n type UnsServiceMetadata,\n type UnsServiceMetadataInput,\n} from \"./service-metadata.js\";\n\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 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\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 this.processName = unsProxyProcessParameters.processName;\n this.processId = randomBytes(16).toString(\"hex\");\n const { name: packageName, version } = PACKAGE_INFO;\n\n // Instantiate the topic builder.\n const topicBuilder = new MqttTopicBuilder(`uns-infra/${MqttTopicBuilder.sanitizeTopicPart(packageName)}/${MqttTopicBuilder.sanitizeTopicPart(version)}/${MqttTopicBuilder.sanitizeTopicPart(this.processName)}/`);\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 ?? [\n wildcardActiveTopic,\n handoverTopic,\n ];\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) {\n\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 );\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): Promise<UnsMqttProxy> {\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(instanceMode, handover);\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(\n event.statusTopic,\n JSON.stringify(event.producedTopics),\n );\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(\n event.statusTopic,\n JSON.stringify(packet),\n );\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(\n this.serviceMetadataTopic,\n JSON.stringify(resolved),\n { retain: true },\n );\n return resolved;\n }\n\n /**\n * Shuts down the process by clearing intervals, timeouts, and removing\n * MQTT event listeners, and stopping the StatusMonitor.\n */\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 } catch (e: any) {\n const reason = e instanceof Error ? e : new Error(String(e));\n logger.error(`${this.processName} - Error stopping StatusMonitor: ${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(\n this.unsMqttProxies.map((proxy) => proxy.stop(options)),\n );\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 logger.info(`${this.processName} - Shutdown complete.`);\n }\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,WAAW,EAAE,MAAM,QAAQ,CAAC;AAErC,OAAO,MAAM,MAAM,cAAc,CAAC;AAElC,OAAO,SAAS,MAAM,2BAA2B,CAAC;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AACrE,OAAO,YAAY,MAAM,+BAA+B,CAAC;AAEzD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,mDAAmD;AACnD,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACzE,OAAO,EAAyD,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AACvH,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAqB5C,MAAM,eAAe;IACX,MAAM,GAAY,KAAK,CAAC;IACxB,kBAAkB,CAAS;IAC3B,WAAW,CAAS;IACpB,SAAS,CAAS;IAClB,cAAc,CAAiB;IAC/B,aAAa,CAAY;IACzB,gBAAgB,CAAY;IAC5B,eAAe,CAAkB;IACjC,aAAa,CAAgB;IAC7B,oBAAoB,CAAS;IAC7B,eAAe,GAAyB,IAAI,CAAC;IAErD,SAAS;IACT,MAAM,CAAC,gBAAgB,GAAG,CAAC,CAAC;IACpB,MAAM,CAAC,UAAU,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AC,KAAK,CAAC,GAAG,IAAI,CAAC,WAAW,iCAAiC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC;YACnF,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC9B,CAAC;QAED,IAAI,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC9B,MAAM,IAAI,cAAc,CAAC,cAAc,EAAE,GAAG,IAAI,CAAC,WAAW,oCAAoC,CAAC,CAAC;QACpG,CAAC;QAED,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 { 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\";\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 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\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 this.processName = unsProxyProcessParameters.processName;\n this.processId = randomBytes(16).toString(\"hex\");\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) {\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 );\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 // 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(instanceMode, handover);\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 /**\n * Shuts down the process by clearing intervals, timeouts, and removing\n * MQTT event listeners, and stopping the StatusMonitor.\n */\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 logger.info(`${this.processName} - Shutdown complete.`);\n }\n}\n\ninterface UnsProxyProcess {}\n\nexport default UnsProxyProcess;\nexport type { UnsServiceMetadata, UnsServiceMetadataInput };\nexport { UnsProxyProcess };\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uns-kit/core",
3
- "version": "3.0.10",
3
+ "version": "3.0.13",
4
4
  "description": "Core utilities and runtime building blocks for UNS-based realtime transformers.",
5
5
  "type": "module",
6
6
  "license": "MIT",