@uns-kit/core 3.0.22 → 3.0.24

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,55 @@ 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.24 - Generated numeric delta metadata
13
+
14
+ When upgrading from `<3.0.24` to `>=3.0.24`, numeric scalar publications in
15
+ the deprecated `MessageMode.Delta` and `MessageMode.Both` modes declare
16
+ `presentationKind: "delta"` and `defaultAggregation: "sum"` on the generated
17
+ `-delta` attribute. They no longer inherit cumulative-counter presentation,
18
+ last aggregation or a counter reset-policy hint. The original raw attribute
19
+ keeps its caller-supplied metadata. Paths, packet values, timestamps, units,
20
+ persistence, freshness and the existing difference/reset calculation remain
21
+ unchanged. Non-numeric and table publication metadata are unchanged.
22
+
23
+ Review existing canonical schema definitions for generated delta attributes:
24
+ controllers may keep previously stored non-null shape fields after an upgrade.
25
+ Correct reviewed definitions to interval/delta semantics and request raw
26
+ history with sum aggregation for interval amounts. Do not difference already
27
+ calculated deltas. Do not globally label unsuffixed attributes as counters
28
+ from their names: other publishers can reuse a name for interval amounts.
29
+
30
+ These legacy producer delta modes still lose previous-value state on restart.
31
+ Preserve consumers while migrating toward raw cumulative counters and history
32
+ API delta/rate transforms; this metadata fix does not make delta state durable.
33
+
34
+ ## 3.0.23 - Application drain on handover
35
+
36
+ Applications upgrading from `<3.0.23` to `>=3.0.23` may register
37
+ `handoverShutdown: { onRelease, drain, timeoutMs }` in `UnsProxyProcess`
38
+ construction, before creating MQTT proxies. `onRelease` runs synchronously when
39
+ an active source accepts a handover: stop admitting new background work, but
40
+ continue handling already accepted MQTT input while subscriber queues drain.
41
+ `drain` runs after the target's acknowledgement and source proxy stops. Await
42
+ accepted application writes, durable spills and replay checkpoints, then close
43
+ writers. Do not call `process.exit` inside either hook. Share an idempotent drain
44
+ with SIGINT/SIGTERM cleanup; signal cleanup remains application-owned.
45
+
46
+ The source exits with status 0 only when its remaining proxy stops and drain
47
+ finish. A rejected hook or deadline exits with status 1 and a generic diagnostic,
48
+ without logging hook error text. The default deadline after acknowledgement is
49
+ 30 seconds; a registered timeout may be 1 to 300000 ms. Timeout does not cancel
50
+ IO or guarantee all writes were saved. Persist recoverable work before relying
51
+ on this hook and review pending files after an incomplete drain.
52
+
53
+ Duplicate acknowledgements share one drain. Unsolicited acknowledgements and
54
+ acknowledgements from a different peer do not exit the process. MQTT wire
55
+ messages are unchanged, so an old source still uses its old immediate exit:
56
+ upgrading only the target cannot retrofit the source hook. `handover_fin` and
57
+ `handover_ack` confirm MQTT ownership transfer, not application drain or a safe
58
+ legacy-directory import. Wait for source process exit separately. This change
59
+ does not add exactly-once semantics or controller fencing.
60
+
12
61
  ## 3.0.22 - Safe API request correlation
13
62
 
14
63
  When upgrading `@uns-kit/api` from `<3.0.22` to `>=3.0.22`, its generic request
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export { default as UnsProxyProcess } from "./uns/uns-proxy-process.js";
2
2
  export type { UnsProxyProcessPlugin, UnsProxyProcessPluginApi, UnsProxyProcessPluginMethod, UnsProxyProcessPluginMethods, } from "./uns/uns-proxy-process.js";
3
3
  export * from "./uns/uns-interfaces.js";
4
+ export type { HandoverShutdownHooks } from "./uns/handover-shutdown.js";
4
5
  export * from "./uns/service-metadata.js";
5
6
  export { ConfigFile } from "./config-file.js";
6
7
  export { default as logger } from "./logger.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,4BAA4B,CAAC;AACxE,YAAY,EACV,qBAAqB,EACrB,wBAAwB,EACxB,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,4BAA4B,CAAC;AACpC,cAAc,yBAAyB,CAAC;A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AAC;AACxC,YAAY,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACxE,cAAc,2BAA2B,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AACzF,YAAY,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAC3F,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AACzE,YAAY,EAAE,mBAAmB,EAAE,2BAA2B,EAAE,MAAM,uBAAuB,CAAC;AAC9F,OAAO,EACL,SAAS,EACT,eAAe,EACf,WAAW,EACX,WAAW,EACX,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,mCAAmC,CAAC;AAC3C,YAAY,EACV,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,EACX,UAAU,EACV,YAAY,EACZ,sBAAsB,EACtB,yBAAyB,EACzB,qBAAqB,EACrB,gCAAgC,EAChC,wCAAwC,EACxC,wCAAwC,GACzC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,iDAAiD,CAAC;AAClF,YAAY,EACV,sBAAsB,EACtB,wBAAwB,EACxB,0BAA0B,EAC1B,gCAAgC,GACjC,MAAM,iDAAiD,CAAC"}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAOxE,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAEzF,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAEzE,OAAO,EACL,SAAS,EACT,eAAe,EACf,WAAW,EACX,WAAW,EACX,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,mCAAmC,CAAC;AAgB3C,OAAO,EAAE,eAAe,EAAE,MAAM,iDAAiD,CAAC","sourcesContent":["export { default as UnsProxyProcess } from \"./uns/uns-proxy-process.js\";\nexport type {\n UnsProxyProcessPlugin,\n UnsProxyProcessPluginApi,\n UnsProxyProcessPluginMethod,\n UnsProxyProcessPluginMethods,\n} from \"./uns/uns-proxy-process.js\";\nexport * from \"./uns/uns-interfaces.js\";\nexport * from \"./uns/service-metadata.js\";\nexport { ConfigFile } from \"./config-file.js\";\nexport { default as logger } from \"./logger.js\";\nexport { getLogger } from \"./logger.js\";\nexport { resolveInfisicalConfig } from \"./uns-config/secret-resolver.js\";\nexport { mqttChannelParameters, resolveMqttChannel } from \"./uns-config/mqtt-channel.js\";\nexport type { MqttChannelConfig, ResolvedMqttChannel } from \"./uns-config/mqtt-channel.js\";\nexport { AuthClient, ServiceTokenProvider } from \"./tools/auth/index.js\";\nexport type { AccessTokenProvider, ServiceTokenProviderOptions } from \"./tools/auth/index.js\";\nexport {\n UnsClient,\n LastValueResult,\n ClientError,\n RangeResult,\n BatchRangeTopicResult,\n BatchRangeResponse,\n} from \"./tools/datahub/datahub-client.js\";\nexport type {\n LastValuePayload,\n CatchAllTimeField,\n CatchAllAggregate,\n RangeQueryOptions,\n RangeColumn,\n RangeStats,\n RangePayload,\n BatchRangeTopicPayload,\n BatchRangeResponsePayload,\n ProviderAssetIdentity,\n AssetIdentityPublicationMetadata,\n AssetProviderIdentityPublicationMetadata,\n AssetIdentityPublicationEvidenceMetadata,\n} from \"./tools/datahub/datahub-client.js\";\nexport { registerService } from \"./tools/datahub/runtime-service-registration.js\";\nexport type {\n RegisterServiceOptions,\n RuntimeServiceDescriptor,\n RuntimeServiceRegistration,\n RuntimeServiceRegistrationClient,\n} from \"./tools/datahub/runtime-service-registration.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAOxE,cAAc,yBAAyB,CAAC;AAExC,cAAc,2BAA2B,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAEzF,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAEzE,OAAO,EACL,SAAS,EACT,eAAe,EACf,WAAW,EACX,WAAW,EACX,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,mCAAmC,CAAC;AAgB3C,OAAO,EAAE,eAAe,EAAE,MAAM,iDAAiD,CAAC","sourcesContent":["export { default as UnsProxyProcess } from \"./uns/uns-proxy-process.js\";\nexport type {\n UnsProxyProcessPlugin,\n UnsProxyProcessPluginApi,\n UnsProxyProcessPluginMethod,\n UnsProxyProcessPluginMethods,\n} from \"./uns/uns-proxy-process.js\";\nexport * from \"./uns/uns-interfaces.js\";\nexport type { HandoverShutdownHooks } from \"./uns/handover-shutdown.js\";\nexport * from \"./uns/service-metadata.js\";\nexport { ConfigFile } from \"./config-file.js\";\nexport { default as logger } from \"./logger.js\";\nexport { getLogger } from \"./logger.js\";\nexport { resolveInfisicalConfig } from \"./uns-config/secret-resolver.js\";\nexport { mqttChannelParameters, resolveMqttChannel } from \"./uns-config/mqtt-channel.js\";\nexport type { MqttChannelConfig, ResolvedMqttChannel } from \"./uns-config/mqtt-channel.js\";\nexport { AuthClient, ServiceTokenProvider } from \"./tools/auth/index.js\";\nexport type { AccessTokenProvider, ServiceTokenProviderOptions } from \"./tools/auth/index.js\";\nexport {\n UnsClient,\n LastValueResult,\n ClientError,\n RangeResult,\n BatchRangeTopicResult,\n BatchRangeResponse,\n} from \"./tools/datahub/datahub-client.js\";\nexport type {\n LastValuePayload,\n CatchAllTimeField,\n CatchAllAggregate,\n RangeQueryOptions,\n RangeColumn,\n RangeStats,\n RangePayload,\n BatchRangeTopicPayload,\n BatchRangeResponsePayload,\n ProviderAssetIdentity,\n AssetIdentityPublicationMetadata,\n AssetProviderIdentityPublicationMetadata,\n AssetIdentityPublicationEvidenceMetadata,\n} from \"./tools/datahub/datahub-client.js\";\nexport { registerService } from \"./tools/datahub/runtime-service-registration.js\";\nexport type {\n RegisterServiceOptions,\n RuntimeServiceDescriptor,\n RuntimeServiceRegistration,\n RuntimeServiceRegistrationClient,\n} from \"./tools/datahub/runtime-service-registration.js\";\n"]}
@@ -1,3 +1,4 @@
1
+ import { type HandoverShutdownHooks } from "./handover-shutdown.js";
1
2
  import { HandoverManagerEvents } from "../uns-mqtt/mqtt-interfaces.js";
2
3
  import MqttProxy from "../uns-mqtt/mqtt-proxy.js";
3
4
  import UnsMqttProxy from "../uns-mqtt/uns-mqtt-proxy.js";
@@ -21,10 +22,14 @@ export declare class HandoverManager {
21
22
  private readonly handoverId;
22
23
  private acceptedHandoverId;
23
24
  private active;
25
+ private sourcePeerId;
26
+ private sourcePreparation;
27
+ private sourceExit;
28
+ private readonly shutdownHooks;
24
29
  handoverRequestEnabled: boolean;
25
30
  handoverEnabled: boolean;
26
31
  forceStartEnabled: boolean;
27
- constructor(processName: string, processId: string, mqttProxy: MqttProxy, unsMqttProxies: UnsMqttProxy[], handoverRequestEnabled: boolean, handoverEnabled: boolean, forceStartEnabled: boolean, handoverId?: string);
32
+ constructor(processName: string, processId: string, mqttProxy: MqttProxy, unsMqttProxies: UnsMqttProxy[], handoverRequestEnabled: boolean, handoverEnabled: boolean, forceStartEnabled: boolean, handoverId?: string, shutdownHooks?: HandoverShutdownHooks);
28
33
  private getUserProperties;
29
34
  private handoverPayload;
30
35
  private getHandoverId;
@@ -40,6 +45,9 @@ export declare class HandoverManager {
40
45
  /**
41
46
  * Handles handovers.
42
47
  */
48
+ private exitSource;
49
+ private prepareSourceHandover;
50
+ private finishSourceHandover;
43
51
  private handleHandover;
44
52
  }
45
53
  //# sourceMappingURL=handover-manager.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"handover-manager.d.ts","sourceRoot":"","sources":["../../src/uns/handover-manager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,SAAS,MAAM,2BAA2B,CAAC;AAElD,OAAO,YAAY,MAAM,+BAA+B,CAAC;AACzD,OAAO,EAAE,2BAA2B,EAAE,MAAM,qCAAqC,CAAC;AAElF,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAQhD;;;;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,CAA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B,oBAAoB;YAiBpB,cAAc;CA2F7B"}
@@ -1,4 +1,5 @@
1
1
  import logger from "../logger.js";
2
+ import { runHandoverShutdown, validateHandoverShutdown } from "./handover-shutdown.js";
2
3
  import { MqttTopicBuilder } from "../uns-mqtt/mqtt-topic-builder.js";
3
4
  import { HandoverManagerEventEmitter } from "./handover-manager-event-emitter.js";
4
5
  import { ACTIVE_TIMEOUT, PACKAGE_INFO } from "./process-config.js";
@@ -26,10 +27,16 @@ export class HandoverManager {
26
27
  handoverId;
27
28
  acceptedHandoverId;
28
29
  active = false;
30
+ sourcePeerId;
31
+ sourcePreparation;
32
+ sourceExit;
33
+ shutdownHooks;
29
34
  handoverRequestEnabled = false;
30
35
  handoverEnabled = true;
31
36
  forceStartEnabled = false;
32
- constructor(processName, processId, mqttProxy, unsMqttProxies, handoverRequestEnabled, handoverEnabled, forceStartEnabled, handoverId) {
37
+ constructor(processName, processId, mqttProxy, unsMqttProxies, handoverRequestEnabled, handoverEnabled, forceStartEnabled, handoverId, shutdownHooks) {
38
+ validateHandoverShutdown(shutdownHooks);
39
+ this.shutdownHooks = shutdownHooks ? { ...shutdownHooks } : undefined;
33
40
  this.processName = processName;
34
41
  this.processId = processId;
35
42
  this.mqttProxy = mqttProxy;
@@ -211,61 +218,102 @@ export class HandoverManager {
211
218
  /**
212
219
  * Handles handovers.
213
220
  */
221
+ exitSource(code) {
222
+ process.exit(code);
223
+ }
224
+ async prepareSourceHandover(response, event) {
225
+ const handoverId = this.getHandoverId(response, event);
226
+ logger.info(`${this.processName} - Received handover request from ${event.packet?.properties?.userProperties?.processName}. Accepting handover.`);
227
+ this.active = false;
228
+ this.event.emit("handoverManager", { active: false });
229
+ this.shutdownHooks?.onRelease?.();
230
+ // Set all UNS proxy instance subscribers to passive and drain the queue.
231
+ const mqttWorkerData = [];
232
+ for (let i = 0; i < this.unsMqttProxies.length; i++) {
233
+ const unsProxy = this.unsMqttProxies[i];
234
+ const workerData = await unsProxy.setSubscriberPassiveAndDrainQueue();
235
+ mqttWorkerData.push(workerData);
236
+ }
237
+ logger.info(`${this.processName} - Handover request accepted. Sending handover_subscriber messages.`);
238
+ // Publish handover_subscriber messages for each instance that has processed some data.
239
+ for (let i = 0; i < mqttWorkerData.length; i++) {
240
+ const workerData = mqttWorkerData[i];
241
+ if (workerData.batchSize > 0) {
242
+ await this.mqttProxy.publish(event.packet.properties?.responseTopic ?? "", this.handoverPayload("handover_subscriber", handoverId, {
243
+ batchSize: workerData.batchSize,
244
+ referenceHash: workerData.referenceHash,
245
+ instanceName: workerData.instanceName,
246
+ }), {
247
+ retain: false,
248
+ properties: {
249
+ responseTopic: this.topicBuilder.getHandoverTopic(),
250
+ userProperties: this.getUserProperties(handoverId),
251
+ },
252
+ });
253
+ }
254
+ }
255
+ logger.info(`${this.processName} - Handover subscriber messages sent.`);
256
+ // Publish a single handover acknowledgment only when all
257
+ // handover_subscriber messages have been sent
258
+ await this.mqttProxy.publish(event.packet.properties?.responseTopic ?? "", this.handoverPayload("handover_fin", handoverId), {
259
+ retain: false,
260
+ properties: {
261
+ responseTopic: this.topicBuilder.getHandoverTopic(),
262
+ userProperties: this.getUserProperties(handoverId),
263
+ },
264
+ });
265
+ logger.info(`${this.processName} - Handover fin message sent.`);
266
+ await Promise.all(this.unsMqttProxies.map((unsProxy) => unsProxy.stop()));
267
+ }
268
+ async finishSourceHandover() {
269
+ const result = await runHandoverShutdown(async () => {
270
+ await this.sourcePreparation;
271
+ await this.shutdownHooks?.drain();
272
+ }, this.shutdownHooks?.timeoutMs ?? 30_000);
273
+ this.handoverInProgress = false;
274
+ this.requestingHandover = false;
275
+ if (result === "completed") {
276
+ logger.info(`${this.processName} - Handover source drain completed. Exiting process.`);
277
+ this.exitSource(0);
278
+ }
279
+ else {
280
+ // Do not log application error text: it may contain paths, topics or credentials.
281
+ logger.error(`${this.processName} - Handover source drain ${result}. Exiting with incomplete drain.`);
282
+ this.exitSource(1);
283
+ }
284
+ }
214
285
  async handleHandover(event) {
215
286
  try {
216
287
  const response = JSON.parse(event.message.toString());
217
288
  // Responder process
218
289
  // Check if the message is a handover request and publish MULTIPLE handover_subscriber messages
219
290
  if (response.type === "handover_request") {
220
- const handoverId = this.getHandoverId(response, event);
221
- this.acceptedHandoverId = handoverId;
222
- logger.info(`${this.processName} - Received handover request from ${event.packet?.properties?.userProperties?.processName}. Accepting handover.`);
223
- // Set all UNS proxy instance subscribers to passive and drain the queue.
224
- const mqttWorkerData = [];
225
- for (let i = 0; i < this.unsMqttProxies.length; i++) {
226
- const unsProxy = this.unsMqttProxies[i];
227
- const workerData = await unsProxy.setSubscriberPassiveAndDrainQueue();
228
- mqttWorkerData.push(workerData);
291
+ const peerId = this.getSourceProcessId(event);
292
+ const replyTopic = event.packet?.properties?.responseTopic;
293
+ if (this.sourcePeerId || !this.active || !peerId || typeof replyTopic !== "string" || !replyTopic)
294
+ return;
295
+ this.sourcePeerId = peerId;
296
+ this.acceptedHandoverId = this.getHandoverId(response, event);
297
+ this.handoverInProgress = true;
298
+ clearTimeout(this.activeTimeout);
299
+ this.activeTimeout = undefined;
300
+ this.sourcePreparation = this.prepareSourceHandover(response, event);
301
+ try {
302
+ await this.sourcePreparation;
229
303
  }
230
- logger.info(`${this.processName} - Handover request accepted. Sending handover_subscriber messages.`);
231
- // Publish handover_subscriber messages for each instance that has processed some data.
232
- for (let i = 0; i < mqttWorkerData.length; i++) {
233
- const workerData = mqttWorkerData[i];
234
- if (workerData.batchSize > 0) {
235
- await this.mqttProxy.publish(event.packet.properties?.responseTopic ?? "", this.handoverPayload("handover_subscriber", handoverId, {
236
- batchSize: workerData.batchSize,
237
- referenceHash: workerData.referenceHash,
238
- instanceName: workerData.instanceName,
239
- }), {
240
- retain: false,
241
- properties: {
242
- responseTopic: this.topicBuilder.getHandoverTopic(),
243
- userProperties: this.getUserProperties(handoverId),
244
- },
245
- });
246
- }
304
+ catch {
305
+ // Subscriber transfer or onRelease failed; never report successful source completion.
306
+ logger.error(`${this.processName} - Handover source preparation failed. Exiting with incomplete drain.`);
307
+ if (!this.sourceExit)
308
+ this.exitSource(1);
247
309
  }
248
- logger.info(`${this.processName} - Handover subscriber messages sent.`);
249
- // Publish a single handover acknowledgment only when all
250
- // handover_subscriber messages have been sent
251
- this.active = false;
252
- this.event.emit("handoverManager", { active: this.active });
253
- await this.mqttProxy.publish(event.packet.properties?.responseTopic ?? "", this.handoverPayload("handover_fin", handoverId), {
254
- retain: false,
255
- properties: {
256
- responseTopic: this.topicBuilder.getHandoverTopic(),
257
- userProperties: this.getUserProperties(handoverId),
258
- },
259
- });
260
- logger.info(`${this.processName} - Handover fin message sent.`);
261
- this.handoverInProgress = false;
262
- this.requestingHandover = false;
263
- await Promise.all(this.unsMqttProxies.map((unsProxy) => unsProxy.stop()));
264
310
  }
265
311
  // Requestor process
266
312
  // Check if the message is one of the handover_subscriber message in response to handover_request
267
313
  // and publish a handover_ack message
268
314
  if (response.type === "handover_subscriber") {
315
+ if (this.sourcePeerId)
316
+ return;
269
317
  if (!this.acceptsHandoverResponse(this.getHandoverId(response, event)))
270
318
  return;
271
319
  // Find correct unsProxy instance for handover_subscriber and set it active
@@ -278,6 +326,8 @@ export class HandoverManager {
278
326
  // Requestor process
279
327
  // Check if the message is a handover_fin at the end of handover_subscriber messages
280
328
  if (response.type === "handover_fin") {
329
+ if (this.sourcePeerId)
330
+ return;
281
331
  const handoverId = this.getHandoverId(response, event);
282
332
  if (!this.acceptsHandoverResponse(handoverId))
283
333
  return;
@@ -306,16 +356,16 @@ export class HandoverManager {
306
356
  // Responder process
307
357
  // Check if the message is a handover_ack at the end of handover_fin messages
308
358
  if (response.type === "handover_ack") {
359
+ if (!this.sourcePreparation || this.getSourceProcessId(event) !== this.sourcePeerId)
360
+ return;
309
361
  const handoverId = this.getHandoverId(response, event);
310
362
  if (this.acceptedHandoverId && handoverId && this.acceptedHandoverId !== handoverId) {
311
363
  logger.warn(`${this.processName} - Ignoring acknowledgement for another migration.`);
312
364
  return;
313
365
  }
314
366
  logger.info(`${this.processName} - Received handover ack from ${event.packet?.properties?.userProperties?.processName}.`);
315
- this.handoverInProgress = false;
316
- this.requestingHandover = false;
317
- logger.info(`${this.processName} - Handover completed. Exiting process.`);
318
- process.exit(0);
367
+ this.sourceExit ??= this.finishSourceHandover();
368
+ await this.sourceExit;
319
369
  }
320
370
  }
321
371
  catch (error) {
@@ -1 +1 @@
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,SAAS,mBAAmB,CAAC,KAAc;IACzC,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAChD,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAChC,OAAO,UAAU,CAAC,MAAM,GAAG,CAAC,IAAI,UAAU,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC;AACpF,CAAC;AAED;;;;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;IACjC,UAAU,CAAqB;IACxC,kBAAkB,CAAqB;IACvC,MAAM,GAAY,KAAK,CAAC;IACzB,sBAAsB,GAAY,KAAK,CAAC;IACxC,eAAe,GAAY,IAAI,CAAC;IAChC,iBAAiB,GAAY,KAAK,CAAC;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CAAC,WAAW,+BAA+B,CAAC,CAAC;YAClE,CAAC;YAED,oBAAoB;YACpB,6EAA6E;YAC7E,IAAI,QAAQ,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;gBACrC,MAAM,UAAU,GAAG,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;gBACvD,IAAI,IAAI,CAAC,kBAAkB,IAAI,UAAU,IAAI,IAAI,CAAC,kBAAkB,KAAK,UAAU,EAAE,CAAC;oBACpF,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,WAAW,oDAAoD,CAAC,CAAC;oBACrF,OAAO;gBACT,CAAC;gBACD,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 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\nfunction normalizeHandoverId(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const normalized = value.trim();\n return normalized.length > 0 && normalized.length <= 128 ? normalized : undefined;\n}\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 readonly handoverId: string | undefined;\n private acceptedHandoverId: string | 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 handoverId?: string,\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 this.handoverId = normalizeHandoverId(handoverId);\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(handoverId?: string): Record<string, string> {\n const properties: Record<string, string> = {\n processName: this.processName,\n processId: this.processId,\n };\n const normalized = normalizeHandoverId(handoverId ?? this.handoverId);\n if (normalized) properties.handoverId = normalized;\n return properties;\n }\n\n private handoverPayload(\n type: string,\n handoverId?: string,\n fields: Record<string, unknown> = {},\n ): string {\n const normalized = normalizeHandoverId(handoverId ?? this.handoverId);\n return JSON.stringify({\n type,\n ...fields,\n ...(normalized ? { handoverId: normalized } : {}),\n });\n }\n\n private getHandoverId(response: unknown, event: UnsEvents[\"input\"]): string | undefined {\n const fromPayload = response && typeof response === \"object\" && !Array.isArray(response)\n ? (response as { handoverId?: unknown }).handoverId\n : undefined;\n if (typeof fromPayload === \"string\") return normalizeHandoverId(fromPayload);\n const fromProperties = event.packet?.properties?.userProperties?.handoverId;\n return typeof fromProperties === \"string\" ? normalizeHandoverId(fromProperties) : undefined;\n }\n\n private acceptsHandoverResponse(receivedHandoverId: string | undefined): boolean {\n if (!this.handoverId || !receivedHandoverId) {\n return true;\n }\n if (this.handoverId === receivedHandoverId) {\n return true;\n }\n logger.warn(`${this.processName} - Ignoring handover message for another migration.`);\n return false;\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, this.handoverPayload(\"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, this.handoverPayload(\"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 const handoverId = this.getHandoverId(response, event);\n this.acceptedHandoverId = handoverId;\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 this.handoverPayload(\"handover_subscriber\", handoverId, {\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(handoverId),\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 this.handoverPayload(\"handover_fin\", handoverId),\n {\n retain: false,\n properties: {\n responseTopic: this.topicBuilder.getHandoverTopic(),\n userProperties: this.getUserProperties(handoverId),\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 if (!this.acceptsHandoverResponse(this.getHandoverId(response, event))) return;\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 const handoverId = this.getHandoverId(response, event);\n if (!this.acceptsHandoverResponse(handoverId)) return;\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 this.handoverPayload(\"handover_ack\", handoverId),\n {\n retain: false,\n properties: {\n responseTopic: this.topicBuilder.getHandoverTopic(),\n userProperties: this.getUserProperties(handoverId),\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 const handoverId = this.getHandoverId(response, event);\n if (this.acceptedHandoverId && handoverId && this.acceptedHandoverId !== handoverId) {\n logger.warn(`${this.processName} - Ignoring acknowledgement for another migration.`);\n return;\n }\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;AAClC,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAA8B,MAAM,wBAAwB,CAAC;AAGnH,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAErE,OAAO,EAAE,2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0C,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QAC7F,CAAC;IACH,CAAC;CACF","sourcesContent":["import logger from \"../logger.js\";\nimport { runHandoverShutdown, validateHandoverShutdown, type HandoverShutdownHooks } from \"./handover-shutdown.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\nfunction normalizeHandoverId(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const normalized = value.trim();\n return normalized.length > 0 && normalized.length <= 128 ? normalized : undefined;\n}\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 readonly handoverId: string | undefined;\n private acceptedHandoverId: string | undefined;\n private active: boolean = false;\n private sourcePeerId: string | undefined;\n private sourcePreparation: Promise<void> | undefined;\n private sourceExit: Promise<void> | undefined;\n private readonly shutdownHooks: HandoverShutdownHooks | undefined;\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 handoverId?: string,\n shutdownHooks?: HandoverShutdownHooks,\n ) {\n validateHandoverShutdown(shutdownHooks);\n this.shutdownHooks = shutdownHooks ? { ...shutdownHooks } : undefined;\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 this.handoverId = normalizeHandoverId(handoverId);\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(handoverId?: string): Record<string, string> {\n const properties: Record<string, string> = {\n processName: this.processName,\n processId: this.processId,\n };\n const normalized = normalizeHandoverId(handoverId ?? this.handoverId);\n if (normalized) properties.handoverId = normalized;\n return properties;\n }\n\n private handoverPayload(\n type: string,\n handoverId?: string,\n fields: Record<string, unknown> = {},\n ): string {\n const normalized = normalizeHandoverId(handoverId ?? this.handoverId);\n return JSON.stringify({\n type,\n ...fields,\n ...(normalized ? { handoverId: normalized } : {}),\n });\n }\n\n private getHandoverId(response: unknown, event: UnsEvents[\"input\"]): string | undefined {\n const fromPayload = response && typeof response === \"object\" && !Array.isArray(response)\n ? (response as { handoverId?: unknown }).handoverId\n : undefined;\n if (typeof fromPayload === \"string\") return normalizeHandoverId(fromPayload);\n const fromProperties = event.packet?.properties?.userProperties?.handoverId;\n return typeof fromProperties === \"string\" ? normalizeHandoverId(fromProperties) : undefined;\n }\n\n private acceptsHandoverResponse(receivedHandoverId: string | undefined): boolean {\n if (!this.handoverId || !receivedHandoverId) {\n return true;\n }\n if (this.handoverId === receivedHandoverId) {\n return true;\n }\n logger.warn(`${this.processName} - Ignoring handover message for another migration.`);\n return false;\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, this.handoverPayload(\"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, this.handoverPayload(\"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 exitSource(code: number): void {\n process.exit(code);\n }\n\n private async prepareSourceHandover(response: any, event: UnsEvents[\"input\"]): Promise<void> {\n const handoverId = this.getHandoverId(response, event);\n\n logger.info(\n `${this.processName} - Received handover request from ${event.packet?.properties?.userProperties?.processName}. Accepting handover.`,\n );\n\n this.active = false;\n this.event.emit(\"handoverManager\", { active: false });\n this.shutdownHooks?.onRelease?.();\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 this.handoverPayload(\"handover_subscriber\", handoverId, {\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(handoverId),\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 await this.mqttProxy.publish(\n event.packet.properties?.responseTopic ?? \"\",\n this.handoverPayload(\"handover_fin\", handoverId),\n {\n retain: false,\n properties: {\n responseTopic: this.topicBuilder.getHandoverTopic(),\n userProperties: this.getUserProperties(handoverId),\n },\n },\n );\n logger.info(`${this.processName} - Handover fin message sent.`);\n\n await Promise.all(this.unsMqttProxies.map((unsProxy: UnsMqttProxy) => unsProxy.stop()));\n }\n\n private async finishSourceHandover(): Promise<void> {\n const result = await runHandoverShutdown(async () => {\n await this.sourcePreparation;\n await this.shutdownHooks?.drain();\n }, this.shutdownHooks?.timeoutMs ?? 30_000);\n this.handoverInProgress = false;\n this.requestingHandover = false;\n if (result === \"completed\") {\n logger.info(`${this.processName} - Handover source drain completed. Exiting process.`);\n this.exitSource(0);\n } else {\n // Do not log application error text: it may contain paths, topics or credentials.\n logger.error(`${this.processName} - Handover source drain ${result}. Exiting with incomplete drain.`);\n this.exitSource(1);\n }\n }\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 const peerId = this.getSourceProcessId(event);\n const replyTopic = event.packet?.properties?.responseTopic;\n if (this.sourcePeerId || !this.active || !peerId || typeof replyTopic !== \"string\" || !replyTopic) return;\n this.sourcePeerId = peerId;\n this.acceptedHandoverId = this.getHandoverId(response, event);\n this.handoverInProgress = true;\n clearTimeout(this.activeTimeout);\n this.activeTimeout = undefined;\n this.sourcePreparation = this.prepareSourceHandover(response, event);\n try {\n await this.sourcePreparation;\n } catch {\n // Subscriber transfer or onRelease failed; never report successful source completion.\n logger.error(`${this.processName} - Handover source preparation failed. Exiting with incomplete drain.`);\n if (!this.sourceExit) this.exitSource(1);\n }\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 if (this.sourcePeerId) return;\n if (!this.acceptsHandoverResponse(this.getHandoverId(response, event))) return;\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 if (this.sourcePeerId) return;\n const handoverId = this.getHandoverId(response, event);\n if (!this.acceptsHandoverResponse(handoverId)) return;\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 this.handoverPayload(\"handover_ack\", handoverId),\n {\n retain: false,\n properties: {\n responseTopic: this.topicBuilder.getHandoverTopic(),\n userProperties: this.getUserProperties(handoverId),\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 if (!this.sourcePreparation || this.getSourceProcessId(event) !== this.sourcePeerId) return;\n const handoverId = this.getHandoverId(response, event);\n if (this.acceptedHandoverId && handoverId && this.acceptedHandoverId !== handoverId) {\n logger.warn(`${this.processName} - Ignoring acknowledgement for another migration.`);\n return;\n }\n logger.info(`${this.processName} - Received handover ack from ${event.packet?.properties?.userProperties?.processName}.`);\n this.sourceExit ??= this.finishSourceHandover();\n await this.sourceExit;\n }\n } catch (error) {\n logger.error(`${this.processName} - Error processing handover response: ${error.message}`);\n }\n }\n}\n"]}
@@ -0,0 +1,14 @@
1
+ /** Application-owned work is separate from the MQTT subscriber handover. */
2
+ export interface HandoverShutdownHooks {
3
+ /** Synchronous: stop admitting new background work when releasing ownership. */
4
+ onRelease?: () => void;
5
+ /** After target acknowledgement: finish accepted work and close writers. Never call process.exit here. */
6
+ drain: () => Promise<void>;
7
+ /** Total time for remaining proxy stops and application drain; default 30 seconds. */
8
+ timeoutMs?: number;
9
+ }
10
+ export declare function validateHandoverShutdown(hooks?: HandoverShutdownHooks): void;
11
+ export type HandoverShutdownResult = "completed" | "failed" | "timed-out";
12
+ /** A timeout does not cancel IO or prove durability. The process owner must exit nonzero. */
13
+ export declare function runHandoverShutdown(work: () => Promise<void>, timeoutMs?: number): Promise<HandoverShutdownResult>;
14
+ //# sourceMappingURL=handover-shutdown.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handover-shutdown.d.ts","sourceRoot":"","sources":["../../src/uns/handover-shutdown.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,MAAM,WAAW,qBAAqB;IACpC,gFAAgF;IAChF,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;IACvB,0GAA0G;IAC1G,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3B,sFAAsF;IACtF,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,wBAAgB,wBAAwB,CAAC,KAAK,CAAC,EAAE,qBAAqB,GAAG,IAAI,CAS5E;AAED,MAAM,MAAM,sBAAsB,GAAG,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;AAE1E,6FAA6F;AAC7F,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,EAAE,SAAS,SAAS,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAiBxH"}
@@ -0,0 +1,30 @@
1
+ export function validateHandoverShutdown(hooks) {
2
+ if (!hooks)
3
+ return;
4
+ if (typeof hooks.drain !== "function" || (hooks.onRelease !== undefined && typeof hooks.onRelease !== "function")) {
5
+ throw new TypeError("Invalid handover shutdown hooks.");
6
+ }
7
+ const timeout = hooks.timeoutMs ?? 30_000;
8
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 300_000) {
9
+ throw new RangeError("Handover shutdown timeout must be between 1 and 300000 milliseconds.");
10
+ }
11
+ }
12
+ /** A timeout does not cancel IO or prove durability. The process owner must exit nonzero. */
13
+ export async function runHandoverShutdown(work, timeoutMs = 30_000) {
14
+ let timer;
15
+ try {
16
+ return await Promise.race([
17
+ Promise.resolve()
18
+ .then(work)
19
+ .then(() => "completed", () => "failed"),
20
+ new Promise((resolve) => {
21
+ timer = setTimeout(() => resolve("timed-out"), timeoutMs);
22
+ }),
23
+ ]);
24
+ }
25
+ finally {
26
+ if (timer)
27
+ clearTimeout(timer);
28
+ }
29
+ }
30
+ //# sourceMappingURL=handover-shutdown.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handover-shutdown.js","sourceRoot":"","sources":["../../src/uns/handover-shutdown.ts"],"names":[],"mappings":"AAUA,MAAM,UAAU,wBAAwB,CAAC,KAA6B;IACpE,IAAI,CAAC,KAAK;QAAE,OAAO;IACnB,IAAI,OAAO,KAAK,CAAC,KAAK,KAAK,UAAU,IAAI,CAAC,KAAK,CAAC,SAAS,KAAK,SAAS,IAAI,OAAO,KAAK,CAAC,SAAS,KAAK,UAAU,CAAC,EAAE,CAAC;QAClH,MAAM,IAAI,SAAS,CAAC,kCAAkC,CAAC,CAAC;IAC1D,CAAC;IACD,MAAM,OAAO,GAAG,KAAK,CAAC,SAAS,IAAI,MAAM,CAAC;IAC1C,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,OAAO,GAAG,CAAC,IAAI,OAAO,GAAG,OAAO,EAAE,CAAC;QACnE,MAAM,IAAI,UAAU,CAAC,sEAAsE,CAAC,CAAC;IAC/F,CAAC;AACH,CAAC;AAID,6FAA6F;AAC7F,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAC,IAAyB,EAAE,SAAS,GAAG,MAAM;IACrF,IAAI,KAAgD,CAAC;IACrD,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC;YACxB,OAAO,CAAC,OAAO,EAAE;iBACd,IAAI,CAAC,IAAI,CAAC;iBACV,IAAI,CACH,GAAG,EAAE,CAAC,WAAoB,EAC1B,GAAG,EAAE,CAAC,QAAiB,CACxB;YACH,IAAI,OAAO,CAAc,CAAC,OAAO,EAAE,EAAE;gBACnC,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,WAAW,CAAC,EAAE,SAAS,CAAC,CAAC;YAC5D,CAAC,CAAC;SACH,CAAC,CAAC;IACL,CAAC;YAAS,CAAC;QACT,IAAI,KAAK;YAAE,YAAY,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;AACH,CAAC","sourcesContent":["/** Application-owned work is separate from the MQTT subscriber handover. */\nexport interface HandoverShutdownHooks {\n /** Synchronous: stop admitting new background work when releasing ownership. */\n onRelease?: () => void;\n /** After target acknowledgement: finish accepted work and close writers. Never call process.exit here. */\n drain: () => Promise<void>;\n /** Total time for remaining proxy stops and application drain; default 30 seconds. */\n timeoutMs?: number;\n}\n\nexport function validateHandoverShutdown(hooks?: HandoverShutdownHooks): void {\n if (!hooks) return;\n if (typeof hooks.drain !== \"function\" || (hooks.onRelease !== undefined && typeof hooks.onRelease !== \"function\")) {\n throw new TypeError(\"Invalid handover shutdown hooks.\");\n }\n const timeout = hooks.timeoutMs ?? 30_000;\n if (!Number.isInteger(timeout) || timeout < 1 || timeout > 300_000) {\n throw new RangeError(\"Handover shutdown timeout must be between 1 and 300000 milliseconds.\");\n }\n}\n\nexport type HandoverShutdownResult = \"completed\" | \"failed\" | \"timed-out\";\n\n/** A timeout does not cancel IO or prove durability. The process owner must exit nonzero. */\nexport async function runHandoverShutdown(work: () => Promise<void>, timeoutMs = 30_000): Promise<HandoverShutdownResult> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n Promise.resolve()\n .then(work)\n .then(\n () => \"completed\" as const,\n () => \"failed\" as const,\n ),\n new Promise<\"timed-out\">((resolve) => {\n timer = setTimeout(() => resolve(\"timed-out\"), timeoutMs);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import type { HandoverShutdownHooks } from "./handover-shutdown.js";
1
2
  import { UnsAttributeType } from "../graphql/schema.js";
2
3
  import { MeasurementUnit } from "./uns-measurements.js";
3
4
  import { UnsTags } from "./uns-tags.js";
@@ -80,6 +81,8 @@ export interface IUnsParameters {
80
81
  defaultPublishOptions?: IMqttPublishOptions;
81
82
  }
82
83
  export interface IUnsProcessParameters {
84
+ /** Optional application drain after a cooperative handover. Register before creating proxies. */
85
+ handoverShutdown?: HandoverShutdownHooks;
83
86
  processName: string;
84
87
  /**
85
88
  * Optional controller-supplied correlation id for one cooperative handover.