@uns-kit/core 1.0.7 → 1.0.9
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/README.md +18 -0
- package/dist/tools/generate-uns-dictionary.d.ts +3 -0
- package/dist/tools/generate-uns-dictionary.d.ts.map +1 -0
- package/dist/tools/generate-uns-dictionary.js +270 -0
- package/dist/tools/generate-uns-dictionary.js.map +1 -0
- package/dist/tools/initialize.d.ts.map +1 -0
- package/dist/tools/initialize.js.map +1 -0
- package/dist/tools/make.d.ts.map +1 -0
- package/dist/tools/make.js.map +1 -0
- package/dist/tools/update-rtt.d.ts.map +1 -0
- package/dist/tools/update-rtt.js.map +1 -0
- package/dist/tools/update-tools.d.ts.map +1 -0
- package/dist/tools/update-tools.js.map +1 -0
- package/dist/uns/uns-attributes.d.ts +6 -143
- package/dist/uns/uns-attributes.d.ts.map +1 -1
- package/dist/uns/uns-attributes.js +7 -180
- package/dist/uns/uns-attributes.js.map +1 -1
- package/dist/uns/uns-dictionary.generated.d.ts +83 -0
- package/dist/uns/uns-dictionary.generated.d.ts.map +1 -0
- package/dist/uns/uns-dictionary.generated.js +160 -0
- package/dist/uns/uns-dictionary.generated.js.map +1 -0
- package/dist/uns/uns-interfaces.d.ts +4 -0
- package/dist/uns/uns-interfaces.d.ts.map +1 -1
- package/dist/uns/uns-interfaces.js.map +1 -1
- package/dist/uns/uns-object.d.ts +14 -38
- package/dist/uns/uns-object.d.ts.map +1 -1
- package/dist/uns/uns-object.js +4 -61
- package/dist/uns/uns-object.js.map +1 -1
- package/dist/uns/uns-proxy.d.ts.map +1 -1
- package/dist/uns/uns-proxy.js +2 -0
- package/dist/uns/uns-proxy.js.map +1 -1
- package/dist/uns-grpc/uns-gateway-server.js +1 -1
- package/dist/uns-grpc/uns-gateway-server.js.map +1 -1
- package/dist/uns-mqtt/uns-mqtt-proxy.d.ts.map +1 -1
- package/dist/uns-mqtt/uns-mqtt-proxy.js +4 -1
- package/dist/uns-mqtt/uns-mqtt-proxy.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uns-object.d.ts","sourceRoot":"","sources":["../../src/uns/uns-object.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"uns-object.d.ts","sourceRoot":"","sources":["../../src/uns/uns-object.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAErE,eAAO,MAAM,WAAW;;;;;;;;;;;;;CAAuB,CAAC;AAEhD,MAAM,MAAM,sBAAsB,GAAG,MAAM,OAAO,oBAAoB,CAAC;AAEvE,MAAM,MAAM,aAAa,GAAG,EAAE,GAAG,sBAAsB,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;AAGxE,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,EAAE,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC"}
|
package/dist/uns/uns-object.js
CHANGED
|
@@ -1,62 +1,5 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
"personnel",
|
|
6
|
-
"process-segment",
|
|
7
|
-
"product-definition",
|
|
8
|
-
"product-quality",
|
|
9
|
-
"work-definition",
|
|
10
|
-
"resource-status",
|
|
11
|
-
"energy-resource",
|
|
12
|
-
"utility-resource",
|
|
13
|
-
"fluid-resource",
|
|
14
|
-
"consumable-resource",
|
|
15
|
-
// Common structural/legacy types used in templates/examples
|
|
16
|
-
"line",
|
|
17
|
-
"area",
|
|
18
|
-
"site",
|
|
19
|
-
"enterprise",
|
|
20
|
-
"asset",
|
|
21
|
-
"sensor",
|
|
22
|
-
];
|
|
23
|
-
// Convenient constants for IntelliSense and to avoid string literals.
|
|
24
|
-
export const ObjectTypes = {
|
|
25
|
-
/** Physical equipment (machines, furnaces, sensors) */
|
|
26
|
-
Equipment: "equipment",
|
|
27
|
-
/** Material lots/batches/raw materials */
|
|
28
|
-
Material: "material",
|
|
29
|
-
/** Operators/supervisors/technologists */
|
|
30
|
-
Personnel: "personnel",
|
|
31
|
-
/** Process step or activity (e.g., rolling, cooling) */
|
|
32
|
-
ProcessSegment: "process-segment",
|
|
33
|
-
/** Product specs/recipes/definitions */
|
|
34
|
-
ProductDefinition: "product-definition",
|
|
35
|
-
/** Quality indicators/results for a product */
|
|
36
|
-
ProductQuality: "product-quality",
|
|
37
|
-
/** Work/task definitions or workflows */
|
|
38
|
-
WorkDefinition: "work-definition",
|
|
39
|
-
/** Status of any resource (material/personnel/equipment) */
|
|
40
|
-
ResourceStatus: "resource-status",
|
|
41
|
-
/** Energy carriers (electricity/steam/gas) */
|
|
42
|
-
EnergyResource: "energy-resource",
|
|
43
|
-
/** Utilities (water/air/nitrogen/etc.) */
|
|
44
|
-
UtilityResource: "utility-resource",
|
|
45
|
-
/** Fluids/gases (non-energy) used in process */
|
|
46
|
-
FluidResource: "fluid-resource",
|
|
47
|
-
/** Consumables (lubricants/cleaners) */
|
|
48
|
-
ConsumableResource: "consumable-resource",
|
|
49
|
-
/** Production line/work unit */
|
|
50
|
-
Line: "line",
|
|
51
|
-
/** Area/department within a site */
|
|
52
|
-
Area: "area",
|
|
53
|
-
/** Plant/site identifier */
|
|
54
|
-
Site: "site",
|
|
55
|
-
/** Enterprise/company identifier */
|
|
56
|
-
Enterprise: "enterprise",
|
|
57
|
-
/** Generic asset placeholder */
|
|
58
|
-
Asset: "asset",
|
|
59
|
-
/** Sensor as a distinct object */
|
|
60
|
-
Sensor: "sensor",
|
|
61
|
-
};
|
|
1
|
+
// Slimmed: use generated dictionary as the source of object types.
|
|
2
|
+
// Ensure generate-uns-dictionary is run (or provide your own generated file).
|
|
3
|
+
import { GeneratedObjectTypes } from "./uns-dictionary.generated.js";
|
|
4
|
+
export const ObjectTypes = GeneratedObjectTypes;
|
|
62
5
|
//# sourceMappingURL=uns-object.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uns-object.js","sourceRoot":"","sources":["../../src/uns/uns-object.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"uns-object.js","sourceRoot":"","sources":["../../src/uns/uns-object.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,8EAA8E;AAC9E,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAErE,MAAM,CAAC,MAAM,WAAW,GAAG,oBAAoB,CAAC","sourcesContent":["// Slimmed: use generated dictionary as the source of object types.\n// Ensure generate-uns-dictionary is run (or provide your own generated file).\nimport { GeneratedObjectTypes } from \"./uns-dictionary.generated.js\";\n\nexport const ObjectTypes = GeneratedObjectTypes;\n\nexport type KnownUnsObjectTypeName = keyof typeof GeneratedObjectTypes;\n\nexport type UnsObjectType = \"\" | KnownUnsObjectTypeName | (string & {});\n\n// Default object id is \"main\" when none is provided.\nexport type UnsObjectId = \"main\" | \"\" | (string & {});\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uns-proxy.d.ts","sourceRoot":"","sources":["../../src/uns/uns-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAE1E,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAE7D,MAAM,CAAC,OAAO,OAAO,QAAQ;IAC3B,OAAO,CAAC,eAAe,CAA+B;IAC/C,KAAK,EAAE,eAAe,CAAC,SAAS,CAAC,CAAoC;IAC5E,SAAS,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACtC,SAAS,CAAC,sBAAsB,EAAE,MAAM,CAAC;IACzC,OAAO,CAAC,cAAc,CAAwC;IAC9D,OAAO,CAAC,oBAAoB,CAAsC;;IAUlE;;OAEG;YACW,kBAAkB;IAgBhC;;OAEG;YACW,wBAAwB;IAgBtC;;;;OAIG;IACH,SAAS,CAAC,mBAAmB,CAAC,WAAW,EAAE,YAAY,GAAG,IAAI;
|
|
1
|
+
{"version":3,"file":"uns-proxy.d.ts","sourceRoot":"","sources":["../../src/uns/uns-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAE1E,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAE7D,MAAM,CAAC,OAAO,OAAO,QAAQ;IAC3B,OAAO,CAAC,eAAe,CAA+B;IAC/C,KAAK,EAAE,eAAe,CAAC,SAAS,CAAC,CAAoC;IAC5E,SAAS,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACtC,SAAS,CAAC,sBAAsB,EAAE,MAAM,CAAC;IACzC,OAAO,CAAC,cAAc,CAAwC;IAC9D,OAAO,CAAC,oBAAoB,CAAsC;;IAUlE;;OAEG;YACW,kBAAkB;IAgBhC;;OAEG;YACW,wBAAwB;IAgBtC;;;;OAIG;IACH,SAAS,CAAC,mBAAmB,CAAC,WAAW,EAAE,YAAY,GAAG,IAAI;IAyB9D;;OAEG;IACH,SAAS,CAAC,mBAAmB,CAAC,SAAS,EAAE,UAAU,GAAG,IAAI;IA0B1D,SAAS,CAAC,qBAAqB,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAC,QAAQ,EAAE,UAAU,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,GAAG,IAAI;IAQ5H,IAAI;CASlB"}
|
package/dist/uns/uns-proxy.js
CHANGED
|
@@ -72,7 +72,9 @@ export default class UnsProxy {
|
|
|
72
72
|
attributeNeedsPersistence: topicObject.attributeNeedsPersistence ?? true,
|
|
73
73
|
dataGroup: topicObject.dataGroup ?? "",
|
|
74
74
|
asset: topicObject.asset,
|
|
75
|
+
assetDescription: topicObject.assetDescription,
|
|
75
76
|
objectType: topicObject.objectType,
|
|
77
|
+
objectTypeDescription: topicObject.objectTypeDescription,
|
|
76
78
|
objectId: topicObject.objectId
|
|
77
79
|
});
|
|
78
80
|
this.emitProducedTopics();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uns-proxy.js","sourceRoot":"","sources":["../../src/uns/uns-proxy.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAI5C,MAAM,CAAC,OAAO,OAAO,QAAQ;IACnB,eAAe,GAA0B,IAAI,CAAC;IAC/C,KAAK,GAA+B,IAAI,eAAe,EAAa,CAAC;IAClE,mBAAmB,CAAS;IAC5B,sBAAsB,CAAS,CAAC,UAAU;IAC5C,cAAc,GAA8B,IAAI,GAAG,EAAE,CAAC;IACtD,oBAAoB,GAA4B,IAAI,GAAG,EAAE,CAAC;IAElE;QACE,+DAA+D;QAC/D,IAAI,CAAC,eAAe,GAAG,WAAW,CAAC,GAAG,EAAE;YACtC,IAAI,CAAC,kBAAkB,EAAE,CAAC;YAC1B,IAAI,CAAC,wBAAwB,EAAE,CAAC;QAClC,CAAC,EAAE,KAAK,CAAC,CAAC;IACZ,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,kBAAkB;QAC9B,IAAI,IAAI,CAAC,mBAAmB,KAAK,EAAE,EAAE,CAAC;YACpC,MAAM,WAAW,GAAG,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC;YACtD,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC3B,IAAI,CAAC;oBACH,IAAI,WAAW,CAAC,MAA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I,CAAC,wBAAwB,EAAE,CAAC;YAChC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,sBAAsB,iCAAiC,SAAS,EAAE,CAAC,CAAC;QAC1F,CAAC;IACH,CAAC;IACM,KAAK,CAAC,IAAI;QACf,iCAAiC;QACjC,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACzB,aAAa,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YACpC,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC;QAC9B,CAAC;IAEH,CAAC;CAEF","sourcesContent":["import { IApiObject, ITopicObject, UnsEvents } from \"./uns-interfaces.js\";\nimport logger from \"../logger.js\";\nimport { UnsEventEmitter } from \"./uns-event-emitter.js\";\nimport { UnsPacket } from \"./uns-packet.js\";\nimport { UnsAsset } from \"./uns-asset.js\";\nimport { UnsObjectId, UnsObjectType } from \"./uns-object.js\";\n\nexport default class UnsProxy {\n private publishInterval: NodeJS.Timeout | null = null;\n public event: UnsEventEmitter<UnsEvents> = new UnsEventEmitter<UnsEvents>();\n protected instanceStatusTopic: string;\n protected instanceNameWithSuffix: string; //was prot\n private producedTopics: Map<string, ITopicObject> = new Map();\n private producedApiEndpoints: Map<string, IApiObject> = new Map();\n\n constructor() {\n // Set up interval to publish produced topics every 60 seconds.\n this.publishInterval = setInterval(() => {\n this.emitProducedTopics();\n this.emitProducedApiEndpoints();\n }, 60000); \n }\n \n /**\n * Publishes the list of produced topics to the MQTT broker.\n */\n private async emitProducedTopics(): Promise<void> {\n if (this.instanceStatusTopic !== \"\") {\n const topicsArray = [...this.producedTopics.values()];\n if (topicsArray.length > 0) {\n try {\n if (topicsArray.length > 0) {\n this.event.emit(\"unsProxyProducedTopics\", { producedTopics: topicsArray, statusTopic: this.instanceStatusTopic + \"topics\" });\n }\n } catch (error) {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing produced topics: ${error.message}`);\n }\n logger.debug(`${this.instanceNameWithSuffix} - Published produced topics.`);\n }\n }\n }\n\n /**\n * Publishes the list of produced API endpoints to the MQTT broker.\n */\n private async emitProducedApiEndpoints(): Promise<void> {\n if (this.instanceStatusTopic !== \"\") {\n const apiEndpointsArray = [...this.producedApiEndpoints.values()];\n if (apiEndpointsArray.length > 0) {\n try {\n if (apiEndpointsArray.length > 0) {\n this.event.emit(\"unsProxyProducedApiEndpoints\", { producedApiEndpoints: apiEndpointsArray, statusTopic: this.instanceStatusTopic + \"api-endpoints\" });\n }\n } catch (error) {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing produced API endpoints: ${error.message}`);\n }\n logger.debug(`${this.instanceNameWithSuffix} - Published produced API endpoints.`);\n }\n }\n }\n\n /**\n * Registers a unique topic so that it is tracked and published only once.\n *\n * @param topicObject - The object containing topic details.\n */\n protected registerUniqueTopic(topicObject: ITopicObject): void {\n if (this.instanceStatusTopic !== \"\") {\n const fullTopic = `${topicObject.topic}${topicObject.asset}/${topicObject.objectType}/${topicObject.objectId}/${topicObject.attribute}`;\n if (!this.producedTopics.has(fullTopic)) {\n this.producedTopics.set(fullTopic, {\n timestamp: topicObject.timestamp,\n topic: topicObject.topic,\n attribute: topicObject.attribute,\n attributeType: topicObject.attributeType,\n description: topicObject.description,\n tags: topicObject.tags,\n attributeNeedsPersistence: topicObject.attributeNeedsPersistence ?? true,\n dataGroup: topicObject.dataGroup ?? \"\",\n asset: topicObject.asset,\n objectType: topicObject.objectType,\n objectId: topicObject.objectId\n });\n this.emitProducedTopics();\n logger.info(`${this.instanceNameWithSuffix} - Registered new topic: ${fullTopic}`);\n }\n }\n } \n\n /**\n * Registers an API endpoint to handle requests for a specific topic and attribute.\n */\n protected registerApiEndpoint(apiObject: IApiObject): void {\n if (this.instanceStatusTopic !== \"\") {\n const fullTopic = `${apiObject.topic}${apiObject.asset}/${apiObject.objectType}/${apiObject.objectId}/${apiObject.attribute}`;\n if (!this.producedApiEndpoints.has(fullTopic)) {\n const time = UnsPacket.formatToISO8601(new Date());\n this.producedApiEndpoints.set(fullTopic, {\n timestamp: time,\n topic: apiObject.topic,\n attribute: apiObject.attribute,\n apiHost: apiObject.apiHost,\n apiEndpoint: apiObject.apiEndpoint,\n apiMethod: apiObject.apiMethod,\n apiQueryParams: apiObject.apiQueryParams,\n apiDescription: apiObject.apiDescription,\n attributeType: apiObject.attributeType,\n apiSwaggerEndpoint: apiObject.apiSwaggerEndpoint,\n asset: apiObject.asset,\n objectType: apiObject.objectType,\n objectId: apiObject.objectId\n });\n this.emitProducedApiEndpoints();\n logger.info(`${this.instanceNameWithSuffix} - Registered new api endpoint: /${fullTopic}`);\n }\n }\n }\n\n protected unregisterApiEndpoint(topic: string, asset:UnsAsset, objectType: UnsObjectType, objectId: UnsObjectId, attribute: string): void {\n const fullTopic = `${topic}/${asset}/${objectType}/${objectId}/${attribute}`;\n if (this.producedApiEndpoints.has(fullTopic)) {\n this.producedApiEndpoints.delete(fullTopic);\n this.emitProducedApiEndpoints();\n logger.info(`${this.instanceNameWithSuffix} - Unregistered API endpoint: ${fullTopic}`);\n }\n }\n public async stop() {\n // Clear the publishing interval.\n if (this.publishInterval) {\n clearInterval(this.publishInterval);\n this.publishInterval = null;\n }\n\n }\n\n}\n"]}
|
|
1
|
+
{"version":3,"file":"uns-proxy.js","sourceRoot":"","sources":["../../src/uns/uns-proxy.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAI5C,MAAM,CAAC,OAAO,OAAO,QAAQ;IACnB,eAAe,GAA0B,IAAI,CAAC;IAC/C,KAAK,GAA+B,IAAI,eAAe,EAAa,CAAC;IAClE,mBAAmB,CAAS;IAC5B,sBAAsB,CAAS,CAAC,UAAU;IAC5C,cAAc,GAA8B,IAAI,GAAG,EAAE,CAAC;IACtD,oBAAoB,GAA4B,IAAI,GAAG,EAAE,CAAC;IAElE;QACE,+DAA+D;QAC/D,IA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AQ,EAAE,SAAS,CAAC,QAAQ;iBAC7B,CAAC,CAAC;gBACH,IAAI,CAAC,wBAAwB,EAAE,CAAC;gBAChC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,sBAAsB,oCAAoC,SAAS,EAAE,CAAC,CAAC;YAC7F,CAAC;QACH,CAAC;IACH,CAAC;IAES,qBAAqB,CAAC,KAAa,EAAE,KAAc,EAAE,UAAyB,EAAE,QAAqB,EAAE,SAAiB;QAChI,MAAM,SAAS,GAAG,GAAG,KAAK,IAAI,KAAK,IAAI,UAAU,IAAI,QAAQ,IAAI,SAAS,EAAE,CAAC;QAC7E,IAAI,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC;YAC7C,IAAI,CAAC,oBAAoB,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;YAC5C,IAAI,CAAC,wBAAwB,EAAE,CAAC;YAChC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,sBAAsB,iCAAiC,SAAS,EAAE,CAAC,CAAC;QAC1F,CAAC;IACH,CAAC;IACM,KAAK,CAAC,IAAI;QACf,iCAAiC;QACjC,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACzB,aAAa,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YACpC,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC;QAC9B,CAAC;IAEH,CAAC;CAEF","sourcesContent":["import { IApiObject, ITopicObject, UnsEvents } from \"./uns-interfaces.js\";\nimport logger from \"../logger.js\";\nimport { UnsEventEmitter } from \"./uns-event-emitter.js\";\nimport { UnsPacket } from \"./uns-packet.js\";\nimport { UnsAsset } from \"./uns-asset.js\";\nimport { UnsObjectId, UnsObjectType } from \"./uns-object.js\";\n\nexport default class UnsProxy {\n private publishInterval: NodeJS.Timeout | null = null;\n public event: UnsEventEmitter<UnsEvents> = new UnsEventEmitter<UnsEvents>();\n protected instanceStatusTopic: string;\n protected instanceNameWithSuffix: string; //was prot\n private producedTopics: Map<string, ITopicObject> = new Map();\n private producedApiEndpoints: Map<string, IApiObject> = new Map();\n\n constructor() {\n // Set up interval to publish produced topics every 60 seconds.\n this.publishInterval = setInterval(() => {\n this.emitProducedTopics();\n this.emitProducedApiEndpoints();\n }, 60000); \n }\n \n /**\n * Publishes the list of produced topics to the MQTT broker.\n */\n private async emitProducedTopics(): Promise<void> {\n if (this.instanceStatusTopic !== \"\") {\n const topicsArray = [...this.producedTopics.values()];\n if (topicsArray.length > 0) {\n try {\n if (topicsArray.length > 0) {\n this.event.emit(\"unsProxyProducedTopics\", { producedTopics: topicsArray, statusTopic: this.instanceStatusTopic + \"topics\" });\n }\n } catch (error) {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing produced topics: ${error.message}`);\n }\n logger.debug(`${this.instanceNameWithSuffix} - Published produced topics.`);\n }\n }\n }\n\n /**\n * Publishes the list of produced API endpoints to the MQTT broker.\n */\n private async emitProducedApiEndpoints(): Promise<void> {\n if (this.instanceStatusTopic !== \"\") {\n const apiEndpointsArray = [...this.producedApiEndpoints.values()];\n if (apiEndpointsArray.length > 0) {\n try {\n if (apiEndpointsArray.length > 0) {\n this.event.emit(\"unsProxyProducedApiEndpoints\", { producedApiEndpoints: apiEndpointsArray, statusTopic: this.instanceStatusTopic + \"api-endpoints\" });\n }\n } catch (error) {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing produced API endpoints: ${error.message}`);\n }\n logger.debug(`${this.instanceNameWithSuffix} - Published produced API endpoints.`);\n }\n }\n }\n\n /**\n * Registers a unique topic so that it is tracked and published only once.\n *\n * @param topicObject - The object containing topic details.\n */\n protected registerUniqueTopic(topicObject: ITopicObject): void {\n if (this.instanceStatusTopic !== \"\") {\n const fullTopic = `${topicObject.topic}${topicObject.asset}/${topicObject.objectType}/${topicObject.objectId}/${topicObject.attribute}`;\n if (!this.producedTopics.has(fullTopic)) {\n this.producedTopics.set(fullTopic, {\n timestamp: topicObject.timestamp,\n topic: topicObject.topic,\n attribute: topicObject.attribute,\n attributeType: topicObject.attributeType,\n description: topicObject.description,\n tags: topicObject.tags,\n attributeNeedsPersistence: topicObject.attributeNeedsPersistence ?? true,\n dataGroup: topicObject.dataGroup ?? \"\",\n asset: topicObject.asset,\n assetDescription: topicObject.assetDescription,\n objectType: topicObject.objectType,\n objectTypeDescription: topicObject.objectTypeDescription,\n objectId: topicObject.objectId\n });\n this.emitProducedTopics();\n logger.info(`${this.instanceNameWithSuffix} - Registered new topic: ${fullTopic}`);\n }\n }\n } \n\n /**\n * Registers an API endpoint to handle requests for a specific topic and attribute.\n */\n protected registerApiEndpoint(apiObject: IApiObject): void {\n if (this.instanceStatusTopic !== \"\") {\n const fullTopic = `${apiObject.topic}${apiObject.asset}/${apiObject.objectType}/${apiObject.objectId}/${apiObject.attribute}`;\n if (!this.producedApiEndpoints.has(fullTopic)) {\n const time = UnsPacket.formatToISO8601(new Date());\n this.producedApiEndpoints.set(fullTopic, {\n timestamp: time,\n topic: apiObject.topic,\n attribute: apiObject.attribute,\n apiHost: apiObject.apiHost,\n apiEndpoint: apiObject.apiEndpoint,\n apiMethod: apiObject.apiMethod,\n apiQueryParams: apiObject.apiQueryParams,\n apiDescription: apiObject.apiDescription,\n attributeType: apiObject.attributeType,\n apiSwaggerEndpoint: apiObject.apiSwaggerEndpoint,\n asset: apiObject.asset,\n objectType: apiObject.objectType,\n objectId: apiObject.objectId\n });\n this.emitProducedApiEndpoints();\n logger.info(`${this.instanceNameWithSuffix} - Registered new api endpoint: /${fullTopic}`);\n }\n }\n }\n\n protected unregisterApiEndpoint(topic: string, asset:UnsAsset, objectType: UnsObjectType, objectId: UnsObjectId, attribute: string): void {\n const fullTopic = `${topic}/${asset}/${objectType}/${objectId}/${attribute}`;\n if (this.producedApiEndpoints.has(fullTopic)) {\n this.producedApiEndpoints.delete(fullTopic);\n this.emitProducedApiEndpoints();\n logger.info(`${this.instanceNameWithSuffix} - Unregistered API endpoint: ${fullTopic}`);\n }\n }\n public async stop() {\n // Clear the publishing interval.\n if (this.publishInterval) {\n clearInterval(this.publishInterval);\n this.publishInterval = null;\n }\n\n }\n\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uns-gateway-server.js","sourceRoot":"","sources":["../../src/uns-grpc/uns-gateway-server.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,eAAe,CAAC;AACjC,OAAO,WAAW,MAAM,oBAAoB,CAAC;AAC7C,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,OAAO,MAAM,UAAU,CAAC;AAC/B,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,eAAe,MAAM,6BAA6B,CAAC;AAC1D,OAAqB,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEjD,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AACrE,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAClD,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;AAE3C,MAAM,mBAAmB,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,mBAAmB,CAAC,CAAC;AACzE,MAAM,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB;IACjD,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAA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,CAAC,IAAI,CAAC,MAAO,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;gBAChF,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;YACrB,CAAC;YACD,IAAI,IAAI,CAAC,UAAU;gBAAE,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC;QAClD,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,MAAM,CAAC,KAAK,CAAC,2BAA2B,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;CACF;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,YAAqB,EAAE,IAA0B;IACrF,MAAM,EAAE,GAAG,IAAI,gBAAgB,EAAE,CAAC;IAClC,OAAO,EAAE,CAAC,KAAK,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;AACtC,CAAC;AACD,SAAS,iBAAiB,CAAC,cAA4B;IACrD,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import grpc from \"@grpc/grpc-js\";\nimport protoLoader from \"@grpc/proto-loader\";\nimport path from \"path\";\nimport getPort from \"get-port\";\nimport { readFileSync } from \"fs\";\nimport { fileURLToPath } from \"url\";\nimport { basePath } from \"../base-path.js\";\n\nimport logger from \"../logger.js\";\nimport { ConfigFile } from \"../config-file.js\";\nimport UnsProxyProcess from \"../uns/uns-proxy-process.js\";\nimport UnsMqttProxy, { MessageMode } from \"../uns-mqtt/uns-mqtt-proxy.js\";\nimport { IUnsMessage, IMqttMessage } from \"../uns/uns-interfaces.js\";\nimport { UnsPacket } from \"../uns/uns-packet.js\";\nimport { IApiProxyOptions, IGetEndpointOptions } from \"../uns/uns-interfaces.js\";\nimport { randomUUID } from \"crypto\";\nimport { MqttTopicBuilder } from \"../uns-mqtt/mqtt-topic-builder.js\";\nimport { ObjectTypes } from \"../uns/uns-object.js\";\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nconst defaultGatewayProto = path.resolve(__dirname, \"uns-gateway.proto\");\nconst GATEWAY_PROTO = process.env.UNS_GATEWAY_PROTO\n ? path.resolve(process.cwd(), process.env.UNS_GATEWAY_PROTO)\n : defaultGatewayProto;\n\ntype GrpcServer = grpc.Server;\n\nexport interface GatewayAddress {\n address: string; // e.g. unix:/tmp/... or 0.0.0.0:PORT\n isUDS: boolean;\n}\n\nexport interface GatewayStartOptions {\n processNameOverride?: string;\n instanceSuffix?: string;\n instanceModeOverride?: \"wait\" | \"force\" | \"handover\";\n handoverOverride?: boolean;\n}\n\ntype UnsApiProxyLike = {\n event: { on(event: string, handler: (payload: any) => void): void };\n get(topic: string, attribute: string, options: IGetEndpointOptions): Promise<void>;\n unregister(topic: string, attribute: string, method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\"): Promise<void>;\n};\n\ntype UnsProxyProcessWithApi = UnsProxyProcess & {\n createApiProxy(instanceName: string, options: IApiProxyOptions): Promise<UnsApiProxyLike>;\n};\n\nconst requireHost = (value: unknown, pathLabel: string): string => {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(`Configuration value '${pathLabel}' is required and must resolve to a string host.`);\n }\n return value;\n};\n\nexport class UnsGatewayServer {\n private server: GrpcServer | null = null;\n private unsProcess: UnsProxyProcessWithApi | null = null;\n private mqttInput: UnsMqttProxy | null = null;\n private mqttOutput: UnsMqttProxy | null = null;\n private handlers: Set<Function> = new Set();\n private unsApiProxy: UnsApiProxyLike | null = null;\n private apiStreams: Set<any> = new Set();\n private pendingApi: Map<string, any> = new Map();\n\n private inputHost: string;\n private outputHost: string;\n private apiOptions: IApiProxyOptions | null = null;\n private outPublisherActive = false;\n private inSubscriberActive = false;\n\n public async start(\n desiredAddr?: string,\n opts?: {\n processNameOverride?: string;\n instanceSuffix?: string;\n instanceModeOverride?: \"wait\" | \"force\" | \"handover\";\n handoverOverride?: boolean;\n }\n ): Promise<GatewayAddress> {\n const packageDef = protoLoader.loadSync(GATEWAY_PROTO, {\n keepCase: true,\n longs: String,\n enums: String,\n defaults: true,\n oneofs: true,\n });\n const proto = grpc.loadPackageDefinition(packageDef) as any;\n\n // Load config and init UNS process + MQTT proxies\n const cfg = await ConfigFile.loadConfig();\n const processName = opts?.processNameOverride ?? cfg.uns.processName;\n const instanceMode = opts?.instanceModeOverride ?? cfg.uns.instanceMode;\n const handover = (typeof opts?.handoverOverride === \"boolean\") ? opts.handoverOverride : cfg.uns.handover;\n const suffix = opts?.instanceSuffix ? `-${opts.instanceSuffix}` : \"\";\n\n const infraHost = requireHost(cfg.infra?.host, \"infra.host\");\n this.unsProcess = new UnsProxyProcess(infraHost, { processName }) as UnsProxyProcessWithApi;\n // cache hosts/options; proxies created lazily on first use\n this.inputHost = requireHost(cfg.input?.host, \"input.host\");\n this.outputHost = requireHost(cfg.output?.host, \"output.host\");\n this.apiOptions = cfg.uns?.jwksWellKnownUrl\n ? { jwks: { wellKnownJwksUrl: cfg.uns.jwksWellKnownUrl, activeKidUrl: cfg.uns.kidWellKnownUrl } }\n : { jwtSecret: \"CHANGEME\" };\n\n const serviceImpl = {\n Publish: this.publish.bind(this),\n Subscribe: this.subscribe.bind(this),\n RegisterApiGet: this.registerApiGet.bind(this),\n UnregisterApiGet: this.unregisterApiGet.bind(this),\n ApiEventStream: this.apiEventStream.bind(this),\n Ready: this.ready.bind(this),\n };\n\n this.server = new grpc.Server();\n this.server.addService(proto.uns.UnsGateway.service, serviceImpl);\n\n const isUnix = process.platform !== \"win32\";\n let addr: string | null = desiredAddr || process.env.UNS_GATEWAY_ADDR || null;\n if (!addr) {\n if (isUnix) {\n const sanitizedProcess = MqttTopicBuilder.sanitizeTopicPart(this.getProcessName());\n const sock = `/tmp/${sanitizedProcess}-uns-gateway.sock`;\n addr = `unix:${sock}`;\n } else {\n const port = await getPort();\n addr = `0.0.0.0:${port}`;\n }\n }\n\n // If UDS and file exists, best-effort unlink (stale sock)\n if (addr.startsWith(\"unix:\")) {\n const fs = await import(\"fs\");\n const p = addr.slice(\"unix:\".length);\n try { if (fs.existsSync(p)) fs.unlinkSync(p); } catch {}\n }\n\n await new Promise<void>((resolve, reject) => {\n this.server!.bindAsync(addr!, grpc.ServerCredentials.createInsecure(), (err) => {\n if (err) return reject(err);\n // grpc-js automatically starts the server after bindAsync in recent versions\n // Calling start() is deprecated; omit to avoid warnings.\n logger.info(`UNS gRPC Gateway listening on ${addr}`);\n resolve();\n });\n });\n\n return { address: addr!, isUDS: addr!.startsWith(\"unix:\") };\n }\n\n private getProcessName(): string {\n try {\n const pkgPath = path.join(basePath, \"package.json\");\n const raw = readFileSync(pkgPath, \"utf8\");\n const pkg = JSON.parse(raw);\n return `${pkg.name}-${pkg.version}`;\n } catch {\n return `uns-gateway`;\n }\n }\n\n private async publish(call: any, callback: any) {\n try {\n await this.ensureMqttOutput();\n const req = call.request as any;\n if (!this.mqttOutput) throw new Error(\"Gateway not initialized\");\n\n const topic: string = req.topic;\n const attribute: string = req.attribute;\n const description: string = req.description ?? \"\";\n const tags: string[] = (req.tags ?? []) as string[];\n const attributeNeedsPersistence: boolean | null = req.attribute_needs_persistence ?? null;\n const valueIsCumulative: boolean = req.value_is_cumulative ?? false;\n\n let message: IUnsMessage | null = null;\n\n if (req.data) {\n const d = req.data;\n const time: string = d.time;\n const uom: string | undefined = d.uom || undefined;\n const dataGroup: string | undefined = d.data_group || undefined;\n const foreignEventKey: string | undefined = d.foreign_event_key || undefined;\n\n let value: any = undefined;\n if (typeof d.value_number === \"number\" && !Number.isNaN(d.value_number)) {\n value = d.value_number;\n } else if (typeof d.value_string === \"string\" && d.value_string.length > 0) {\n value = d.value_string;\n }\n if (value === undefined) throw new Error(\"Data.value_number or Data.value_string must be set\");\n\n message = { data: { time, value, uom, dataGroup, foreignEventKey } } as IUnsMessage;\n } else if (req.table) {\n const t = req.table;\n const time: string = t.time;\n const dataGroup: string | undefined = t.data_group || undefined;\n const values: Record<string, string | number | null | undefined> = {};\n (t.values ?? []).forEach((kv: any) => {\n const key = kv.key as string;\n if (typeof kv.value_number === \"number\" && !Number.isNaN(kv.value_number)) {\n values[key] = kv.value_number;\n } else if (typeof kv.value_string === \"string\") {\n values[key] = kv.value_string;\n } else {\n values[key] = null;\n }\n });\n message = { table: { time, values, dataGroup } } as IUnsMessage;\n } else {\n throw new Error(\"PublishRequest.content must be data or table\");\n }\n\n const packet = await UnsPacket.unsPacketFromUnsMessage(message);\n const mqttMsg: IMqttMessage = {\n topic,\n attribute,\n description,\n tags,\n packet,\n asset:\"meter\",\n objectType: ObjectTypes.EnergyResource,\n objectId: \"main\",\n attributeNeedsPersistence,\n };\n\n // delta mode if cumulative\n if (message.data && valueIsCumulative) {\n this.mqttOutput.publishMqttMessage(mqttMsg, MessageMode.Delta);\n } else {\n this.mqttOutput.publishMqttMessage(mqttMsg, MessageMode.Raw);\n }\n\n callback(null, { ok: true });\n } catch (err: any) {\n logger.error(`Gateway Publish error: ${err.message}`);\n callback(null, { ok: false, error: err.message });\n }\n }\n\n private async subscribe(call: any) {\n await this.ensureMqttInput();\n const req = call.request as any;\n const topics: string[] = (req.topics ?? []) as string[];\n if (topics.length === 0) {\n call.emit(\"error\", { code: grpc.status.INVALID_ARGUMENT, details: \"topics is required\" });\n call.end();\n return;\n }\n\n // Subscribe and stream messages to this client\n this.mqttInput.subscribeAsync(topics);\n\n const handler = (event: any) => {\n try {\n // Forward as UNS packet JSON if parsable, else raw message\n const payload = event.packet ? JSON.stringify(event.packet) : String(event.message ?? \"\");\n call.write({ topic: event.topic, payload });\n } catch (e) {\n // drop\n }\n };\n this.handlers.add(handler);\n this.mqttInput.event.on(\"input\", handler);\n\n call.on(\"cancelled\", () => this.cleanupHandler(handler));\n call.on(\"error\", () => this.cleanupHandler(handler));\n call.on(\"close\", () => this.cleanupHandler(handler));\n }\n\n private attachStatusListeners(): void {\n if (this.mqttOutput) {\n this.mqttOutput.event.on(\"mqttProxyStatus\", (e: any) => {\n if (e?.event === \"t-publisher-active\") this.outPublisherActive = !!e.value;\n });\n }\n if (this.mqttInput) {\n this.mqttInput.event.on(\"mqttProxyStatus\", (e: any) => {\n if (e?.event === \"t-subscriber-active\") this.inSubscriberActive = !!e.value;\n });\n }\n }\n\n private async ensureMqttOutput() {\n if (!this.mqttOutput) {\n // slight delay to let process MQTT connect\n while ((this.unsProcess as any)?.processMqttProxy?.isConnected === false) {\n await new Promise((r) => setTimeout(r, 50));\n }\n this.mqttOutput = await this.unsProcess!.createUnsMqttProxy(\n this.outputHost,\n this.getInstanceName(\"gatewayOutput\"),\n \"force\",\n true,\n { publishThrottlingDelay: 1 },\n );\n this.attachStatusListeners();\n }\n }\n\n private async ensureMqttInput() {\n if (!this.mqttInput) {\n while ((this.unsProcess as any)?.processMqttProxy?.isConnected === false) {\n await new Promise((r) => setTimeout(r, 50));\n }\n this.mqttInput = await this.unsProcess!.createUnsMqttProxy(\n this.inputHost,\n this.getInstanceName(\"gatewayInput\"),\n \"force\",\n true,\n { mqttSubToTopics: [] },\n );\n this.attachStatusListeners();\n }\n }\n\n private async ensureApiProxy() {\n if (!this.unsApiProxy) {\n if (typeof (this.unsProcess as any)?.createApiProxy !== \"function\") {\n throw new Error(\"API plugin not registered. Please install @uns-kit/api and register it with UnsProxyProcess before starting the gateway.\");\n }\n this.unsApiProxy = await this.unsProcess!.createApiProxy(this.getInstanceName(\"gatewayApi\"), this.apiOptions!);\n this.unsApiProxy.event.on(\"apiGetEvent\", (event: any) => this.onApiGetEvent(event));\n }\n }\n\n private getInstanceName(base: string): string {\n // derive suffix from processName/CLI by inspecting configured instanceStatusTopic is overkill; keep base names unique per process\n return base;\n }\n\n private async registerApiGet(call: any, callback: any) {\n try {\n await this.ensureApiProxy();\n const req = call.request as any;\n const topic: string = req.topic;\n const attribute: string = req.attribute;\n const apiDescription: string | undefined = req.api_description || undefined;\n const tags: string[] | undefined = (req.tags ?? []) as string[];\n const queryParams: any[] = (req.query_params ?? []).map((p: any) => ({\n name: p.name,\n type: (p.type === \"number\" || p.type === \"boolean\") ? p.type : \"string\",\n required: !!p.required,\n description: p.description ?? undefined,\n }));\n\n const options: IGetEndpointOptions = {\n apiDescription,\n tags,\n queryParams,\n };\n await this.unsApiProxy.get(topic as any, attribute, options);\n callback(null, { ok: true });\n } catch (err: any) {\n logger.error(`Gateway RegisterApiGet error: ${err.message}`);\n callback(null, { ok: false, error: err.message });\n }\n }\n\n private async unregisterApiGet(call: any, callback: any) {\n try {\n await this.ensureApiProxy();\n const req = call.request as any;\n const topic: string = req.topic;\n const attribute: string = req.attribute;\n await this.unsApiProxy.unregister(topic as any, attribute, \"GET\");\n callback(null, { ok: true });\n } catch (err: any) {\n logger.error(`Gateway UnregisterApiGet error: ${err.message}`);\n callback(null, { ok: false, error: err.message });\n }\n }\n\n private onApiGetEvent(event: any) {\n // Correlate request and forward to connected gRPC streams\n const id = randomUUID();\n const req = event.req;\n const res = event.res;\n const path: string = req.path || req.originalUrl || \"/\";\n // Derive topic/attribute is optional; we send path and query\n const bearer = (req.headers?.[\"authorization\"] as string | undefined) ?? \"\";\n this.pendingApi.set(id, res);\n // Timeout after 10s\n setTimeout(() => {\n if (this.pendingApi.has(id)) {\n const r = this.pendingApi.get(id);\n try { r.status(504).send(\"Gateway timeout\"); } catch {}\n this.pendingApi.delete(id);\n }\n }, 10_000).unref?.();\n\n const query: Record<string, string> = {};\n Object.entries(req.query || {}).forEach(([k, v]) => { query[k] = String(v); });\n const msg = { id, method: \"GET\", path, query, bearer };\n for (const stream of this.apiStreams) {\n try { stream.write(msg); } catch {}\n }\n }\n\n private async apiEventStream(call: any) {\n // Register stream\n await this.ensureApiProxy();\n this.apiStreams.add(call);\n call.on(\"data\", (resp: any) => {\n const id: string = resp.id;\n const status: number = resp.status ?? 200;\n const body: string = resp.body ?? \"\";\n const headers: Record<string, string> = resp.headers ?? {};\n const res = this.pendingApi.get(id);\n if (res) {\n try {\n Object.entries(headers).forEach(([k, v]) => res.setHeader(k, v));\n res.status(status).send(body);\n } catch {}\n this.pendingApi.delete(id);\n }\n });\n const cleanup = () => { this.apiStreams.delete(call); };\n call.on(\"cancelled\", cleanup);\n call.on(\"error\", cleanup);\n call.on(\"close\", cleanup);\n }\n\n private async ready(call: any, callback: any) {\n try {\n const req = call.request as any;\n const timeoutMs: number = req.timeout_ms && req.timeout_ms > 0 ? req.timeout_ms : 15000;\n const waitOut = !!req.wait_output;\n const waitIn = !!req.wait_input;\n const waitApi = !!req.wait_api;\n\n if (waitOut) await this.ensureMqttOutput();\n if (waitIn) await this.ensureMqttInput();\n if (waitApi) await this.ensureApiProxy();\n\n const start = Date.now();\n const check = () => {\n const okOut = !waitOut || this.outPublisherActive;\n const okIn = !waitIn || this.inSubscriberActive;\n const okApi = !waitApi || !!this.unsApiProxy; // creation ensures listening\n return okOut && okIn && okApi;\n };\n\n if (check()) return callback(null, { ok: true });\n\n const onStatus = () => {\n if (check()) done(true);\n };\n\n const done = (ok: boolean, err?: string) => {\n if (this.mqttOutput) this.mqttOutput.event.off(\"mqttProxyStatus\", onStatus as any);\n if (this.mqttInput) this.mqttInput.event.off(\"mqttProxyStatus\", onStatus as any);\n callback(null, { ok, error: err });\n };\n\n if (this.mqttOutput) this.mqttOutput.event.on(\"mqttProxyStatus\", onStatus as any);\n if (this.mqttInput) this.mqttInput.event.on(\"mqttProxyStatus\", onStatus as any);\n\n const iv = setInterval(() => {\n if (check()) {\n clearInterval(iv);\n done(true);\n } else if (Date.now() - start > timeoutMs) {\n clearInterval(iv);\n done(false, \"timeout waiting for readiness\");\n }\n }, 100);\n } catch (e: any) {\n callback(null, { ok: false, error: e.message });\n }\n }\n\n private cleanupHandler(handler: Function) {\n if (this.mqttInput) this.mqttInput.event.off(\"input\", handler as any);\n this.handlers.delete(handler);\n }\n\n public async shutdown(): Promise<void> {\n try {\n for (const h of Array.from(this.handlers)) this.cleanupHandler(h);\n if (this.server) {\n await new Promise<void>((resolve) => this.server!.tryShutdown(() => resolve()));\n this.server = null;\n }\n if (this.unsProcess) this.unsProcess.shutdown();\n } catch (e: any) {\n logger.error(`Gateway shutdown error: ${e.message}`);\n }\n }\n}\n\nexport async function startUnsGateway(addrOverride?: string, opts?: GatewayStartOptions): Promise<GatewayAddress> {\n const gw = new UnsGatewayServer();\n return gw.start(addrOverride, opts);\n}\nfunction sanitizeTopicPart(getProcessName: () => string) {\n throw new Error(\"Function not implemented.\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"uns-gateway-server.js","sourceRoot":"","sources":["../../src/uns-grpc/uns-gateway-server.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,eAAe,CAAC;AACjC,OAAO,WAAW,MAAM,oBAAoB,CAAC;AAC7C,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,OAAO,MAAM,UAAU,CAAC;AAC/B,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,MAAM,MAAM,cAAc,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,eAAe,MAAM,6BAA6B,CAAC;AAC1D,OAAqB,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEjD,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AACrE,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAClD,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;AAE3C,MAAM,mBAAmB,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,mBAAmB,CAAC,CAAC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AAC,cAAc,CAAC,CAAC,CAAC,CAAC;YAClE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;gBAChB,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,MAAO,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;gBAChF,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;YACrB,CAAC;YACD,IAAI,IAAI,CAAC,UAAU;gBAAE,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC;QAClD,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,MAAM,CAAC,KAAK,CAAC,2BAA2B,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;CACF;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,YAAqB,EAAE,IAA0B;IACrF,MAAM,EAAE,GAAG,IAAI,gBAAgB,EAAE,CAAC;IAClC,OAAO,EAAE,CAAC,KAAK,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;AACtC,CAAC;AACD,SAAS,iBAAiB,CAAC,cAA4B;IACrD,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import grpc from \"@grpc/grpc-js\";\nimport protoLoader from \"@grpc/proto-loader\";\nimport path from \"path\";\nimport getPort from \"get-port\";\nimport { readFileSync } from \"fs\";\nimport { fileURLToPath } from \"url\";\nimport { basePath } from \"../base-path.js\";\n\nimport logger from \"../logger.js\";\nimport { ConfigFile } from \"../config-file.js\";\nimport UnsProxyProcess from \"../uns/uns-proxy-process.js\";\nimport UnsMqttProxy, { MessageMode } from \"../uns-mqtt/uns-mqtt-proxy.js\";\nimport { IUnsMessage, IMqttMessage } from \"../uns/uns-interfaces.js\";\nimport { UnsPacket } from \"../uns/uns-packet.js\";\nimport { IApiProxyOptions, IGetEndpointOptions } from \"../uns/uns-interfaces.js\";\nimport { randomUUID } from \"crypto\";\nimport { MqttTopicBuilder } from \"../uns-mqtt/mqtt-topic-builder.js\";\nimport { ObjectTypes } from \"../uns/uns-object.js\";\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nconst defaultGatewayProto = path.resolve(__dirname, \"uns-gateway.proto\");\nconst GATEWAY_PROTO = process.env.UNS_GATEWAY_PROTO\n ? path.resolve(process.cwd(), process.env.UNS_GATEWAY_PROTO)\n : defaultGatewayProto;\n\ntype GrpcServer = grpc.Server;\n\nexport interface GatewayAddress {\n address: string; // e.g. unix:/tmp/... or 0.0.0.0:PORT\n isUDS: boolean;\n}\n\nexport interface GatewayStartOptions {\n processNameOverride?: string;\n instanceSuffix?: string;\n instanceModeOverride?: \"wait\" | \"force\" | \"handover\";\n handoverOverride?: boolean;\n}\n\ntype UnsApiProxyLike = {\n event: { on(event: string, handler: (payload: any) => void): void };\n get(topic: string, attribute: string, options: IGetEndpointOptions): Promise<void>;\n unregister(topic: string, attribute: string, method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\"): Promise<void>;\n};\n\ntype UnsProxyProcessWithApi = UnsProxyProcess & {\n createApiProxy(instanceName: string, options: IApiProxyOptions): Promise<UnsApiProxyLike>;\n};\n\nconst requireHost = (value: unknown, pathLabel: string): string => {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(`Configuration value '${pathLabel}' is required and must resolve to a string host.`);\n }\n return value;\n};\n\nexport class UnsGatewayServer {\n private server: GrpcServer | null = null;\n private unsProcess: UnsProxyProcessWithApi | null = null;\n private mqttInput: UnsMqttProxy | null = null;\n private mqttOutput: UnsMqttProxy | null = null;\n private handlers: Set<Function> = new Set();\n private unsApiProxy: UnsApiProxyLike | null = null;\n private apiStreams: Set<any> = new Set();\n private pendingApi: Map<string, any> = new Map();\n\n private inputHost: string;\n private outputHost: string;\n private apiOptions: IApiProxyOptions | null = null;\n private outPublisherActive = false;\n private inSubscriberActive = false;\n\n public async start(\n desiredAddr?: string,\n opts?: {\n processNameOverride?: string;\n instanceSuffix?: string;\n instanceModeOverride?: \"wait\" | \"force\" | \"handover\";\n handoverOverride?: boolean;\n }\n ): Promise<GatewayAddress> {\n const packageDef = protoLoader.loadSync(GATEWAY_PROTO, {\n keepCase: true,\n longs: String,\n enums: String,\n defaults: true,\n oneofs: true,\n });\n const proto = grpc.loadPackageDefinition(packageDef) as any;\n\n // Load config and init UNS process + MQTT proxies\n const cfg = await ConfigFile.loadConfig();\n const processName = opts?.processNameOverride ?? cfg.uns.processName;\n const instanceMode = opts?.instanceModeOverride ?? cfg.uns.instanceMode;\n const handover = (typeof opts?.handoverOverride === \"boolean\") ? opts.handoverOverride : cfg.uns.handover;\n const suffix = opts?.instanceSuffix ? `-${opts.instanceSuffix}` : \"\";\n\n const infraHost = requireHost(cfg.infra?.host, \"infra.host\");\n this.unsProcess = new UnsProxyProcess(infraHost, { processName }) as UnsProxyProcessWithApi;\n // cache hosts/options; proxies created lazily on first use\n this.inputHost = requireHost(cfg.input?.host, \"input.host\");\n this.outputHost = requireHost(cfg.output?.host, \"output.host\");\n this.apiOptions = cfg.uns?.jwksWellKnownUrl\n ? { jwks: { wellKnownJwksUrl: cfg.uns.jwksWellKnownUrl, activeKidUrl: cfg.uns.kidWellKnownUrl } }\n : { jwtSecret: \"CHANGEME\" };\n\n const serviceImpl = {\n Publish: this.publish.bind(this),\n Subscribe: this.subscribe.bind(this),\n RegisterApiGet: this.registerApiGet.bind(this),\n UnregisterApiGet: this.unregisterApiGet.bind(this),\n ApiEventStream: this.apiEventStream.bind(this),\n Ready: this.ready.bind(this),\n };\n\n this.server = new grpc.Server();\n this.server.addService(proto.uns.UnsGateway.service, serviceImpl);\n\n const isUnix = process.platform !== \"win32\";\n let addr: string | null = desiredAddr || process.env.UNS_GATEWAY_ADDR || null;\n if (!addr) {\n if (isUnix) {\n const sanitizedProcess = MqttTopicBuilder.sanitizeTopicPart(this.getProcessName());\n const sock = `/tmp/${sanitizedProcess}-uns-gateway.sock`;\n addr = `unix:${sock}`;\n } else {\n const port = await getPort();\n addr = `0.0.0.0:${port}`;\n }\n }\n\n // If UDS and file exists, best-effort unlink (stale sock)\n if (addr.startsWith(\"unix:\")) {\n const fs = await import(\"fs\");\n const p = addr.slice(\"unix:\".length);\n try { if (fs.existsSync(p)) fs.unlinkSync(p); } catch {}\n }\n\n await new Promise<void>((resolve, reject) => {\n this.server!.bindAsync(addr!, grpc.ServerCredentials.createInsecure(), (err) => {\n if (err) return reject(err);\n // grpc-js automatically starts the server after bindAsync in recent versions\n // Calling start() is deprecated; omit to avoid warnings.\n logger.info(`UNS gRPC Gateway listening on ${addr}`);\n resolve();\n });\n });\n\n return { address: addr!, isUDS: addr!.startsWith(\"unix:\") };\n }\n\n private getProcessName(): string {\n try {\n const pkgPath = path.join(basePath, \"package.json\");\n const raw = readFileSync(pkgPath, \"utf8\");\n const pkg = JSON.parse(raw);\n return `${pkg.name}-${pkg.version}`;\n } catch {\n return `uns-gateway`;\n }\n }\n\n private async publish(call: any, callback: any) {\n try {\n await this.ensureMqttOutput();\n const req = call.request as any;\n if (!this.mqttOutput) throw new Error(\"Gateway not initialized\");\n\n const topic: string = req.topic;\n const attribute: string = req.attribute;\n const description: string = req.description ?? \"\";\n const tags: string[] = (req.tags ?? []) as string[];\n const attributeNeedsPersistence: boolean | null = req.attribute_needs_persistence ?? null;\n const valueIsCumulative: boolean = req.value_is_cumulative ?? false;\n\n let message: IUnsMessage | null = null;\n\n if (req.data) {\n const d = req.data;\n const time: string = d.time;\n const uom: string | undefined = d.uom || undefined;\n const dataGroup: string | undefined = d.data_group || undefined;\n const foreignEventKey: string | undefined = d.foreign_event_key || undefined;\n\n let value: any = undefined;\n if (typeof d.value_number === \"number\" && !Number.isNaN(d.value_number)) {\n value = d.value_number;\n } else if (typeof d.value_string === \"string\" && d.value_string.length > 0) {\n value = d.value_string;\n }\n if (value === undefined) throw new Error(\"Data.value_number or Data.value_string must be set\");\n\n message = { data: { time, value, uom, dataGroup, foreignEventKey } } as IUnsMessage;\n } else if (req.table) {\n const t = req.table;\n const time: string = t.time;\n const dataGroup: string | undefined = t.data_group || undefined;\n const values: Record<string, string | number | null | undefined> = {};\n (t.values ?? []).forEach((kv: any) => {\n const key = kv.key as string;\n if (typeof kv.value_number === \"number\" && !Number.isNaN(kv.value_number)) {\n values[key] = kv.value_number;\n } else if (typeof kv.value_string === \"string\") {\n values[key] = kv.value_string;\n } else {\n values[key] = null;\n }\n });\n message = { table: { time, values, dataGroup } } as IUnsMessage;\n } else {\n throw new Error(\"PublishRequest.content must be data or table\");\n }\n\n const packet = await UnsPacket.unsPacketFromUnsMessage(message);\n const mqttMsg: IMqttMessage = {\n topic,\n attribute,\n description,\n tags,\n packet,\n asset:\"meter\",\n objectType: ObjectTypes[\"energy-resource\"],\n objectId: \"main\",\n attributeNeedsPersistence,\n };\n\n // delta mode if cumulative\n if (message.data && valueIsCumulative) {\n this.mqttOutput.publishMqttMessage(mqttMsg, MessageMode.Delta);\n } else {\n this.mqttOutput.publishMqttMessage(mqttMsg, MessageMode.Raw);\n }\n\n callback(null, { ok: true });\n } catch (err: any) {\n logger.error(`Gateway Publish error: ${err.message}`);\n callback(null, { ok: false, error: err.message });\n }\n }\n\n private async subscribe(call: any) {\n await this.ensureMqttInput();\n const req = call.request as any;\n const topics: string[] = (req.topics ?? []) as string[];\n if (topics.length === 0) {\n call.emit(\"error\", { code: grpc.status.INVALID_ARGUMENT, details: \"topics is required\" });\n call.end();\n return;\n }\n\n // Subscribe and stream messages to this client\n this.mqttInput.subscribeAsync(topics);\n\n const handler = (event: any) => {\n try {\n // Forward as UNS packet JSON if parsable, else raw message\n const payload = event.packet ? JSON.stringify(event.packet) : String(event.message ?? \"\");\n call.write({ topic: event.topic, payload });\n } catch (e) {\n // drop\n }\n };\n this.handlers.add(handler);\n this.mqttInput.event.on(\"input\", handler);\n\n call.on(\"cancelled\", () => this.cleanupHandler(handler));\n call.on(\"error\", () => this.cleanupHandler(handler));\n call.on(\"close\", () => this.cleanupHandler(handler));\n }\n\n private attachStatusListeners(): void {\n if (this.mqttOutput) {\n this.mqttOutput.event.on(\"mqttProxyStatus\", (e: any) => {\n if (e?.event === \"t-publisher-active\") this.outPublisherActive = !!e.value;\n });\n }\n if (this.mqttInput) {\n this.mqttInput.event.on(\"mqttProxyStatus\", (e: any) => {\n if (e?.event === \"t-subscriber-active\") this.inSubscriberActive = !!e.value;\n });\n }\n }\n\n private async ensureMqttOutput() {\n if (!this.mqttOutput) {\n // slight delay to let process MQTT connect\n while ((this.unsProcess as any)?.processMqttProxy?.isConnected === false) {\n await new Promise((r) => setTimeout(r, 50));\n }\n this.mqttOutput = await this.unsProcess!.createUnsMqttProxy(\n this.outputHost,\n this.getInstanceName(\"gatewayOutput\"),\n \"force\",\n true,\n { publishThrottlingDelay: 1 },\n );\n this.attachStatusListeners();\n }\n }\n\n private async ensureMqttInput() {\n if (!this.mqttInput) {\n while ((this.unsProcess as any)?.processMqttProxy?.isConnected === false) {\n await new Promise((r) => setTimeout(r, 50));\n }\n this.mqttInput = await this.unsProcess!.createUnsMqttProxy(\n this.inputHost,\n this.getInstanceName(\"gatewayInput\"),\n \"force\",\n true,\n { mqttSubToTopics: [] },\n );\n this.attachStatusListeners();\n }\n }\n\n private async ensureApiProxy() {\n if (!this.unsApiProxy) {\n if (typeof (this.unsProcess as any)?.createApiProxy !== \"function\") {\n throw new Error(\"API plugin not registered. Please install @uns-kit/api and register it with UnsProxyProcess before starting the gateway.\");\n }\n this.unsApiProxy = await this.unsProcess!.createApiProxy(this.getInstanceName(\"gatewayApi\"), this.apiOptions!);\n this.unsApiProxy.event.on(\"apiGetEvent\", (event: any) => this.onApiGetEvent(event));\n }\n }\n\n private getInstanceName(base: string): string {\n // derive suffix from processName/CLI by inspecting configured instanceStatusTopic is overkill; keep base names unique per process\n return base;\n }\n\n private async registerApiGet(call: any, callback: any) {\n try {\n await this.ensureApiProxy();\n const req = call.request as any;\n const topic: string = req.topic;\n const attribute: string = req.attribute;\n const apiDescription: string | undefined = req.api_description || undefined;\n const tags: string[] | undefined = (req.tags ?? []) as string[];\n const queryParams: any[] = (req.query_params ?? []).map((p: any) => ({\n name: p.name,\n type: (p.type === \"number\" || p.type === \"boolean\") ? p.type : \"string\",\n required: !!p.required,\n description: p.description ?? undefined,\n }));\n\n const options: IGetEndpointOptions = {\n apiDescription,\n tags,\n queryParams,\n };\n await this.unsApiProxy.get(topic as any, attribute, options);\n callback(null, { ok: true });\n } catch (err: any) {\n logger.error(`Gateway RegisterApiGet error: ${err.message}`);\n callback(null, { ok: false, error: err.message });\n }\n }\n\n private async unregisterApiGet(call: any, callback: any) {\n try {\n await this.ensureApiProxy();\n const req = call.request as any;\n const topic: string = req.topic;\n const attribute: string = req.attribute;\n await this.unsApiProxy.unregister(topic as any, attribute, \"GET\");\n callback(null, { ok: true });\n } catch (err: any) {\n logger.error(`Gateway UnregisterApiGet error: ${err.message}`);\n callback(null, { ok: false, error: err.message });\n }\n }\n\n private onApiGetEvent(event: any) {\n // Correlate request and forward to connected gRPC streams\n const id = randomUUID();\n const req = event.req;\n const res = event.res;\n const path: string = req.path || req.originalUrl || \"/\";\n // Derive topic/attribute is optional; we send path and query\n const bearer = (req.headers?.[\"authorization\"] as string | undefined) ?? \"\";\n this.pendingApi.set(id, res);\n // Timeout after 10s\n setTimeout(() => {\n if (this.pendingApi.has(id)) {\n const r = this.pendingApi.get(id);\n try { r.status(504).send(\"Gateway timeout\"); } catch {}\n this.pendingApi.delete(id);\n }\n }, 10_000).unref?.();\n\n const query: Record<string, string> = {};\n Object.entries(req.query || {}).forEach(([k, v]) => { query[k] = String(v); });\n const msg = { id, method: \"GET\", path, query, bearer };\n for (const stream of this.apiStreams) {\n try { stream.write(msg); } catch {}\n }\n }\n\n private async apiEventStream(call: any) {\n // Register stream\n await this.ensureApiProxy();\n this.apiStreams.add(call);\n call.on(\"data\", (resp: any) => {\n const id: string = resp.id;\n const status: number = resp.status ?? 200;\n const body: string = resp.body ?? \"\";\n const headers: Record<string, string> = resp.headers ?? {};\n const res = this.pendingApi.get(id);\n if (res) {\n try {\n Object.entries(headers).forEach(([k, v]) => res.setHeader(k, v));\n res.status(status).send(body);\n } catch {}\n this.pendingApi.delete(id);\n }\n });\n const cleanup = () => { this.apiStreams.delete(call); };\n call.on(\"cancelled\", cleanup);\n call.on(\"error\", cleanup);\n call.on(\"close\", cleanup);\n }\n\n private async ready(call: any, callback: any) {\n try {\n const req = call.request as any;\n const timeoutMs: number = req.timeout_ms && req.timeout_ms > 0 ? req.timeout_ms : 15000;\n const waitOut = !!req.wait_output;\n const waitIn = !!req.wait_input;\n const waitApi = !!req.wait_api;\n\n if (waitOut) await this.ensureMqttOutput();\n if (waitIn) await this.ensureMqttInput();\n if (waitApi) await this.ensureApiProxy();\n\n const start = Date.now();\n const check = () => {\n const okOut = !waitOut || this.outPublisherActive;\n const okIn = !waitIn || this.inSubscriberActive;\n const okApi = !waitApi || !!this.unsApiProxy; // creation ensures listening\n return okOut && okIn && okApi;\n };\n\n if (check()) return callback(null, { ok: true });\n\n const onStatus = () => {\n if (check()) done(true);\n };\n\n const done = (ok: boolean, err?: string) => {\n if (this.mqttOutput) this.mqttOutput.event.off(\"mqttProxyStatus\", onStatus as any);\n if (this.mqttInput) this.mqttInput.event.off(\"mqttProxyStatus\", onStatus as any);\n callback(null, { ok, error: err });\n };\n\n if (this.mqttOutput) this.mqttOutput.event.on(\"mqttProxyStatus\", onStatus as any);\n if (this.mqttInput) this.mqttInput.event.on(\"mqttProxyStatus\", onStatus as any);\n\n const iv = setInterval(() => {\n if (check()) {\n clearInterval(iv);\n done(true);\n } else if (Date.now() - start > timeoutMs) {\n clearInterval(iv);\n done(false, \"timeout waiting for readiness\");\n }\n }, 100);\n } catch (e: any) {\n callback(null, { ok: false, error: e.message });\n }\n }\n\n private cleanupHandler(handler: Function) {\n if (this.mqttInput) this.mqttInput.event.off(\"input\", handler as any);\n this.handlers.delete(handler);\n }\n\n public async shutdown(): Promise<void> {\n try {\n for (const h of Array.from(this.handlers)) this.cleanupHandler(h);\n if (this.server) {\n await new Promise<void>((resolve) => this.server!.tryShutdown(() => resolve()));\n this.server = null;\n }\n if (this.unsProcess) this.unsProcess.shutdown();\n } catch (e: any) {\n logger.error(`Gateway shutdown error: ${e.message}`);\n }\n }\n}\n\nexport async function startUnsGateway(addrOverride?: string, opts?: GatewayStartOptions): Promise<GatewayAddress> {\n const gw = new UnsGatewayServer();\n return gw.start(addrOverride, opts);\n}\nfunction sanitizeTopicPart(getProcessName: () => string) {\n throw new Error(\"Function not implemented.\");\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uns-mqtt-proxy.d.ts","sourceRoot":"","sources":["../../src/uns-mqtt/uns-mqtt-proxy.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,cAAc,EAAE,SAAS,EAAa,MAAM,0BAA0B,CAAC;AAO1G,OAAO,QAAQ,MAAM,qBAAqB,CAAC;AAU3C,oBAAY,WAAW;IACrB,GAAG,QAAQ,CAAM,iCAAiC;IAClD,KAAK,UAAU,CAAE,8BAA8B;IAC/C,IAAI,SAAS;CACd;AAED,MAAM,CAAC,OAAO,OAAO,YAAa,SAAQ,QAAQ;IAChD,OAAO,CAAC,UAAU,CAA8E;IAChG,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,eAAe,CAAmF;IAC1G,OAAO,CAAC,aAAa,CAAiB;IACtC,SAAS,CAAC,kBAAkB,EAAE,MAAM,CAAC;IAC9B,YAAY,EAAE,MAAM,CAAC;IAC5B,OAAO,CAAC,iBAAiB,CAAkC;IAC3D,OAAO,CAAC,YAAY,CAAmB;gBAGrC,QAAQ,EAAE,MAAM,EAChB,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,MAAM,EACpB,aAAa,CAAC,EAAE,cAAc,EAC9B,eAAe,GAAE,OAAe,EAChC,gBAAgB,GAAE,OAAe;IA0BnC;;;OAGG;IACH,OAAO,C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;IACI,kBAAkB,CAAC,WAAW,EAAE,YAAY,GAAG,IAAI,EAAE,IAAI,GAAE,WAA6B;IAiC/F;;;;;;OAMG;IACI,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIpE;;;;;OAKG;IACI,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI;IAI7D;;;;OAIG;IACI,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,IAAI;IAItD;;;;OAIG;IACI,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI;IAI/C;;;;;;;OAOG;YACW,wBAAwB;IAmFtC;;OAEG;IACU,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAmBnC"}
|
|
@@ -311,17 +311,20 @@ export default class UnsMqttProxy extends UnsProxy {
|
|
|
311
311
|
const { objectType, objectId, asset } = this.resolveObjectIdentity(msg);
|
|
312
312
|
const normalizedTopic = this.normalizeTopicWithObject(msg.topic);
|
|
313
313
|
msg.topic = normalizedTopic;
|
|
314
|
+
const description = msg.description ?? "";
|
|
314
315
|
this.registerUniqueTopic({
|
|
315
316
|
timestamp: time,
|
|
316
317
|
topic: msg.topic,
|
|
317
318
|
attribute: msg.attribute,
|
|
318
319
|
attributeType: attributeType,
|
|
319
|
-
description
|
|
320
|
+
description,
|
|
320
321
|
tags: msg.tags,
|
|
321
322
|
attributeNeedsPersistence: msg.attributeNeedsPersistence,
|
|
322
323
|
dataGroup,
|
|
323
324
|
asset,
|
|
325
|
+
assetDescription: msg.assetDescription,
|
|
324
326
|
objectType,
|
|
327
|
+
objectTypeDescription: msg.objectTypeDescription,
|
|
325
328
|
objectId
|
|
326
329
|
});
|
|
327
330
|
const publishTopic = `${msg.topic}${asset ? `${asset}/` : ""}${objectType ? `${objectType}/` : ""}${objectId ? `${objectId}/` : ""}${msg.attribute}`;
|
|
@@ -1 +1 @@
|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AM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,sBAAsB,wCAAwC,GAAG,CAAC,KAAK,GAAG,GAAG,CAAC,SAAS,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACpI,CAAC;IACH,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,IAAI;QACf,KAAK,CAAC,IAAI,EAAE,CAAC;QACb,4CAA4C;QAC5C,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC;gBACH,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;gBAC/C,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,sBAAsB,uCAAuC,QAAQ,EAAE,CAAC,CAAC;YAC/F,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,sBAAsB,gCAAgC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YAC9F,CAAC;QACH,CAAC;QAED,2CAA2C;QAC3C,KAAK,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACjD,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC,CAAC;YACvD,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAClC,CAAC;IACH,CAAC;CAEF","sourcesContent":["import { readFileSync } from \"fs\";\nimport { IClientPublishOptions } from \"mqtt\";\nimport * as path from \"path\";\nimport { Worker } from \"worker_threads\";\nimport { fileURLToPath } from \"url\";\nimport { basePath } from \"../base-path.js\";\nimport logger from \"../logger.js\";\nimport { IMqttMessage, IUnsPacket, IUnsParameters, UnsEvents, ValueType } from \"../uns/uns-interfaces.js\";\nimport type { UnsObjectId, UnsObjectType } from \"../uns/uns-object.js\";\nimport type { UnsAsset } from \"../uns/uns-asset.js\";\nimport { MeasurementUnit } from \"../uns/uns-measurements.js\";\nimport { UnsPacket } from \"../uns/uns-packet.js\";\nimport { IMqttParameters, IMqttWorkerData } from \"./mqtt-interfaces.js\";\nimport { MqttTopicBuilder } from \"./mqtt-topic-builder.js\";\nimport UnsProxy from \"../uns/uns-proxy.js\";\nimport { UnsAttributeType } from \"../graphql/schema.js\";\n\nconst packageJsonPath = path.join(basePath, \"package.json\");\nconst packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\"));\n\nconst moduleDirectory = path.dirname(fileURLToPath(import.meta.url));\nconst packageRoot = path.resolve(moduleDirectory, \"..\", \"..\");\nconst workerScriptPath = path.join(packageRoot, \"dist/uns-mqtt/mqtt-worker-init.js\");\n\nexport enum MessageMode {\n Raw = 'raw', // Send only the original message\n Delta = 'delta', // Send only the delta message\n Both = 'both' // Send both the original and delta messages\n}\n\nexport default class UnsMqttProxy extends UnsProxy {\n private lastValues: Map<string, { value: ValueType; uom: string; timestamp: Date }> = new Map();\n private worker: Worker;\n private pendingEnqueues: Map<string, { resolve: () => void; reject: (reason?: any) => void }> = new Map();\n private unsParameters: IUnsParameters;\n protected processStatusTopic: string;\n public instanceName: string;\n private currentSequenceId: Map<string, number> = new Map();\n private topicBuilder: MqttTopicBuilder;\n\n constructor(\n mqttHost: string,\n processName: string,\n instanceName: string,\n unsParameters?: IUnsParameters,\n publisherActive: boolean = false,\n subscriberActive: boolean = false\n ) {\n super();\n this.instanceName = instanceName;\n // Create the topic builder using packageJson values and the processName.\n this.topicBuilder = new MqttTopicBuilder(`uns-infra/${MqttTopicBuilder.sanitizeTopicPart(packageJson.name)}/${MqttTopicBuilder.sanitizeTopicPart(packageJson.version)}/${MqttTopicBuilder.sanitizeTopicPart(processName)}/`);\n\n // Generate the processStatusTopic using the builder.\n this.processStatusTopic = this.topicBuilder.getProcessStatusTopic();\n // Derive the instanceStatusTopic by appending the instance name.\n this.instanceStatusTopic = this.processStatusTopic + instanceName + \"/\";\n\n // Concatenate processName with instanceName for the worker identification.\n this.instanceNameWithSuffix = `${processName}-${instanceName}`;\n \n const mqttParameters: IMqttParameters = {\n mqttSubToTopics: unsParameters?.mqttSubToTopics ?? [],\n username: unsParameters?.username ?? \"\",\n password: unsParameters?.password ?? \"\",\n mqttSSL: unsParameters?.mqttSSL ?? false,\n statusTopic: this.instanceStatusTopic,\n };\n this.unsParameters = unsParameters ?? {};\n this.startQueueWorker(mqttHost, this.instanceNameWithSuffix, mqttParameters, publisherActive, subscriberActive);\n }\n\n /**\n * Resolve object identity from explicit fields or the tail of the topic path.\n * Falls back to parsing when not provided for backward compatibility.\n */\n private resolveObjectIdentity(msg: IMqttMessage): { objectType?: UnsObjectType; objectId?: UnsObjectId; asset?: UnsAsset } {\n const providedType = msg.objectType;\n const providedId = msg.objectId;\n const providedAsset = msg.asset;\n\n const topicParts = msg.topic.split(\"/\").filter((part) => part.length > 0);\n const hasObjectTail = topicParts.length >= 2;\n const parsedType = hasObjectTail ? topicParts[topicParts.length - 2] as UnsObjectType : undefined;\n const parsedId = hasObjectTail ? topicParts[topicParts.length - 1] as UnsObjectId : undefined;\n const parsedAsset = hasObjectTail\n ? (topicParts.length >= 3 ? topicParts[topicParts.length - 3] as UnsAsset : undefined)\n : (topicParts.length >= 1 ? topicParts[topicParts.length - 1] as UnsAsset : undefined);\n\n const objectType = providedType ?? parsedType;\n const objectId = providedId ?? parsedId ?? \"main\";\n const asset = providedAsset ?? parsedAsset;\n\n // If values are provided, trust them; otherwise derive from topic.\n if (!providedType || !providedId) {\n if (parsedType && parsedId) {\n logger.warn(`${this.instanceNameWithSuffix} - objectType/objectId missing; derived from topic tail ${parsedType}/${parsedId}`);\n } else {\n logger.warn(`${this.instanceNameWithSuffix} - objectType/objectId missing; defaulting objectId to 'main' for topic '${msg.topic}'. Expected topic to end with '<objectType>/<objectId>/'`);\n }\n }\n // Asset is optional; no warning on mismatch to avoid noisy logs when base topics don't carry it.\n\n msg.objectType = objectType;\n msg.objectId = objectId;\n msg.asset = asset;\n\n return { objectType, objectId, asset };\n }\n\n /**\n * Ensure the topic ends with a trailing slash for attribute concatenation.\n */\n private normalizeTopicWithObject(topic: string): string {\n return topic.endsWith(\"/\") ? topic : `${topic}/`;\n }\n\n /**\n * Starts a worker thread to process the throttled publish queue.\n */\n private startQueueWorker(\n mqttHost: string,\n instanceNameWithSuffix: string,\n mqttParameters: IMqttParameters,\n publisherActive: boolean,\n subscriberActive: boolean\n ): void {\n const workerData: IMqttWorkerData = {\n publishThrottlingDelay: this.unsParameters.publishThrottlingDelay ?? 1,\n subscribeThrottlingDelay: this.unsParameters.subscribeThrottlingDelay ?? 1,\n persistToDisk: false,\n mqttHost: mqttHost,\n instanceNameWithSuffix: instanceNameWithSuffix,\n mqttParameters: mqttParameters,\n publisherActive,\n subscriberActive\n };\n\n this.worker = new Worker(workerScriptPath, { workerData });\n\n this.worker.on(\"message\", (msg) => {\n if (msg && msg.command === \"enqueueResult\" && msg.id) {\n const pending = this.pendingEnqueues.get(msg.id);\n if (pending) {\n if (msg.status === \"success\" && msg.topic && msg.message) {\n pending.resolve();\n } else {\n pending.reject(new Error(msg.error));\n }\n this.pendingEnqueues.delete(msg.id);\n }\n } else if (msg && msg.command === \"input\") {\n this.event.emit(\"input\", { topic: msg.topic, message: msg.message.toString(), packet: msg.packet });\n } else if (msg && (msg.command === \"handover_subscriber\" || msg.command === \"handover_publisher\")) {\n this.event.emit(\"mqttWorker\", { command: msg.command, batchSize: msg.batchSize, referenceHash: msg.referenceHash, instanceName: this.instanceName });\n } else if (msg && msg.command === \"mqttProxyStatus\") {\n this.event.emit(\"mqttProxyStatus\", { event: msg.event, value: msg.value, uom: msg.uom, statusTopic: msg.statusTopic });\n }\n });\n\n this.worker.on(\"error\", (err) => {\n logger.error(\"Error in worker:\", err);\n });\n\n this.worker.on(\"exit\", (code) => {\n if (code !== 0) {\n logger.error(`Worker exited with code ${code}`);\n }\n });\n }\n\n /**\n * Enqueues a message to the worker queue.\n *\n * @param topic - The topic to which the message belongs.\n * @param message - The message to be enqueued.\n * @param options - Optional publish options.\n * @returns A promise that resolves when the message is successfully enqueued.\n */\n private async enqueueMessageToWorkerQueue(topic: string, message: string, options?: IClientPublishOptions): Promise<void> {\n return new Promise((resolve, reject) => {\n // const id: string = String(this.currentSequenceId.get(topic) ?? 0);\n const id = `${Date.now()}-${Math.random()}`;\n this.pendingEnqueues.set(id, { resolve, reject });\n this.worker.postMessage({ command: \"enqueue\", id, topic, message, options });\n });\n }\n\n /**\n * Sets the publisher active state.\n *\n * @param batchSize - Optional batch size.\n * @param referenceHash - Optional reference hash.\n */\n public setPublisherActive(batchSize?: number, referenceHash?: string): void {\n this.worker.postMessage({ command: \"setPublisherActive\", batchSize, referenceHash });\n }\n\n /**\n * Sets the publisher to passive mode.\n * @returns A promise that resolves when the publisher is set to passive.\n */\n public setPublisherPassive(): Promise<UnsEvents[\"mqttWorker\"]> {\n this.worker.postMessage({ command: \"setPublisherPassive\"});\n return new Promise((resolve) => {\n this.event.on(\"mqttWorker\", (msg: UnsEvents[\"mqttWorker\"]) => {\n if (msg.command === \"handover_publisher\") {\n logger.info(`${this.instanceNameWithSuffix} - Publisher set to passive.`);\n resolve(msg);\n }\n });\n });\n }\n\n /**\n * Sets the subscriber active state.\n *\n * @param batchSize - Optional batch size.\n * @param referenceHash - Optional reference hash.\n */\n public setSubscriberActive(batchSize?: number, referenceHash?: string): void {\n this.worker.postMessage({ command: \"setSubscriberActive\", batchSize, referenceHash });\n }\n\n /**\n * Sets the subscriber to passive mode.\n * @returns A promise that resolves when the subscriber is set to passive.\n */\n public setSubscriberPassive(): Promise<UnsEvents[\"mqttWorker\"]> {\n this.worker.postMessage({ command: \"setSubscriberPassive\"});\n return new Promise((resolve) => {\n this.event.on(\"mqttWorker\", (msg: UnsEvents[\"mqttWorker\"]) => {\n if (msg.command === \"handover_subscriber\") {\n logger.info(`${this.instanceNameWithSuffix} - Publisher set to passive.`);\n resolve(msg);\n }\n });\n });\n }\n\n\n /**\n * Sets the subscriber to passive mode and allows the publisher to run\n * until the queue is empty (all messages are processed).\n */\n public async setSubscriberPassiveAndDrainQueue(): Promise<UnsEvents[\"mqttWorker\"]> {\n return new Promise(async (resolve) => {\n const mqttWorkerData = await this.setSubscriberPassive();\n while (this.pendingEnqueues.size > 0) {\n await new Promise((resolve) => setTimeout(resolve, 100)); // Poll every 100ms\n }\n logger.info(`${this.instanceNameWithSuffix} - Subscriber set to passive and queue drained.`);\n resolve(mqttWorkerData);\n });\n }\n\n /**\n * Processes and publishes MQTT messages based on the selected message mode.\n *\n * @param mqttMessage - The MQTT message object.\n * @param mode - The message mode (Raw, Delta, or Both).\n */\n public publishMqttMessage(mqttMessage: IMqttMessage | null, mode: MessageMode = MessageMode.Raw) {\n if (mqttMessage) {\n if (mqttMessage.packet) {\n const time = UnsPacket.formatToISO8601(new Date());\n switch (mode) {\n case MessageMode.Raw: {\n this.processAndEnqueueMessage(mqttMessage, time, false);\n break;\n }\n case MessageMode.Delta: {\n const deltaMessage = { ...mqttMessage };\n deltaMessage.attribute = `${mqttMessage.attribute}-delta`;\n deltaMessage.description = `${mqttMessage.description} (delta)`;\n this.processAndEnqueueMessage(deltaMessage, time, true);\n break;\n }\n case MessageMode.Both: {\n this.processAndEnqueueMessage(mqttMessage, time, false);\n const deltaMessageBoth = { ...mqttMessage };\n deltaMessageBoth.attribute = `${mqttMessage.attribute}-delta`;\n deltaMessageBoth.description = `${mqttMessage.description} (delta)`;\n this.processAndEnqueueMessage(deltaMessageBoth, time, true);\n break;\n }\n } \n } else {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing mqtt message: mqttMessage.packet must be defined.`);\n }\n } else {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing mqtt message: mqttMessage must be defined.`);\n }\n }\n\n /**\n * Publishes a message to a specified topic.\n *\n * @param topic - The MQTT topic.\n * @param message - The message to publish.\n * @returns A promise that resolves when enqueued.\n */\n public publishMessage(topic: string, message: string): Promise<void> {\n return this.enqueueMessageToWorkerQueue(topic, message);\n }\n\n /**\n * Parses an MQTT packet from a JSON string.\n *\n * @param mqttPacket - The MQTT packet string.\n * @returns A parsed IUnsPacket object or null.\n */\n public parseMqttPacket(mqttPacket: string): IUnsPacket | null {\n return UnsPacket.parseMqttPacket(mqttPacket, this.instanceNameWithSuffix);\n }\n\n /**\n * Subscribes asynchronously to one or more topics.\n *\n * @param topics - A topic or list of topics.\n */\n public subscribeAsync(topics: string | string[]): void {\n this.worker.postMessage({ command: \"subscribeAsync\", topics });\n }\n\n /**\n * Unsubscribes asynchronously from the given topics.\n *\n * @param topics - A list of topics.\n */\n public unsubscribeAsync(topics: string[]): void {\n this.worker.postMessage({ command: \"unsubscribeAsync\", topics });\n }\n\n /**\n * Processes and enqueues a message to the worker queue, including handling\n * sequencing, value differences, and tracking of unique topics.\n *\n * @param msg - The MQTT message to process.\n * @param time - The timestamp.\n * @param valueIsCumulative - Whether the value is cumulative.\n */\n private async processAndEnqueueMessage(msg: IMqttMessage, time: string, valueIsCumulative: boolean = false): Promise<void> {\n try {\n const attributeType =\n msg.packet.message.data ? UnsAttributeType.Data :\n msg.packet.message.event ? UnsAttributeType.Event :\n msg.packet.message.table ? UnsAttributeType.Table : null;\n \n let dataGroup = \"\";\n if (attributeType == UnsAttributeType.Data)\n dataGroup = msg.packet.message.data.dataGroup ?? \"\";\n if (attributeType == UnsAttributeType.Table)\n dataGroup = msg.packet.message.table.dataGroup ?? \"\";\n if (attributeType == UnsAttributeType.Event)\n dataGroup = msg.packet.message.event.dataGroup ?? \"\";\n\n const { objectType, objectId, asset } = this.resolveObjectIdentity(msg);\n const normalizedTopic = this.normalizeTopicWithObject(msg.topic);\n msg.topic = normalizedTopic;\n\n this.registerUniqueTopic({\n timestamp: time,\n topic: msg.topic,\n attribute: msg.attribute,\n attributeType: attributeType,\n description: msg.description,\n tags: msg.tags,\n attributeNeedsPersistence: msg.attributeNeedsPersistence,\n dataGroup,\n asset,\n objectType,\n objectId\n });\n\n const publishTopic = `${msg.topic}${asset ? `${asset}/` : \"\"}${objectType ? `${objectType}/` : \"\"}${objectId ? `${objectId}/` : \"\"}${msg.attribute}`;\n const sequenceId = this.currentSequenceId.get(msg.topic) ?? 0;\n this.currentSequenceId.set(msg.topic, sequenceId + 1);\n msg.packet.sequenceId = sequenceId;\n\n if (msg.packet.message.data) {\n const newValue = msg.packet.message.data.value;\n const newUom: MeasurementUnit = msg.packet.message.data.uom;\n const lastValueEntry = this.lastValues.get(publishTopic);\n const currentTime = new Date(msg.packet.message.data.time);\n\n if (lastValueEntry) {\n const intervalBetweenMessages = currentTime.getTime() - lastValueEntry.timestamp.getTime();\n const lastValue = lastValueEntry.value;\n this.lastValues.set(publishTopic, { value: newValue, uom: newUom, timestamp: currentTime });\n // Compute the delta and manage cumulative resets\n if (valueIsCumulative == true && typeof newValue === \"number\" && typeof lastValue === \"number\") {\n // Skip if newValue is 0 (likely a glitch)\n if (newValue === 0) {\n return; // Don't process or enqueue\n }\n const delta = newValue - lastValue;\n msg.packet.message.data.value = delta < 0 ? newValue : delta;\n }\n msg.packet.interval = intervalBetweenMessages;\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n this.lastValues.set(publishTopic, { value: newValue, uom: newUom, timestamp: currentTime });\n logger.debug(`${this.instanceNameWithSuffix} - Need one more packet to calculate interval on topic ${publishTopic}`);\n if (valueIsCumulative === false) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n logger.debug(`${this.instanceNameWithSuffix} - Need one more packet to calculate difference on value in data for topic ${publishTopic}`);\n }\n }\n } else if (msg.packet.message.command) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else if (msg.packet.message.event) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else if (msg.packet.message.table) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n }\n } catch (error: any) {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing message to topic ${msg.topic}${msg.attribute}: ${error.message}`);\n }\n }\n\n /**\n * Stops the UnsProxy instance and cleans up resources.\n */\n public async stop(): Promise<void> {\n super.stop();\n // Terminate the worker thread if it exists.\n if (this.worker) {\n try {\n const exitCode = await this.worker.terminate();\n logger.info(`${this.instanceNameWithSuffix} - Worker terminated with exit code ${exitCode}`);\n } catch (error: any) {\n logger.error(`${this.instanceNameWithSuffix} - Error terminating worker: ${error.message}`);\n }\n }\n \n // Optionally, handle any pending enqueues.\n for (const [id, pending] of this.pendingEnqueues) {\n pending.reject(new Error(\"UnsProxy has been stopped\"));\n this.pendingEnqueues.delete(id);\n }\n }\n\n}\n"]}
|
|
1
|
+
{"version":3,"file":"uns-mqtt-proxy.js","sourceRoot":"","sources":["../../src/uns-mqtt/uns-mqtt-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAElC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,MAAM,MAAM,cAAc,CAAC;AAKlC,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,QAAQ,MAAM,qBAAqB,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAExD,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;AAC5D,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC,CAAC;AAEtE,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,M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,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACjD,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC,CAAC;YACvD,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAClC,CAAC;IACH,CAAC;CAEF","sourcesContent":["import { readFileSync } from \"fs\";\nimport { IClientPublishOptions } from \"mqtt\";\nimport * as path from \"path\";\nimport { Worker } from \"worker_threads\";\nimport { fileURLToPath } from \"url\";\nimport { basePath } from \"../base-path.js\";\nimport logger from \"../logger.js\";\nimport { IMqttMessage, IUnsPacket, IUnsParameters, UnsEvents, ValueType } from \"../uns/uns-interfaces.js\";\nimport type { UnsObjectId, UnsObjectType } from \"../uns/uns-object.js\";\nimport type { UnsAsset } from \"../uns/uns-asset.js\";\nimport { MeasurementUnit } from \"../uns/uns-measurements.js\";\nimport { UnsPacket } from \"../uns/uns-packet.js\";\nimport { IMqttParameters, IMqttWorkerData } from \"./mqtt-interfaces.js\";\nimport { MqttTopicBuilder } from \"./mqtt-topic-builder.js\";\nimport UnsProxy from \"../uns/uns-proxy.js\";\nimport { UnsAttributeType } from \"../graphql/schema.js\";\n\nconst packageJsonPath = path.join(basePath, \"package.json\");\nconst packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\"));\n\nconst moduleDirectory = path.dirname(fileURLToPath(import.meta.url));\nconst packageRoot = path.resolve(moduleDirectory, \"..\", \"..\");\nconst workerScriptPath = path.join(packageRoot, \"dist/uns-mqtt/mqtt-worker-init.js\");\n\nexport enum MessageMode {\n Raw = 'raw', // Send only the original message\n Delta = 'delta', // Send only the delta message\n Both = 'both' // Send both the original and delta messages\n}\n\nexport default class UnsMqttProxy extends UnsProxy {\n private lastValues: Map<string, { value: ValueType; uom: string; timestamp: Date }> = new Map();\n private worker: Worker;\n private pendingEnqueues: Map<string, { resolve: () => void; reject: (reason?: any) => void }> = new Map();\n private unsParameters: IUnsParameters;\n protected processStatusTopic: string;\n public instanceName: string;\n private currentSequenceId: Map<string, number> = new Map();\n private topicBuilder: MqttTopicBuilder;\n\n constructor(\n mqttHost: string,\n processName: string,\n instanceName: string,\n unsParameters?: IUnsParameters,\n publisherActive: boolean = false,\n subscriberActive: boolean = false\n ) {\n super();\n this.instanceName = instanceName;\n // Create the topic builder using packageJson values and the processName.\n this.topicBuilder = new MqttTopicBuilder(`uns-infra/${MqttTopicBuilder.sanitizeTopicPart(packageJson.name)}/${MqttTopicBuilder.sanitizeTopicPart(packageJson.version)}/${MqttTopicBuilder.sanitizeTopicPart(processName)}/`);\n\n // Generate the processStatusTopic using the builder.\n this.processStatusTopic = this.topicBuilder.getProcessStatusTopic();\n // Derive the instanceStatusTopic by appending the instance name.\n this.instanceStatusTopic = this.processStatusTopic + instanceName + \"/\";\n\n // Concatenate processName with instanceName for the worker identification.\n this.instanceNameWithSuffix = `${processName}-${instanceName}`;\n \n const mqttParameters: IMqttParameters = {\n mqttSubToTopics: unsParameters?.mqttSubToTopics ?? [],\n username: unsParameters?.username ?? \"\",\n password: unsParameters?.password ?? \"\",\n mqttSSL: unsParameters?.mqttSSL ?? false,\n statusTopic: this.instanceStatusTopic,\n };\n this.unsParameters = unsParameters ?? {};\n this.startQueueWorker(mqttHost, this.instanceNameWithSuffix, mqttParameters, publisherActive, subscriberActive);\n }\n\n /**\n * Resolve object identity from explicit fields or the tail of the topic path.\n * Falls back to parsing when not provided for backward compatibility.\n */\n private resolveObjectIdentity(msg: IMqttMessage): { objectType?: UnsObjectType; objectId?: UnsObjectId; asset?: UnsAsset } {\n const providedType = msg.objectType;\n const providedId = msg.objectId;\n const providedAsset = msg.asset;\n\n const topicParts = msg.topic.split(\"/\").filter((part) => part.length > 0);\n const hasObjectTail = topicParts.length >= 2;\n const parsedType = hasObjectTail ? topicParts[topicParts.length - 2] as UnsObjectType : undefined;\n const parsedId = hasObjectTail ? topicParts[topicParts.length - 1] as UnsObjectId : undefined;\n const parsedAsset = hasObjectTail\n ? (topicParts.length >= 3 ? topicParts[topicParts.length - 3] as UnsAsset : undefined)\n : (topicParts.length >= 1 ? topicParts[topicParts.length - 1] as UnsAsset : undefined);\n\n const objectType = providedType ?? parsedType;\n const objectId = providedId ?? parsedId ?? \"main\";\n const asset = providedAsset ?? parsedAsset;\n\n // If values are provided, trust them; otherwise derive from topic.\n if (!providedType || !providedId) {\n if (parsedType && parsedId) {\n logger.warn(`${this.instanceNameWithSuffix} - objectType/objectId missing; derived from topic tail ${parsedType}/${parsedId}`);\n } else {\n logger.warn(`${this.instanceNameWithSuffix} - objectType/objectId missing; defaulting objectId to 'main' for topic '${msg.topic}'. Expected topic to end with '<objectType>/<objectId>/'`);\n }\n }\n // Asset is optional; no warning on mismatch to avoid noisy logs when base topics don't carry it.\n\n msg.objectType = objectType;\n msg.objectId = objectId;\n msg.asset = asset;\n\n return { objectType, objectId, asset };\n }\n\n /**\n * Ensure the topic ends with a trailing slash for attribute concatenation.\n */\n private normalizeTopicWithObject(topic: string): string {\n return topic.endsWith(\"/\") ? topic : `${topic}/`;\n }\n\n /**\n * Starts a worker thread to process the throttled publish queue.\n */\n private startQueueWorker(\n mqttHost: string,\n instanceNameWithSuffix: string,\n mqttParameters: IMqttParameters,\n publisherActive: boolean,\n subscriberActive: boolean\n ): void {\n const workerData: IMqttWorkerData = {\n publishThrottlingDelay: this.unsParameters.publishThrottlingDelay ?? 1,\n subscribeThrottlingDelay: this.unsParameters.subscribeThrottlingDelay ?? 1,\n persistToDisk: false,\n mqttHost: mqttHost,\n instanceNameWithSuffix: instanceNameWithSuffix,\n mqttParameters: mqttParameters,\n publisherActive,\n subscriberActive\n };\n\n this.worker = new Worker(workerScriptPath, { workerData });\n\n this.worker.on(\"message\", (msg) => {\n if (msg && msg.command === \"enqueueResult\" && msg.id) {\n const pending = this.pendingEnqueues.get(msg.id);\n if (pending) {\n if (msg.status === \"success\" && msg.topic && msg.message) {\n pending.resolve();\n } else {\n pending.reject(new Error(msg.error));\n }\n this.pendingEnqueues.delete(msg.id);\n }\n } else if (msg && msg.command === \"input\") {\n this.event.emit(\"input\", { topic: msg.topic, message: msg.message.toString(), packet: msg.packet });\n } else if (msg && (msg.command === \"handover_subscriber\" || msg.command === \"handover_publisher\")) {\n this.event.emit(\"mqttWorker\", { command: msg.command, batchSize: msg.batchSize, referenceHash: msg.referenceHash, instanceName: this.instanceName });\n } else if (msg && msg.command === \"mqttProxyStatus\") {\n this.event.emit(\"mqttProxyStatus\", { event: msg.event, value: msg.value, uom: msg.uom, statusTopic: msg.statusTopic });\n }\n });\n\n this.worker.on(\"error\", (err) => {\n logger.error(\"Error in worker:\", err);\n });\n\n this.worker.on(\"exit\", (code) => {\n if (code !== 0) {\n logger.error(`Worker exited with code ${code}`);\n }\n });\n }\n\n /**\n * Enqueues a message to the worker queue.\n *\n * @param topic - The topic to which the message belongs.\n * @param message - The message to be enqueued.\n * @param options - Optional publish options.\n * @returns A promise that resolves when the message is successfully enqueued.\n */\n private async enqueueMessageToWorkerQueue(topic: string, message: string, options?: IClientPublishOptions): Promise<void> {\n return new Promise((resolve, reject) => {\n // const id: string = String(this.currentSequenceId.get(topic) ?? 0);\n const id = `${Date.now()}-${Math.random()}`;\n this.pendingEnqueues.set(id, { resolve, reject });\n this.worker.postMessage({ command: \"enqueue\", id, topic, message, options });\n });\n }\n\n /**\n * Sets the publisher active state.\n *\n * @param batchSize - Optional batch size.\n * @param referenceHash - Optional reference hash.\n */\n public setPublisherActive(batchSize?: number, referenceHash?: string): void {\n this.worker.postMessage({ command: \"setPublisherActive\", batchSize, referenceHash });\n }\n\n /**\n * Sets the publisher to passive mode.\n * @returns A promise that resolves when the publisher is set to passive.\n */\n public setPublisherPassive(): Promise<UnsEvents[\"mqttWorker\"]> {\n this.worker.postMessage({ command: \"setPublisherPassive\"});\n return new Promise((resolve) => {\n this.event.on(\"mqttWorker\", (msg: UnsEvents[\"mqttWorker\"]) => {\n if (msg.command === \"handover_publisher\") {\n logger.info(`${this.instanceNameWithSuffix} - Publisher set to passive.`);\n resolve(msg);\n }\n });\n });\n }\n\n /**\n * Sets the subscriber active state.\n *\n * @param batchSize - Optional batch size.\n * @param referenceHash - Optional reference hash.\n */\n public setSubscriberActive(batchSize?: number, referenceHash?: string): void {\n this.worker.postMessage({ command: \"setSubscriberActive\", batchSize, referenceHash });\n }\n\n /**\n * Sets the subscriber to passive mode.\n * @returns A promise that resolves when the subscriber is set to passive.\n */\n public setSubscriberPassive(): Promise<UnsEvents[\"mqttWorker\"]> {\n this.worker.postMessage({ command: \"setSubscriberPassive\"});\n return new Promise((resolve) => {\n this.event.on(\"mqttWorker\", (msg: UnsEvents[\"mqttWorker\"]) => {\n if (msg.command === \"handover_subscriber\") {\n logger.info(`${this.instanceNameWithSuffix} - Publisher set to passive.`);\n resolve(msg);\n }\n });\n });\n }\n\n\n /**\n * Sets the subscriber to passive mode and allows the publisher to run\n * until the queue is empty (all messages are processed).\n */\n public async setSubscriberPassiveAndDrainQueue(): Promise<UnsEvents[\"mqttWorker\"]> {\n return new Promise(async (resolve) => {\n const mqttWorkerData = await this.setSubscriberPassive();\n while (this.pendingEnqueues.size > 0) {\n await new Promise((resolve) => setTimeout(resolve, 100)); // Poll every 100ms\n }\n logger.info(`${this.instanceNameWithSuffix} - Subscriber set to passive and queue drained.`);\n resolve(mqttWorkerData);\n });\n }\n\n /**\n * Processes and publishes MQTT messages based on the selected message mode.\n *\n * @param mqttMessage - The MQTT message object.\n * @param mode - The message mode (Raw, Delta, or Both).\n */\n public publishMqttMessage(mqttMessage: IMqttMessage | null, mode: MessageMode = MessageMode.Raw) {\n if (mqttMessage) {\n if (mqttMessage.packet) {\n const time = UnsPacket.formatToISO8601(new Date());\n switch (mode) {\n case MessageMode.Raw: {\n this.processAndEnqueueMessage(mqttMessage, time, false);\n break;\n }\n case MessageMode.Delta: {\n const deltaMessage = { ...mqttMessage };\n deltaMessage.attribute = `${mqttMessage.attribute}-delta`;\n deltaMessage.description = `${mqttMessage.description} (delta)`;\n this.processAndEnqueueMessage(deltaMessage, time, true);\n break;\n }\n case MessageMode.Both: {\n this.processAndEnqueueMessage(mqttMessage, time, false);\n const deltaMessageBoth = { ...mqttMessage };\n deltaMessageBoth.attribute = `${mqttMessage.attribute}-delta`;\n deltaMessageBoth.description = `${mqttMessage.description} (delta)`;\n this.processAndEnqueueMessage(deltaMessageBoth, time, true);\n break;\n }\n } \n } else {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing mqtt message: mqttMessage.packet must be defined.`);\n }\n } else {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing mqtt message: mqttMessage must be defined.`);\n }\n }\n\n /**\n * Publishes a message to a specified topic.\n *\n * @param topic - The MQTT topic.\n * @param message - The message to publish.\n * @returns A promise that resolves when enqueued.\n */\n public publishMessage(topic: string, message: string): Promise<void> {\n return this.enqueueMessageToWorkerQueue(topic, message);\n }\n\n /**\n * Parses an MQTT packet from a JSON string.\n *\n * @param mqttPacket - The MQTT packet string.\n * @returns A parsed IUnsPacket object or null.\n */\n public parseMqttPacket(mqttPacket: string): IUnsPacket | null {\n return UnsPacket.parseMqttPacket(mqttPacket, this.instanceNameWithSuffix);\n }\n\n /**\n * Subscribes asynchronously to one or more topics.\n *\n * @param topics - A topic or list of topics.\n */\n public subscribeAsync(topics: string | string[]): void {\n this.worker.postMessage({ command: \"subscribeAsync\", topics });\n }\n\n /**\n * Unsubscribes asynchronously from the given topics.\n *\n * @param topics - A list of topics.\n */\n public unsubscribeAsync(topics: string[]): void {\n this.worker.postMessage({ command: \"unsubscribeAsync\", topics });\n }\n\n /**\n * Processes and enqueues a message to the worker queue, including handling\n * sequencing, value differences, and tracking of unique topics.\n *\n * @param msg - The MQTT message to process.\n * @param time - The timestamp.\n * @param valueIsCumulative - Whether the value is cumulative.\n */\n private async processAndEnqueueMessage(msg: IMqttMessage, time: string, valueIsCumulative: boolean = false): Promise<void> {\n try {\n const attributeType =\n msg.packet.message.data ? UnsAttributeType.Data :\n msg.packet.message.event ? UnsAttributeType.Event :\n msg.packet.message.table ? UnsAttributeType.Table : null;\n \n let dataGroup = \"\";\n if (attributeType == UnsAttributeType.Data)\n dataGroup = msg.packet.message.data.dataGroup ?? \"\";\n if (attributeType == UnsAttributeType.Table)\n dataGroup = msg.packet.message.table.dataGroup ?? \"\";\n if (attributeType == UnsAttributeType.Event)\n dataGroup = msg.packet.message.event.dataGroup ?? \"\";\n\n const { objectType, objectId, asset } = this.resolveObjectIdentity(msg);\n const normalizedTopic = this.normalizeTopicWithObject(msg.topic);\n msg.topic = normalizedTopic;\n const description = msg.description ?? \"\";\n\n this.registerUniqueTopic({\n timestamp: time,\n topic: msg.topic,\n attribute: msg.attribute,\n attributeType: attributeType,\n description,\n tags: msg.tags,\n attributeNeedsPersistence: msg.attributeNeedsPersistence,\n dataGroup,\n asset,\n assetDescription: msg.assetDescription,\n objectType,\n objectTypeDescription: msg.objectTypeDescription,\n objectId\n });\n\n const publishTopic = `${msg.topic}${asset ? `${asset}/` : \"\"}${objectType ? `${objectType}/` : \"\"}${objectId ? `${objectId}/` : \"\"}${msg.attribute}`;\n const sequenceId = this.currentSequenceId.get(msg.topic) ?? 0;\n this.currentSequenceId.set(msg.topic, sequenceId + 1);\n msg.packet.sequenceId = sequenceId;\n\n if (msg.packet.message.data) {\n const newValue = msg.packet.message.data.value;\n const newUom: MeasurementUnit = msg.packet.message.data.uom;\n const lastValueEntry = this.lastValues.get(publishTopic);\n const currentTime = new Date(msg.packet.message.data.time);\n\n if (lastValueEntry) {\n const intervalBetweenMessages = currentTime.getTime() - lastValueEntry.timestamp.getTime();\n const lastValue = lastValueEntry.value;\n this.lastValues.set(publishTopic, { value: newValue, uom: newUom, timestamp: currentTime });\n // Compute the delta and manage cumulative resets\n if (valueIsCumulative == true && typeof newValue === \"number\" && typeof lastValue === \"number\") {\n // Skip if newValue is 0 (likely a glitch)\n if (newValue === 0) {\n return; // Don't process or enqueue\n }\n const delta = newValue - lastValue;\n msg.packet.message.data.value = delta < 0 ? newValue : delta;\n }\n msg.packet.interval = intervalBetweenMessages;\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n this.lastValues.set(publishTopic, { value: newValue, uom: newUom, timestamp: currentTime });\n logger.debug(`${this.instanceNameWithSuffix} - Need one more packet to calculate interval on topic ${publishTopic}`);\n if (valueIsCumulative === false) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n logger.debug(`${this.instanceNameWithSuffix} - Need one more packet to calculate difference on value in data for topic ${publishTopic}`);\n }\n }\n } else if (msg.packet.message.command) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else if (msg.packet.message.event) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else if (msg.packet.message.table) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n }\n } catch (error: any) {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing message to topic ${msg.topic}${msg.attribute}: ${error.message}`);\n }\n }\n\n /**\n * Stops the UnsProxy instance and cleans up resources.\n */\n public async stop(): Promise<void> {\n super.stop();\n // Terminate the worker thread if it exists.\n if (this.worker) {\n try {\n const exitCode = await this.worker.terminate();\n logger.info(`${this.instanceNameWithSuffix} - Worker terminated with exit code ${exitCode}`);\n } catch (error: any) {\n logger.error(`${this.instanceNameWithSuffix} - Error terminating worker: ${error.message}`);\n }\n }\n \n // Optionally, handle any pending enqueues.\n for (const [id, pending] of this.pendingEnqueues) {\n pending.reject(new Error(\"UnsProxy has been stopped\"));\n this.pendingEnqueues.delete(id);\n }\n }\n\n}\n"]}
|