node-opcua-server 2.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/.mocharc.yml +10 -0
  2. package/LICENSE +20 -0
  3. package/dist/base_server.d.ts +110 -0
  4. package/dist/base_server.js +476 -0
  5. package/dist/base_server.js.map +1 -0
  6. package/dist/factory.d.ts +10 -0
  7. package/dist/factory.js +24 -0
  8. package/dist/factory.js.map +1 -0
  9. package/dist/history_server_capabilities.d.ts +35 -0
  10. package/dist/history_server_capabilities.js +44 -0
  11. package/dist/history_server_capabilities.js.map +1 -0
  12. package/dist/i_channel_data.d.ts +13 -0
  13. package/dist/i_channel_data.js +3 -0
  14. package/dist/i_channel_data.js.map +1 -0
  15. package/dist/i_register_server_manager.d.ts +16 -0
  16. package/dist/i_register_server_manager.js +3 -0
  17. package/dist/i_register_server_manager.js.map +1 -0
  18. package/dist/i_server_side_publish_engine.d.ts +36 -0
  19. package/dist/i_server_side_publish_engine.js +50 -0
  20. package/dist/i_server_side_publish_engine.js.map +1 -0
  21. package/dist/i_socket_data.d.ts +11 -0
  22. package/dist/i_socket_data.js +3 -0
  23. package/dist/i_socket_data.js.map +1 -0
  24. package/dist/index.d.ts +14 -0
  25. package/dist/index.js +27 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/monitored_item.d.ts +173 -0
  28. package/dist/monitored_item.js +1006 -0
  29. package/dist/monitored_item.js.map +1 -0
  30. package/dist/node_sampler.d.ts +3 -0
  31. package/dist/node_sampler.js +76 -0
  32. package/dist/node_sampler.js.map +1 -0
  33. package/dist/opcua_server.d.ts +668 -0
  34. package/dist/opcua_server.js +2407 -0
  35. package/dist/opcua_server.js.map +1 -0
  36. package/dist/queue.d.ts +11 -0
  37. package/dist/queue.js +71 -0
  38. package/dist/queue.js.map +1 -0
  39. package/dist/register_server_manager.d.ts +92 -0
  40. package/dist/register_server_manager.js +574 -0
  41. package/dist/register_server_manager.js.map +1 -0
  42. package/dist/register_server_manager_hidden.d.ts +17 -0
  43. package/dist/register_server_manager_hidden.js +28 -0
  44. package/dist/register_server_manager_hidden.js.map +1 -0
  45. package/dist/register_server_manager_mdns_only.d.ts +19 -0
  46. package/dist/register_server_manager_mdns_only.js +58 -0
  47. package/dist/register_server_manager_mdns_only.js.map +1 -0
  48. package/dist/server_capabilities.d.ts +61 -0
  49. package/dist/server_capabilities.js +109 -0
  50. package/dist/server_capabilities.js.map +1 -0
  51. package/dist/server_end_point.d.ts +180 -0
  52. package/dist/server_end_point.js +825 -0
  53. package/dist/server_end_point.js.map +1 -0
  54. package/dist/server_engine.d.ts +311 -0
  55. package/dist/server_engine.js +1659 -0
  56. package/dist/server_engine.js.map +1 -0
  57. package/dist/server_publish_engine.d.ts +109 -0
  58. package/dist/server_publish_engine.js +531 -0
  59. package/dist/server_publish_engine.js.map +1 -0
  60. package/dist/server_publish_engine_for_orphan_subscriptions.d.ts +16 -0
  61. package/dist/server_publish_engine_for_orphan_subscriptions.js +50 -0
  62. package/dist/server_publish_engine_for_orphan_subscriptions.js.map +1 -0
  63. package/dist/server_session.d.ts +176 -0
  64. package/dist/server_session.js +734 -0
  65. package/dist/server_session.js.map +1 -0
  66. package/dist/server_subscription.d.ts +393 -0
  67. package/dist/server_subscription.js +1313 -0
  68. package/dist/server_subscription.js.map +1 -0
  69. package/dist/sessions_compatible_for_transfer.d.ts +2 -0
  70. package/dist/sessions_compatible_for_transfer.js +36 -0
  71. package/dist/sessions_compatible_for_transfer.js.map +1 -0
  72. package/dist/validate_filter.d.ts +5 -0
  73. package/dist/validate_filter.js +64 -0
  74. package/dist/validate_filter.js.map +1 -0
  75. package/package.json +88 -0
  76. package/source/base_server.ts +617 -0
  77. package/source/factory.ts +25 -0
  78. package/source/history_server_capabilities.ts +75 -0
  79. package/source/i_channel_data.ts +17 -0
  80. package/source/i_register_server_manager.ts +24 -0
  81. package/source/i_server_side_publish_engine.ts +77 -0
  82. package/source/i_socket_data.ts +11 -0
  83. package/source/index.ts +14 -0
  84. package/source/monitored_item.ts +1303 -0
  85. package/source/node_sampler.ts +82 -0
  86. package/source/opcua_server.ts +3742 -0
  87. package/source/queue.ts +73 -0
  88. package/source/register_server_manager.ts +744 -0
  89. package/source/register_server_manager_hidden.ts +33 -0
  90. package/source/register_server_manager_mdns_only.ts +69 -0
  91. package/source/server_capabilities.ts +177 -0
  92. package/source/server_end_point.ts +1182 -0
  93. package/source/server_engine.ts +2167 -0
  94. package/source/server_publish_engine.ts +657 -0
  95. package/source/server_publish_engine_for_orphan_subscriptions.ts +52 -0
  96. package/source/server_session.ts +931 -0
  97. package/source/server_subscription.ts +1792 -0
  98. package/source/sessions_compatible_for_transfer.ts +33 -0
  99. package/source/validate_filter.ts +86 -0
  100. package/test_helpers/create_certificates.js +1 -0
@@ -0,0 +1,1313 @@
1
+ "use strict";
2
+ /**
3
+ * @module node-opcua-server
4
+ */
5
+ // tslint:disable:no-console
6
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.Subscription = exports.SubscriptionState = void 0;
17
+ const queue_1 = require("./queue");
18
+ const chalk = require("chalk");
19
+ const events_1 = require("events");
20
+ const node_opcua_address_space_1 = require("node-opcua-address-space");
21
+ const node_opcua_address_space_2 = require("node-opcua-address-space");
22
+ const node_opcua_assert_1 = require("node-opcua-assert");
23
+ const node_opcua_common_1 = require("node-opcua-common");
24
+ const node_opcua_data_model_1 = require("node-opcua-data-model");
25
+ const node_opcua_debug_1 = require("node-opcua-debug");
26
+ const node_opcua_nodeid_1 = require("node-opcua-nodeid");
27
+ const node_opcua_object_registry_1 = require("node-opcua-object-registry");
28
+ const node_opcua_secure_channel_1 = require("node-opcua-secure-channel");
29
+ const node_opcua_service_filter_1 = require("node-opcua-service-filter");
30
+ const node_opcua_service_subscription_1 = require("node-opcua-service-subscription");
31
+ const node_opcua_service_subscription_2 = require("node-opcua-service-subscription");
32
+ const node_opcua_status_code_1 = require("node-opcua-status-code");
33
+ const node_opcua_types_1 = require("node-opcua-types");
34
+ const monitored_item_1 = require("./monitored_item");
35
+ const validate_filter_1 = require("./validate_filter");
36
+ const i_server_side_publish_engine_1 = require("./i_server_side_publish_engine");
37
+ const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
38
+ const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
39
+ const warningLog = (0, node_opcua_debug_1.make_warningLog)(__filename);
40
+ const maxNotificationMessagesInQueue = 100;
41
+ var SubscriptionState;
42
+ (function (SubscriptionState) {
43
+ SubscriptionState[SubscriptionState["CLOSED"] = 1] = "CLOSED";
44
+ SubscriptionState[SubscriptionState["CREATING"] = 2] = "CREATING";
45
+ SubscriptionState[SubscriptionState["NORMAL"] = 3] = "NORMAL";
46
+ // The keep-alive counter is not used in this state.
47
+ SubscriptionState[SubscriptionState["LATE"] = 4] = "LATE";
48
+ // ready to be sent, but there are no Publish requests queued. When in this state, the next Publish
49
+ // request is processed when it is received. The keep-alive counter is not used in this state.
50
+ SubscriptionState[SubscriptionState["KEEPALIVE"] = 5] = "KEEPALIVE";
51
+ // alive counter to count down to 0 from its maximum.
52
+ SubscriptionState[SubscriptionState["TERMINATED"] = 6] = "TERMINATED";
53
+ })(SubscriptionState = exports.SubscriptionState || (exports.SubscriptionState = {}));
54
+ function _adjust_publishing_interval(publishingInterval) {
55
+ publishingInterval =
56
+ publishingInterval === undefined || Number.isNaN(publishingInterval)
57
+ ? Subscription.defaultPublishingInterval
58
+ : publishingInterval;
59
+ publishingInterval = Math.max(publishingInterval, Subscription.minimumPublishingInterval);
60
+ publishingInterval = Math.min(publishingInterval, Subscription.maximumPublishingInterval);
61
+ return publishingInterval;
62
+ }
63
+ const minimumMaxKeepAliveCount = 2;
64
+ const maximumMaxKeepAliveCount = 12000;
65
+ function _adjust_maxKeepAliveCount(maxKeepAliveCount /*,publishingInterval*/) {
66
+ maxKeepAliveCount = maxKeepAliveCount || minimumMaxKeepAliveCount;
67
+ maxKeepAliveCount = Math.max(maxKeepAliveCount, minimumMaxKeepAliveCount);
68
+ maxKeepAliveCount = Math.min(maxKeepAliveCount, maximumMaxKeepAliveCount);
69
+ return maxKeepAliveCount;
70
+ }
71
+ function _adjust_lifeTimeCount(lifeTimeCount, maxKeepAliveCount, publishingInterval) {
72
+ lifeTimeCount = lifeTimeCount || 1;
73
+ // let's make sure that lifeTimeCount is at least three time maxKeepAliveCount
74
+ // Note : the specs say ( part 3 - CreateSubscriptionParameter )
75
+ // "The lifetime count shall be a minimum of three times the keep keep-alive count."
76
+ lifeTimeCount = Math.max(lifeTimeCount, maxKeepAliveCount * 3);
77
+ const minTicks = Math.ceil((5 * 1000) / publishingInterval); // we want 5 seconds min
78
+ lifeTimeCount = Math.max(minTicks, lifeTimeCount);
79
+ return lifeTimeCount;
80
+ }
81
+ function _adjust_publishingEnable(publishingEnabled) {
82
+ return publishingEnabled === null || publishingEnabled === undefined ? true : !!publishingEnabled;
83
+ }
84
+ function _adjust_maxNotificationsPerPublish(maxNotificationsPerPublish) {
85
+ (0, node_opcua_assert_1.assert)(Subscription.maxNotificationPerPublishHighLimit > 0, "Subscription.maxNotificationPerPublishHighLimit must be positive");
86
+ maxNotificationsPerPublish = maxNotificationsPerPublish || 0;
87
+ (0, node_opcua_assert_1.assert)(typeof maxNotificationsPerPublish === "number");
88
+ // must be strictly positive
89
+ maxNotificationsPerPublish = maxNotificationsPerPublish >= 0 ? maxNotificationsPerPublish : 0;
90
+ if (maxNotificationsPerPublish === 0) {
91
+ // if zero then => use our HighLimit
92
+ maxNotificationsPerPublish = Subscription.maxNotificationPerPublishHighLimit;
93
+ }
94
+ else {
95
+ // if not zero then should be capped by maxNotificationPerPublishHighLimit
96
+ maxNotificationsPerPublish = Math.min(Subscription.maxNotificationPerPublishHighLimit, maxNotificationsPerPublish);
97
+ }
98
+ (0, node_opcua_assert_1.assert)(maxNotificationsPerPublish !== 0 && maxNotificationsPerPublish <= Subscription.maxNotificationPerPublishHighLimit);
99
+ return maxNotificationsPerPublish;
100
+ }
101
+ function w(s, length) {
102
+ return ("000" + s).substr(-length);
103
+ }
104
+ function t(d) {
105
+ return w(d.getHours(), 2) + ":" + w(d.getMinutes(), 2) + ":" + w(d.getSeconds(), 2) + ":" + w(d.getMilliseconds(), 3);
106
+ }
107
+ function _getSequenceNumbers(arr) {
108
+ return arr.map((notificationMessage) => notificationMessage.sequenceNumber);
109
+ }
110
+ function analyseEventFilterResult(node, eventFilter) {
111
+ /* istanbul ignore next */
112
+ if (!(eventFilter instanceof node_opcua_service_filter_1.EventFilter)) {
113
+ throw new Error("Internal Error");
114
+ }
115
+ const selectClauseResults = (0, node_opcua_address_space_1.checkSelectClauses)(node, eventFilter.selectClauses || []);
116
+ const whereClauseResult = new node_opcua_types_1.ContentFilterResult();
117
+ return new node_opcua_types_1.EventFilterResult({
118
+ selectClauseDiagnosticInfos: [],
119
+ selectClauseResults,
120
+ whereClauseResult
121
+ });
122
+ }
123
+ function analyseDataChangeFilterResult(node, dataChangeFilter) {
124
+ (0, node_opcua_assert_1.assert)(dataChangeFilter instanceof node_opcua_service_subscription_2.DataChangeFilter);
125
+ // the opcua specification doesn't provide dataChangeFilterResult
126
+ return null;
127
+ }
128
+ function analyseAggregateFilterResult(node, aggregateFilter) {
129
+ (0, node_opcua_assert_1.assert)(aggregateFilter instanceof node_opcua_service_subscription_1.AggregateFilter);
130
+ return new node_opcua_types_1.AggregateFilterResult({});
131
+ }
132
+ function _process_filter(node, filter) {
133
+ if (!filter) {
134
+ return null;
135
+ }
136
+ if (filter instanceof node_opcua_service_filter_1.EventFilter) {
137
+ return analyseEventFilterResult(node, filter);
138
+ }
139
+ else if (filter instanceof node_opcua_service_subscription_2.DataChangeFilter) {
140
+ return analyseDataChangeFilterResult(node, filter);
141
+ }
142
+ else if (filter instanceof node_opcua_service_subscription_1.AggregateFilter) {
143
+ return analyseAggregateFilterResult(node, filter);
144
+ }
145
+ // istanbul ignore next
146
+ throw new Error("invalid filter");
147
+ }
148
+ /**
149
+ * @private
150
+ */
151
+ function createSubscriptionDiagnostics(subscription) {
152
+ (0, node_opcua_assert_1.assert)(subscription instanceof Subscription);
153
+ const subscriptionDiagnostics = new node_opcua_common_1.SubscriptionDiagnosticsDataType({});
154
+ const subscription_subscriptionDiagnostics = subscriptionDiagnostics;
155
+ subscription_subscriptionDiagnostics.$subscription = subscription;
156
+ // "sessionId"
157
+ subscription_subscriptionDiagnostics.__defineGetter__("sessionId", function () {
158
+ if (!this.$subscription) {
159
+ return node_opcua_nodeid_1.NodeId.nullNodeId;
160
+ }
161
+ return this.$subscription.getSessionId();
162
+ });
163
+ subscription_subscriptionDiagnostics.__defineGetter__("subscriptionId", function () {
164
+ if (!this.$subscription) {
165
+ return 0;
166
+ }
167
+ return this.$subscription.id;
168
+ });
169
+ subscription_subscriptionDiagnostics.__defineGetter__("priority", function () {
170
+ if (!this.$subscription) {
171
+ return 0;
172
+ }
173
+ return this.$subscription.priority;
174
+ });
175
+ subscription_subscriptionDiagnostics.__defineGetter__("publishingInterval", function () {
176
+ if (!this.$subscription) {
177
+ return 0;
178
+ }
179
+ return this.$subscription.publishingInterval;
180
+ });
181
+ subscription_subscriptionDiagnostics.__defineGetter__("maxLifetimeCount", function () {
182
+ return this.$subscription.lifeTimeCount;
183
+ });
184
+ subscription_subscriptionDiagnostics.__defineGetter__("maxKeepAliveCount", function () {
185
+ if (!this.$subscription) {
186
+ return 0;
187
+ }
188
+ return this.$subscription.maxKeepAliveCount;
189
+ });
190
+ subscription_subscriptionDiagnostics.__defineGetter__("maxNotificationsPerPublish", function () {
191
+ if (!this.$subscription) {
192
+ return 0;
193
+ }
194
+ return this.$subscription.maxNotificationsPerPublish;
195
+ });
196
+ subscription_subscriptionDiagnostics.__defineGetter__("publishingEnabled", function () {
197
+ if (!this.$subscription) {
198
+ return false;
199
+ }
200
+ return this.$subscription.publishingEnabled;
201
+ });
202
+ subscription_subscriptionDiagnostics.__defineGetter__("monitoredItemCount", function () {
203
+ if (!this.$subscription) {
204
+ return 0;
205
+ }
206
+ return this.$subscription.monitoredItemCount;
207
+ });
208
+ subscription_subscriptionDiagnostics.__defineGetter__("nextSequenceNumber", function () {
209
+ if (!this.$subscription) {
210
+ return 0;
211
+ }
212
+ return this.$subscription._get_future_sequence_number();
213
+ });
214
+ subscription_subscriptionDiagnostics.__defineGetter__("disabledMonitoredItemCount", function () {
215
+ if (!this.$subscription) {
216
+ return 0;
217
+ }
218
+ return this.$subscription.disabledMonitoredItemCount;
219
+ });
220
+ /* those member of self.subscriptionDiagnostics are handled directly
221
+
222
+ modifyCount
223
+ enableCount,
224
+ disableCount,
225
+ republishRequestCount,
226
+ notificationsCount,
227
+ publishRequestCount,
228
+ dataChangeNotificationsCount,
229
+ eventNotificationsCount,
230
+ */
231
+ /*
232
+ those members are not updated yet in the code :
233
+ "republishMessageRequestCount",
234
+ "republishMessageCount",
235
+ "transferRequestCount",
236
+ "transferredToAltClientCount",
237
+ "transferredToSameClientCount",
238
+ "latePublishRequestCount",
239
+ "currentKeepAliveCount",
240
+ "currentLifetimeCount",
241
+ "unacknowledgedMessageCount",
242
+ "discardedMessageCount",
243
+ "monitoringQueueOverflowCount",
244
+ "eventQueueOverFlowCount"
245
+ */
246
+ // add object in Variable SubscriptionDiagnosticArray (i=2290) ( Array of SubscriptionDiagnostics)
247
+ // add properties in Variable to reflect
248
+ return subscriptionDiagnostics;
249
+ }
250
+ let g_monitoredItemId = Math.ceil(Math.random() * 100000);
251
+ function getNextMonitoredItemId() {
252
+ return g_monitoredItemId++;
253
+ }
254
+ // function myFilter<T>(t1: any, chunk: any[]): T[] {
255
+ // return chunk.filter(filter_instanceof.bind(null, t1));
256
+ // }
257
+ // function makeNotificationData(notifications_chunk: QueueItem): NotificationData {
258
+ // const dataChangedNotificationData = myFilter<MonitoredItemNotification>(MonitoredItemNotification, notifications_chunk);
259
+ // const eventNotificationListData = myFilter<EventFieldList>(EventFieldList, notifications_chunk);
260
+ // assert(notifications_chunk.length === dataChangedNotificationData.length + eventNotificationListData.length);
261
+ // const notifications: (DataChangeNotification | EventNotificationList)[] = [];
262
+ // // add dataChangeNotification
263
+ // if (dataChangedNotificationData.length) {
264
+ // const dataChangeNotification = new DataChangeNotification({
265
+ // diagnosticInfos: [],
266
+ // monitoredItems: dataChangedNotificationData
267
+ // });
268
+ // notifications.push(dataChangeNotification);
269
+ // }
270
+ // // add dataChangeNotification
271
+ // if (eventNotificationListData.length) {
272
+ // const eventNotificationList = new EventNotificationList({
273
+ // events: eventNotificationListData
274
+ // });
275
+ // notifications.push(eventNotificationList);
276
+ // }
277
+ // return notifications.length === 0 ? null : notifications;
278
+ // }
279
+ const INVALID_ID = -1;
280
+ /**
281
+ * The Subscription class used in the OPCUA server side.
282
+ */
283
+ class Subscription extends events_1.EventEmitter {
284
+ constructor(options) {
285
+ super();
286
+ this._keep_alive_counter = 0;
287
+ this._hasUncollectedMonitoredItemNotifications = false;
288
+ options = options || {};
289
+ Subscription.registry.register(this);
290
+ this.sessionId = options.sessionId || node_opcua_nodeid_1.NodeId.nullNodeId;
291
+ (0, node_opcua_assert_1.assert)(this.sessionId instanceof node_opcua_nodeid_1.NodeId, "expecting a sessionId NodeId");
292
+ this.publishEngine = options.publishEngine;
293
+ this.id = options.id || INVALID_ID;
294
+ this.priority = options.priority || 0;
295
+ this.publishingInterval = _adjust_publishing_interval(options.publishingInterval);
296
+ this.maxKeepAliveCount = _adjust_maxKeepAliveCount(options.maxKeepAliveCount); // , this.publishingInterval);
297
+ this.resetKeepAliveCounter();
298
+ this.lifeTimeCount = _adjust_lifeTimeCount(options.lifeTimeCount || 0, this.maxKeepAliveCount, this.publishingInterval);
299
+ this.maxNotificationsPerPublish = _adjust_maxNotificationsPerPublish(options.maxNotificationsPerPublish);
300
+ this._life_time_counter = 0;
301
+ this.resetLifeTimeCounter();
302
+ // notification message that are ready to be sent to the client
303
+ this._pending_notifications = new queue_1.Queue();
304
+ this._sent_notification_messages = [];
305
+ this._sequence_number_generator = new node_opcua_secure_channel_1.SequenceNumberGenerator();
306
+ // initial state of the subscription
307
+ this.state = SubscriptionState.CREATING;
308
+ this.publishIntervalCount = 0;
309
+ this.monitoredItems = {}; // monitored item map
310
+ this.monitoredItemIdCounter = 0;
311
+ this.publishingEnabled = _adjust_publishingEnable(options.publishingEnabled);
312
+ this.subscriptionDiagnostics = createSubscriptionDiagnostics(this);
313
+ // A boolean value that is set to TRUE to mean that either a NotificationMessage or a keep-alive
314
+ // Message has been sent on the Subscription. It is a flag that is used to ensure that either a
315
+ // NotificationMessage or a keep-alive Message is sent out the first time the publishing
316
+ // timer expires.
317
+ this.messageSent = false;
318
+ this.timerId = null;
319
+ this._start_timer();
320
+ debugLog(chalk.green(`creating subscription ${this.id}`));
321
+ }
322
+ getSessionId() {
323
+ return this.sessionId;
324
+ }
325
+ toString() {
326
+ let str = "Subscription:\n";
327
+ str += " subscriptionId " + this.id + "\n";
328
+ str += " sessionId " + this.getSessionId().toString() + "\n";
329
+ str += " publishingEnabled " + this.publishingEnabled + "\n";
330
+ str += " maxKeepAliveCount " + this.maxKeepAliveCount + "\n";
331
+ str += " publishingInterval " + this.publishingInterval + "\n";
332
+ str += " lifeTimeCount " + this.lifeTimeCount + "\n";
333
+ str += " maxKeepAliveCount " + this.maxKeepAliveCount + "\n";
334
+ return str;
335
+ }
336
+ /**
337
+ * modify subscription parameters
338
+ * @param param
339
+ */
340
+ modify(param) {
341
+ // update diagnostic counter
342
+ this.subscriptionDiagnostics.modifyCount += 1;
343
+ const publishingInterval_old = this.publishingInterval;
344
+ param.requestedPublishingInterval = param.requestedPublishingInterval || 0;
345
+ param.requestedMaxKeepAliveCount = param.requestedMaxKeepAliveCount || this.maxKeepAliveCount;
346
+ param.requestedLifetimeCount = param.requestedLifetimeCount || this.lifeTimeCount;
347
+ this.publishingInterval = _adjust_publishing_interval(param.requestedPublishingInterval);
348
+ this.maxKeepAliveCount = _adjust_maxKeepAliveCount(param.requestedMaxKeepAliveCount);
349
+ this.lifeTimeCount = _adjust_lifeTimeCount(param.requestedLifetimeCount, this.maxKeepAliveCount, this.publishingInterval);
350
+ this.maxNotificationsPerPublish = _adjust_maxNotificationsPerPublish(param.maxNotificationsPerPublish || 0);
351
+ this.priority = param.priority || 0;
352
+ this.resetLifeTimeAndKeepAliveCounters();
353
+ if (publishingInterval_old !== this.publishingInterval) {
354
+ // todo
355
+ }
356
+ this._stop_timer();
357
+ this._start_timer();
358
+ }
359
+ /**
360
+ * set publishing mode
361
+ * @param publishingEnabled
362
+ */
363
+ setPublishingMode(publishingEnabled) {
364
+ this.publishingEnabled = !!publishingEnabled;
365
+ // update diagnostics
366
+ if (this.publishingEnabled) {
367
+ this.subscriptionDiagnostics.enableCount += 1;
368
+ }
369
+ else {
370
+ this.subscriptionDiagnostics.disableCount += 1;
371
+ }
372
+ this.resetLifeTimeCounter();
373
+ if (!publishingEnabled && this.state !== SubscriptionState.CLOSED) {
374
+ this.state = SubscriptionState.NORMAL;
375
+ }
376
+ return node_opcua_status_code_1.StatusCodes.Good;
377
+ }
378
+ /**
379
+ * @private
380
+ */
381
+ get keepAliveCounterHasExpired() {
382
+ return this._keep_alive_counter >= this.maxKeepAliveCount;
383
+ }
384
+ /**
385
+ * Reset the Lifetime Counter Variable to the value specified for the lifetime of a Subscription in
386
+ * the CreateSubscription Service( 5.13.2).
387
+ * @private
388
+ */
389
+ resetLifeTimeCounter() {
390
+ this._life_time_counter = 0;
391
+ }
392
+ /**
393
+ * @private
394
+ */
395
+ increaseLifeTimeCounter() {
396
+ this._life_time_counter += 1;
397
+ }
398
+ /**
399
+ * True if the subscription life time has expired.
400
+ *
401
+ */
402
+ get lifeTimeHasExpired() {
403
+ (0, node_opcua_assert_1.assert)(this.lifeTimeCount > 0);
404
+ return this._life_time_counter >= this.lifeTimeCount;
405
+ }
406
+ /**
407
+ * number of milliseconds before this subscription times out (lifeTimeHasExpired === true);
408
+ */
409
+ get timeToExpiration() {
410
+ return (this.lifeTimeCount - this._life_time_counter) * this.publishingInterval;
411
+ }
412
+ get timeToKeepAlive() {
413
+ return (this.maxKeepAliveCount - this._keep_alive_counter) * this.publishingInterval;
414
+ }
415
+ /**
416
+ * Terminates the subscription.
417
+ * Calling this method will also remove any monitored items.
418
+ *
419
+ */
420
+ terminate() {
421
+ (0, node_opcua_assert_1.assert)(arguments.length === 0);
422
+ debugLog("Subscription#terminate status", SubscriptionState[this.state]);
423
+ if (this.state === SubscriptionState.CLOSED) {
424
+ // todo verify if asserting is required here
425
+ return;
426
+ }
427
+ // stop timer
428
+ this._stop_timer();
429
+ debugLog("terminating Subscription ", this.id, " with ", this.monitoredItemCount, " monitored items");
430
+ // dispose all monitoredItem
431
+ const keys = Object.keys(this.monitoredItems);
432
+ for (const key of keys) {
433
+ const status = this.removeMonitoredItem(parseInt(key, 10));
434
+ (0, node_opcua_assert_1.assert)(status === node_opcua_status_code_1.StatusCodes.Good);
435
+ }
436
+ (0, node_opcua_assert_1.assert)(this.monitoredItemCount === 0);
437
+ if (this.$session) {
438
+ this.$session._unexposeSubscriptionDiagnostics(this);
439
+ }
440
+ this.state = SubscriptionState.CLOSED;
441
+ /**
442
+ * notify the subscription owner that the subscription has been terminated.
443
+ * @event "terminated"
444
+ */
445
+ this.emit("terminated");
446
+ if (this.publishEngine) {
447
+ this.publishEngine.on_close_subscription(this);
448
+ }
449
+ }
450
+ setTriggering(triggeringItemId, linksToAdd, linksToRemove) {
451
+ /** Bad_NothingToDo, Bad_TooManyOperations,Bad_SubscriptionIdInvalid, Bad_MonitoredItemIdInvalid */
452
+ linksToAdd = linksToAdd || [];
453
+ linksToRemove = linksToRemove || [];
454
+ if (linksToAdd.length === 0 && linksToRemove.length === 0) {
455
+ return { statusCode: node_opcua_status_code_1.StatusCodes.BadNothingToDo, addResults: [], removeResults: [] };
456
+ }
457
+ const triggeringItem = this.getMonitoredItem(triggeringItemId);
458
+ const monitoredItemsToAdd = linksToAdd.map((id) => this.getMonitoredItem(id));
459
+ const monitoredItemsToRemove = linksToRemove.map((id) => this.getMonitoredItem(id));
460
+ if (!triggeringItem) {
461
+ const removeResults1 = monitoredItemsToRemove.map((m) => m ? node_opcua_status_code_1.StatusCodes.Good : node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid);
462
+ const addResults1 = monitoredItemsToAdd.map((m) => m ? node_opcua_status_code_1.StatusCodes.Good : node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid);
463
+ return {
464
+ statusCode: node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid,
465
+ addResults: addResults1,
466
+ removeResults: removeResults1
467
+ };
468
+ }
469
+ //
470
+ // note: it seems that CTT imposed that we do remove before add
471
+ const removeResults = monitoredItemsToRemove.map((m) => !m ? node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid : triggeringItem.removeLinkItem(m.monitoredItemId));
472
+ const addResults = monitoredItemsToAdd.map((m) => !m ? node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid : triggeringItem.addLinkItem(m.monitoredItemId));
473
+ const statusCode = node_opcua_status_code_1.StatusCodes.Good;
474
+ // do binding
475
+ return {
476
+ statusCode,
477
+ addResults,
478
+ removeResults
479
+ };
480
+ }
481
+ dispose() {
482
+ if (doDebug) {
483
+ debugLog("Subscription#dispose", this.id, this.monitoredItemCount);
484
+ }
485
+ (0, node_opcua_assert_1.assert)(this.monitoredItemCount === 0, "MonitoredItems haven't been deleted first !!!");
486
+ (0, node_opcua_assert_1.assert)(this.timerId === null, "Subscription timer haven't been terminated");
487
+ if (this.subscriptionDiagnostics) {
488
+ this.subscriptionDiagnostics.$subscription = null;
489
+ }
490
+ this.publishEngine = undefined;
491
+ this._pending_notifications.clear();
492
+ this._sent_notification_messages = [];
493
+ this.sessionId = node_opcua_nodeid_1.NodeId.nullNodeId;
494
+ this.$session = undefined;
495
+ this.removeAllListeners();
496
+ Subscription.registry.unregister(this);
497
+ }
498
+ get aborted() {
499
+ const session = this.$session;
500
+ if (!session) {
501
+ return true;
502
+ }
503
+ return session.aborted;
504
+ }
505
+ /**
506
+ * number of pending notifications
507
+ */
508
+ get pendingNotificationsCount() {
509
+ return this._pending_notifications ? this._pending_notifications.size : 0;
510
+ }
511
+ /**
512
+ * is 'true' if there are pending notifications for this subscription. (i.e moreNotifications)
513
+ */
514
+ get hasPendingNotifications() {
515
+ return this.pendingNotificationsCount > 0;
516
+ }
517
+ /**
518
+ * number of sent notifications
519
+ */
520
+ get sentNotificationMessageCount() {
521
+ return this._sent_notification_messages.length;
522
+ }
523
+ /**
524
+ * @internal
525
+ */
526
+ _flushSentNotifications() {
527
+ const tmp = this._sent_notification_messages;
528
+ this._sent_notification_messages = [];
529
+ return tmp;
530
+ }
531
+ /**
532
+ * number of monitored items handled by this subscription
533
+ */
534
+ get monitoredItemCount() {
535
+ return Object.keys(this.monitoredItems).length;
536
+ }
537
+ /**
538
+ * number of disabled monitored items.
539
+ */
540
+ get disabledMonitoredItemCount() {
541
+ return Object.values(this.monitoredItems).reduce((cumul, monitoredItem) => {
542
+ return cumul + (monitoredItem.monitoringMode === node_opcua_service_subscription_2.MonitoringMode.Disabled ? 1 : 0);
543
+ }, 0);
544
+ }
545
+ /**
546
+ * The number of unacknowledged messages saved in the republish queue.
547
+ */
548
+ get unacknowledgedMessageCount() {
549
+ return this.subscriptionDiagnostics.unacknowledgedMessageCount;
550
+ }
551
+ /**
552
+ * adjust monitored item sampling interval
553
+ * - an samplingInterval ===0 means that we use a event-base model ( no sampling)
554
+ * - otherwise the sampling is adjusted
555
+ * @private
556
+ */
557
+ adjustSamplingInterval(samplingInterval, node) {
558
+ if (samplingInterval < 0) {
559
+ // - The value -1 indicates that the default sampling interval defined by the publishing
560
+ // interval of the Subscription is requested.
561
+ // - Any negative number is interpreted as -1.
562
+ samplingInterval = this.publishingInterval;
563
+ }
564
+ else if (samplingInterval === 0) {
565
+ // OPCUA 1.0.3 Part 4 - 5.12.1.2
566
+ // The value 0 indicates that the Server should use the fastest practical rate.
567
+ // The fastest supported sampling interval may be equal to 0, which indicates
568
+ // that the data item is exception-based rather than being sampled at some period.
569
+ // An exception-based model means that the underlying system does not require
570
+ // sampling and reports data changes.
571
+ const dataValueSamplingInterval = node.readAttribute(node_opcua_address_space_2.SessionContext.defaultContext, node_opcua_data_model_1.AttributeIds.MinimumSamplingInterval);
572
+ // TODO if attributeId === AttributeIds.Value : sampling interval required here
573
+ if (dataValueSamplingInterval.statusCode === node_opcua_status_code_1.StatusCodes.Good) {
574
+ // node provides a Minimum sampling interval ...
575
+ samplingInterval = dataValueSamplingInterval.value.value;
576
+ (0, node_opcua_assert_1.assert)(samplingInterval >= 0 && samplingInterval <= monitored_item_1.MonitoredItem.maximumSamplingInterval);
577
+ // note : at this stage, a samplingInterval===0 means that the data item is really exception-based
578
+ }
579
+ }
580
+ else if (samplingInterval < monitored_item_1.MonitoredItem.minimumSamplingInterval) {
581
+ samplingInterval = monitored_item_1.MonitoredItem.minimumSamplingInterval;
582
+ }
583
+ else if (samplingInterval > monitored_item_1.MonitoredItem.maximumSamplingInterval) {
584
+ // If the requested samplingInterval is higher than the
585
+ // maximum sampling interval supported by the Server, the maximum sampling
586
+ // interval is returned.
587
+ samplingInterval = monitored_item_1.MonitoredItem.maximumSamplingInterval;
588
+ }
589
+ const node_minimumSamplingInterval = node && node.minimumSamplingInterval ? node.minimumSamplingInterval : 0;
590
+ samplingInterval = Math.max(samplingInterval, node_minimumSamplingInterval);
591
+ return samplingInterval;
592
+ }
593
+ /**
594
+ * create a monitored item
595
+ * @param addressSpace - address space
596
+ * @param timestampsToReturn - the timestamp to return
597
+ * @param monitoredItemCreateRequest - the parameters describing the monitored Item to create
598
+ */
599
+ preCreateMonitoredItem(addressSpace, timestampsToReturn, monitoredItemCreateRequest) {
600
+ (0, node_opcua_assert_1.assert)(monitoredItemCreateRequest instanceof node_opcua_service_subscription_2.MonitoredItemCreateRequest);
601
+ function handle_error(statusCode) {
602
+ return {
603
+ createResult: new node_opcua_service_subscription_2.MonitoredItemCreateResult({ statusCode }),
604
+ monitoredItemCreateRequest
605
+ };
606
+ }
607
+ const itemToMonitor = monitoredItemCreateRequest.itemToMonitor;
608
+ const node = addressSpace.findNode(itemToMonitor.nodeId);
609
+ if (!node) {
610
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown);
611
+ }
612
+ if (itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value && !(node.nodeClass === node_opcua_data_model_1.NodeClass.Variable)) {
613
+ // AttributeIds.Value is only valid for monitoring value of UAVariables.
614
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadAttributeIdInvalid);
615
+ }
616
+ if (itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.INVALID) {
617
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadAttributeIdInvalid);
618
+ }
619
+ if (!itemToMonitor.indexRange.isValid()) {
620
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadIndexRangeInvalid);
621
+ }
622
+ // check dataEncoding applies only on Values
623
+ if (itemToMonitor.dataEncoding.name && itemToMonitor.attributeId !== node_opcua_data_model_1.AttributeIds.Value) {
624
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadDataEncodingInvalid);
625
+ }
626
+ // check dataEncoding
627
+ if (!(0, node_opcua_data_model_1.isValidDataEncoding)(itemToMonitor.dataEncoding)) {
628
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadDataEncodingUnsupported);
629
+ }
630
+ // check that item can be read by current user session
631
+ // filter
632
+ const requestedParameters = monitoredItemCreateRequest.requestedParameters;
633
+ const filter = requestedParameters.filter;
634
+ const statusCodeFilter = (0, validate_filter_1.validateFilter)(filter, itemToMonitor, node);
635
+ if (statusCodeFilter !== node_opcua_status_code_1.StatusCodes.Good) {
636
+ return handle_error(statusCodeFilter);
637
+ }
638
+ // xx var monitoringMode = monitoredItemCreateRequest.monitoringMode; // Disabled, Sampling, Reporting
639
+ // xx var requestedParameters = monitoredItemCreateRequest.requestedParameters;
640
+ // do we have enough room for new monitored items ?
641
+ if (this.monitoredItemCount >= Subscription.maxMonitoredItemCount) {
642
+ return handle_error(node_opcua_status_code_1.StatusCodes.BadTooManyMonitoredItems);
643
+ }
644
+ const createResult = this._createMonitoredItemStep2(timestampsToReturn, monitoredItemCreateRequest, node);
645
+ (0, node_opcua_assert_1.assert)(createResult.statusCode === node_opcua_status_code_1.StatusCodes.Good);
646
+ const monitoredItem = this.getMonitoredItem(createResult.monitoredItemId);
647
+ // istanbul ignore next
648
+ if (!monitoredItem) {
649
+ throw new Error("internal error");
650
+ }
651
+ // TODO: fix old way to set node. !!!!
652
+ monitoredItem.setNode(node);
653
+ this.emit("monitoredItem", monitoredItem, itemToMonitor);
654
+ return { monitoredItem, monitoredItemCreateRequest, createResult };
655
+ }
656
+ applyOnMonitoredItem(functor) {
657
+ return __awaiter(this, void 0, void 0, function* () {
658
+ for (const m of Object.values(this.monitoredItems)) {
659
+ yield functor(m);
660
+ }
661
+ });
662
+ }
663
+ postCreateMonitoredItem(monitoredItem, monitoredItemCreateRequest, createResult) {
664
+ this._createMonitoredItemStep3(monitoredItem, monitoredItemCreateRequest);
665
+ }
666
+ createMonitoredItem(addressSpace, timestampsToReturn, monitoredItemCreateRequest) {
667
+ const { monitoredItem, createResult } = this.preCreateMonitoredItem(addressSpace, timestampsToReturn, monitoredItemCreateRequest);
668
+ this.postCreateMonitoredItem(monitoredItem, monitoredItemCreateRequest, createResult);
669
+ return createResult;
670
+ }
671
+ /**
672
+ * get a monitoredItem by Id.
673
+ * @param monitoredItemId : the id of the monitored item to get.
674
+ * @return the monitored item matching monitoredItemId
675
+ */
676
+ getMonitoredItem(monitoredItemId) {
677
+ return this.monitoredItems[monitoredItemId] || null;
678
+ }
679
+ /**
680
+ * remove a monitored Item from the subscription.
681
+ * @param monitoredItemId : the id of the monitored item to get.
682
+ */
683
+ removeMonitoredItem(monitoredItemId) {
684
+ debugLog("Removing monitoredIem ", monitoredItemId);
685
+ if (!this.monitoredItems.hasOwnProperty(monitoredItemId.toString())) {
686
+ return node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid;
687
+ }
688
+ const monitoredItem = this.monitoredItems[monitoredItemId];
689
+ monitoredItem.terminate();
690
+ monitoredItem.dispose();
691
+ /**
692
+ *
693
+ * notify that a monitored item has been removed from the subscription
694
+ * @param monitoredItem {MonitoredItem}
695
+ */
696
+ this.emit("removeMonitoredItem", monitoredItem);
697
+ delete this.monitoredItems[monitoredItemId];
698
+ this._removePendingNotificationsFor(monitoredItemId);
699
+ // flush pending notifications
700
+ // assert(this._pending_notifications.size === 0);
701
+ return node_opcua_status_code_1.StatusCodes.Good;
702
+ }
703
+ /**
704
+ * rue if monitored Item have uncollected Notifications
705
+ */
706
+ get hasUncollectedMonitoredItemNotifications() {
707
+ if (this._hasUncollectedMonitoredItemNotifications) {
708
+ return true;
709
+ }
710
+ const keys = Object.keys(this.monitoredItems);
711
+ const n = keys.length;
712
+ for (let i = 0; i < n; i++) {
713
+ const key = parseInt(keys[i], 10);
714
+ const monitoredItem = this.monitoredItems[key];
715
+ if (monitoredItem.hasMonitoredItemNotifications) {
716
+ this._hasUncollectedMonitoredItemNotifications = true;
717
+ return true;
718
+ }
719
+ }
720
+ return false;
721
+ }
722
+ get subscriptionId() {
723
+ return this.id;
724
+ }
725
+ getMessageForSequenceNumber(sequenceNumber) {
726
+ const notification_message = this._sent_notification_messages.find((e) => e.sequenceNumber === sequenceNumber);
727
+ return notification_message || null;
728
+ }
729
+ /**
730
+ * returns true if the notification has expired
731
+ * @param notification
732
+ */
733
+ notificationHasExpired(notification) {
734
+ (0, node_opcua_assert_1.assert)(notification.hasOwnProperty("start_tick"));
735
+ (0, node_opcua_assert_1.assert)(isFinite(notification.start_tick + this.maxKeepAliveCount));
736
+ return notification.start_tick + this.maxKeepAliveCount < this.publishIntervalCount;
737
+ }
738
+ /**
739
+ * returns in an array the sequence numbers of the notifications that have been sent
740
+ * and that haven't been acknowledged yet.
741
+ */
742
+ getAvailableSequenceNumbers() {
743
+ const availableSequenceNumbers = _getSequenceNumbers(this._sent_notification_messages);
744
+ return availableSequenceNumbers;
745
+ }
746
+ /**
747
+ * acknowledges a notification identified by its sequence number
748
+ */
749
+ acknowledgeNotification(sequenceNumber) {
750
+ debugLog("acknowledgeNotification ", sequenceNumber);
751
+ let foundIndex = -1;
752
+ this._sent_notification_messages.forEach((e, index) => {
753
+ if (e.sequenceNumber === sequenceNumber) {
754
+ foundIndex = index;
755
+ }
756
+ });
757
+ if (foundIndex === -1) {
758
+ if (doDebug) {
759
+ debugLog(chalk.red("acknowledging sequence FAILED !!! "), chalk.cyan(sequenceNumber.toString()));
760
+ }
761
+ return node_opcua_status_code_1.StatusCodes.BadSequenceNumberUnknown;
762
+ }
763
+ else {
764
+ if (doDebug) {
765
+ debugLog(chalk.yellow("acknowledging sequence "), chalk.cyan(sequenceNumber.toString()));
766
+ }
767
+ this._sent_notification_messages.splice(foundIndex, 1);
768
+ this.subscriptionDiagnostics.unacknowledgedMessageCount--;
769
+ return node_opcua_status_code_1.StatusCodes.Good;
770
+ }
771
+ }
772
+ /**
773
+ * getMonitoredItems is used to get information about monitored items of a subscription.Its intended
774
+ * use is defined in Part 4. This method is the implementation of the Standard OPCUA GetMonitoredItems Method.
775
+ * from spec:
776
+ * This method can be used to get the list of monitored items in a subscription if CreateMonitoredItems
777
+ * failed due to a network interruption and the client does not know if the creation succeeded in the server.
778
+ *
779
+ */
780
+ getMonitoredItems() {
781
+ const result = {
782
+ clientHandles: [],
783
+ serverHandles: [],
784
+ statusCode: node_opcua_status_code_1.StatusCodes.Good
785
+ };
786
+ for (const monitoredItemId of Object.keys(this.monitoredItems)) {
787
+ const monitoredItem = this.getMonitoredItem(parseInt(monitoredItemId, 10));
788
+ result.clientHandles.push(monitoredItem.clientHandle);
789
+ // TODO: serverHandle is defined anywhere in the OPCUA Specification 1.02
790
+ // I am not sure what shall be reported for serverHandle...
791
+ // using monitoredItem.monitoredItemId instead...
792
+ // May be a clarification in the OPCUA Spec is required.
793
+ result.serverHandles.push(parseInt(monitoredItemId, 10));
794
+ }
795
+ return result;
796
+ }
797
+ /**
798
+ * @private
799
+ */
800
+ resendInitialValues() {
801
+ return __awaiter(this, void 0, void 0, function* () {
802
+ const promises = [];
803
+ for (const monitoredItem of Object.values(this.monitoredItems)) {
804
+ (0, node_opcua_assert_1.assert)(monitoredItem.clientHandle !== 4294967295);
805
+ promises.push(monitoredItem.resendInitialValues());
806
+ }
807
+ yield Promise.all(promises);
808
+ this._harvestMonitoredItems();
809
+ });
810
+ }
811
+ /**
812
+ * @private
813
+ */
814
+ notifyTransfer() {
815
+ var _a;
816
+ // OPCUA UA Spec 1.0.3 : part 3 - page 82 - 5.13.7 TransferSubscriptions:
817
+ // If the Server transfers the Subscription to the new Session, the Server shall issue
818
+ // a StatusChangeNotification notificationMessage with the status code
819
+ // Good_SubscriptionTransferred to the old Session.
820
+ debugLog(chalk.red(" Subscription => Notifying Transfer "));
821
+ const notificationData = new node_opcua_service_subscription_2.StatusChangeNotification({
822
+ status: node_opcua_status_code_1.StatusCodes.GoodSubscriptionTransferred
823
+ });
824
+ if (this.publishEngine.pendingPublishRequestCount) {
825
+ // the GoodSubscriptionTransferred can be processed immediately
826
+ this._addNotificationMessage(notificationData);
827
+ debugLog(chalk.red("pendingPublishRequestCount"), (_a = this.publishEngine) === null || _a === void 0 ? void 0 : _a.pendingPublishRequestCount);
828
+ this._publish_pending_notifications();
829
+ }
830
+ else {
831
+ debugLog(chalk.red("Cannot send GoodSubscriptionTransferred => lets create a TransferredSubscription "));
832
+ const ts = new i_server_side_publish_engine_1.TransferredSubscription({
833
+ generator: this._sequence_number_generator,
834
+ id: this.id,
835
+ publishEngine: this.publishEngine
836
+ });
837
+ ts._pending_notification = notificationData;
838
+ this.publishEngine._closed_subscriptions.push(ts);
839
+ }
840
+ }
841
+ /**
842
+ *
843
+ * the server invokes the resetLifeTimeAndKeepAliveCounters method of the subscription
844
+ * when the server has send a Publish Response, so that the subscription
845
+ * can reset its life time counter.
846
+ *
847
+ * @private
848
+ */
849
+ resetLifeTimeAndKeepAliveCounters() {
850
+ this.resetLifeTimeCounter();
851
+ this.resetKeepAliveCounter();
852
+ }
853
+ _updateCounters(notificationMessage) {
854
+ for (const notificationData of notificationMessage.notificationData || []) {
855
+ // update diagnostics
856
+ if (notificationData instanceof node_opcua_service_subscription_2.DataChangeNotification) {
857
+ const nbNotifs = notificationData.monitoredItems.length;
858
+ this.subscriptionDiagnostics.dataChangeNotificationsCount += nbNotifs;
859
+ this.subscriptionDiagnostics.notificationsCount += nbNotifs;
860
+ }
861
+ else if (notificationData instanceof node_opcua_service_subscription_2.EventNotificationList) {
862
+ const nbNotifs = notificationData.events.length;
863
+ this.subscriptionDiagnostics.eventNotificationsCount += nbNotifs;
864
+ this.subscriptionDiagnostics.notificationsCount += nbNotifs;
865
+ }
866
+ else {
867
+ (0, node_opcua_assert_1.assert)(notificationData instanceof node_opcua_service_subscription_2.StatusChangeNotification);
868
+ // TODO
869
+ // note: :there is no way to count StatusChangeNotifications in opcua yet.
870
+ }
871
+ }
872
+ }
873
+ /**
874
+ * _publish_pending_notifications send a "notification" event:
875
+ *
876
+ * @private
877
+ * @precondition
878
+ * - pendingPublishRequestCount > 0
879
+ */
880
+ _publish_pending_notifications() {
881
+ var _a;
882
+ const publishEngine = this.publishEngine;
883
+ const subscriptionId = this.id;
884
+ // preconditions
885
+ (0, node_opcua_assert_1.assert)(publishEngine.pendingPublishRequestCount > 0);
886
+ (0, node_opcua_assert_1.assert)(this.hasPendingNotifications);
887
+ const notificationMessage = this._popNotificationToSend();
888
+ if (notificationMessage.notificationData.length === 0) {
889
+ return; // nothing to do
890
+ }
891
+ const moreNotifications = this.hasPendingNotifications;
892
+ this.emit("notification", notificationMessage);
893
+ // Update counters ....
894
+ this._updateCounters(notificationMessage);
895
+ (0, node_opcua_assert_1.assert)(notificationMessage.hasOwnProperty("sequenceNumber"));
896
+ (0, node_opcua_assert_1.assert)(notificationMessage.hasOwnProperty("notificationData"));
897
+ // update diagnostics
898
+ this.subscriptionDiagnostics.publishRequestCount += 1;
899
+ const response = new node_opcua_service_subscription_2.PublishResponse({
900
+ moreNotifications,
901
+ notificationMessage: {
902
+ notificationData: notificationMessage.notificationData,
903
+ sequenceNumber: this._get_next_sequence_number()
904
+ },
905
+ subscriptionId
906
+ });
907
+ this._sent_notification_messages.push(response.notificationMessage);
908
+ // get available sequence number;
909
+ const availableSequenceNumbers = this.getAvailableSequenceNumbers();
910
+ (0, node_opcua_assert_1.assert)(!response.notificationMessage ||
911
+ availableSequenceNumbers[availableSequenceNumbers.length - 1] === response.notificationMessage.sequenceNumber);
912
+ response.availableSequenceNumbers = availableSequenceNumbers;
913
+ publishEngine._send_response(this, response);
914
+ this.messageSent = true;
915
+ this.subscriptionDiagnostics.unacknowledgedMessageCount++;
916
+ this.resetLifeTimeAndKeepAliveCounters();
917
+ if (doDebug) {
918
+ debugLog("Subscription sending a notificationMessage subscriptionId=", subscriptionId, "sequenceNumber = ", notificationMessage.sequenceNumber.toString(), (_a = notificationMessage.notificationData) === null || _a === void 0 ? void 0 : _a.map((x) => x === null || x === void 0 ? void 0 : x.constructor.name).join(" "));
919
+ // debugLog(notificationMessage.toString());
920
+ }
921
+ if (this.state !== SubscriptionState.CLOSED) {
922
+ (0, node_opcua_assert_1.assert)(notificationMessage.notificationData.length > 0, "We are not expecting a keep-alive message here");
923
+ this.state = SubscriptionState.NORMAL;
924
+ debugLog("subscription " + this.id + chalk.bgYellow(" set to NORMAL"));
925
+ }
926
+ }
927
+ process_subscription() {
928
+ (0, node_opcua_assert_1.assert)(this.publishEngine.pendingPublishRequestCount > 0);
929
+ if (!this.publishingEnabled) {
930
+ // no publish to do, except keep alive
931
+ debugLog(" -> no publish to do, except keep alive");
932
+ this._process_keepAlive();
933
+ return;
934
+ }
935
+ if (!this.hasPendingNotifications && this.hasUncollectedMonitoredItemNotifications) {
936
+ // collect notification from monitored items
937
+ this._harvestMonitoredItems();
938
+ }
939
+ // let process them first
940
+ if (this.hasPendingNotifications) {
941
+ this._publish_pending_notifications();
942
+ if (this.state === SubscriptionState.NORMAL && this.hasPendingNotifications) {
943
+ // istanbul ignore next
944
+ if (doDebug) {
945
+ debugLog(" -> pendingPublishRequestCount > 0 " + "&& normal state => re-trigger tick event immediately ");
946
+ }
947
+ // let process an new publish request
948
+ setImmediate(this._tick.bind(this));
949
+ }
950
+ }
951
+ else {
952
+ this._process_keepAlive();
953
+ }
954
+ }
955
+ _get_future_sequence_number() {
956
+ return this._sequence_number_generator ? this._sequence_number_generator.future() : 0;
957
+ }
958
+ _process_keepAlive() {
959
+ this.increaseKeepAliveCounter();
960
+ if (this.keepAliveCounterHasExpired) {
961
+ debugLog(` -> _process_keepAlive => keepAliveCounterHasExpired`);
962
+ if (this._sendKeepAliveResponse()) {
963
+ this.resetLifeTimeAndKeepAliveCounters();
964
+ }
965
+ else {
966
+ debugLog(" -> subscription.state === LATE , " +
967
+ "because keepAlive Response cannot be send due to lack of PublishRequest");
968
+ this.state = SubscriptionState.LATE;
969
+ }
970
+ }
971
+ }
972
+ _stop_timer() {
973
+ if (this.timerId) {
974
+ debugLog(chalk.bgWhite.blue("Subscription#_stop_timer subscriptionId="), this.id);
975
+ clearInterval(this.timerId);
976
+ this.timerId = null;
977
+ }
978
+ }
979
+ _start_timer() {
980
+ debugLog(chalk.bgWhite.blue("Subscription#_start_timer subscriptionId="), this.id, " publishingInterval = ", this.publishingInterval);
981
+ (0, node_opcua_assert_1.assert)(this.timerId === null);
982
+ // from the spec:
983
+ // When a Subscription is created, the first Message is sent at the end of the first publishing cycle to
984
+ // inform the Client that the Subscription is operational. A NotificationMessage is sent if there are
985
+ // Notifications ready to be reported. If there are none, a keep-alive Message is sent instead that
986
+ // contains a sequence number of 1, indicating that the first NotificationMessage has not yet been sent.
987
+ // This is the only time a keep-alive Message is sent without waiting for the maximum keep-alive count
988
+ // to be reached, as specified in (f) above.
989
+ // make sure that a keep-alive Message will be send at the end of the first publishing cycle
990
+ // if there are no Notifications ready.
991
+ this._keep_alive_counter = this.maxKeepAliveCount;
992
+ (0, node_opcua_assert_1.assert)(this.publishingInterval >= Subscription.minimumPublishingInterval);
993
+ this.timerId = setInterval(this._tick.bind(this), this.publishingInterval);
994
+ }
995
+ // counter
996
+ _get_next_sequence_number() {
997
+ return this._sequence_number_generator ? this._sequence_number_generator.next() : 0;
998
+ }
999
+ /**
1000
+ * @private
1001
+ */
1002
+ _tick() {
1003
+ // istanbul ignore next
1004
+ if (doDebug) {
1005
+ debugLog(`Subscription#_tick id ${this.id} aborted=${this.aborted} state=${SubscriptionState[this.state]}`);
1006
+ }
1007
+ if (this.aborted) {
1008
+ // xx console.log(" Log aborted")
1009
+ // xx // underlying channel has been aborted ...
1010
+ // xx self.publishEngine.cancelPendingPublishRequestBeforeChannelChange();
1011
+ // xx // let's still increase lifetime counter to detect timeout
1012
+ }
1013
+ if (this.state === SubscriptionState.CLOSED) {
1014
+ warningLog(`Warning: Subscription#_tick id ${this.id} called while subscription is CLOSED`);
1015
+ return;
1016
+ }
1017
+ this.discardOldSentNotifications();
1018
+ // istanbul ignore next
1019
+ if (doDebug) {
1020
+ debugLog(t(new Date()) + " " + this._life_time_counter + "/" + this.lifeTimeCount + chalk.cyan(" Subscription#_tick"), " processing subscriptionId=", this.id, "hasUncollectedMonitoredItemNotifications = ", this.hasUncollectedMonitoredItemNotifications, " publishingIntervalCount =", this.publishIntervalCount);
1021
+ }
1022
+ this.publishEngine._on_tick();
1023
+ this.publishIntervalCount += 1;
1024
+ this.increaseLifeTimeCounter();
1025
+ if (this.lifeTimeHasExpired) {
1026
+ /* istanbul ignore next */
1027
+ if (doDebug) {
1028
+ debugLog(chalk.red.bold(`Subscription ${this.id} has expired !!!!! => Terminating`));
1029
+ }
1030
+ /**
1031
+ * notify the subscription owner that the subscription has expired by exceeding its life time.
1032
+ * @event expired
1033
+ *
1034
+ */
1035
+ this.emit("expired");
1036
+ // notify new terminated status only when subscription has timeout.
1037
+ debugLog("adding StatusChangeNotification notification message for BadTimeout subscription = ", this.id);
1038
+ this._addNotificationMessage(new node_opcua_service_subscription_2.StatusChangeNotification({ status: node_opcua_status_code_1.StatusCodes.BadTimeout }));
1039
+ // kill timer and delete monitored items and transfer pending notification messages
1040
+ this.terminate();
1041
+ return;
1042
+ }
1043
+ const publishEngine = this.publishEngine;
1044
+ // istanbul ignore next
1045
+ if (doDebug) {
1046
+ debugLog("Subscription#_tick self._pending_notifications= ", this._pending_notifications.size);
1047
+ }
1048
+ if (publishEngine.pendingPublishRequestCount === 0 &&
1049
+ (this.hasPendingNotifications || this.hasUncollectedMonitoredItemNotifications)) {
1050
+ // istanbul ignore next
1051
+ if (doDebug) {
1052
+ debugLog("subscription set to LATE hasPendingNotifications = ", this.hasPendingNotifications, " hasUncollectedMonitoredItemNotifications =", this.hasUncollectedMonitoredItemNotifications);
1053
+ }
1054
+ this.state = SubscriptionState.LATE;
1055
+ return;
1056
+ }
1057
+ if (publishEngine.pendingPublishRequestCount > 0) {
1058
+ if (this.hasPendingNotifications) {
1059
+ // simply pop pending notification and send it
1060
+ this.process_subscription();
1061
+ }
1062
+ else if (this.hasUncollectedMonitoredItemNotifications) {
1063
+ this.process_subscription();
1064
+ }
1065
+ else {
1066
+ this._process_keepAlive();
1067
+ }
1068
+ }
1069
+ else {
1070
+ this._process_keepAlive();
1071
+ }
1072
+ }
1073
+ /**
1074
+ * @private
1075
+ */
1076
+ _sendKeepAliveResponse() {
1077
+ const future_sequence_number = this._get_future_sequence_number();
1078
+ if (this.publishEngine.send_keep_alive_response(this.id, future_sequence_number)) {
1079
+ this.messageSent = true;
1080
+ // istanbul ignore next
1081
+ if (doDebug) {
1082
+ debugLog(` -> Subscription#_sendKeepAliveResponse subscriptionId ${this.id} future_sequence_number ${future_sequence_number}`);
1083
+ }
1084
+ /**
1085
+ * notify the subscription owner that a keepalive message has to be sent.
1086
+ * @event keepalive
1087
+ *
1088
+ */
1089
+ this.emit("keepalive", future_sequence_number);
1090
+ this.state = SubscriptionState.KEEPALIVE;
1091
+ return true;
1092
+ }
1093
+ return false;
1094
+ }
1095
+ /**
1096
+ * Reset the Lifetime Counter Variable to the value specified for the lifetime of a Subscription in
1097
+ * the CreateSubscription Service( 5.13.2).
1098
+ * @private
1099
+ */
1100
+ resetKeepAliveCounter() {
1101
+ this._keep_alive_counter = 0;
1102
+ // istanbul ignore next
1103
+ if (doDebug) {
1104
+ debugLog(" -> subscriptionId", this.id, " Resetting keepAliveCounter = ", this._keep_alive_counter, this.maxKeepAliveCount);
1105
+ }
1106
+ }
1107
+ /**
1108
+ * @private
1109
+ */
1110
+ increaseKeepAliveCounter() {
1111
+ this._keep_alive_counter += 1;
1112
+ // istanbul ignore next
1113
+ if (doDebug) {
1114
+ debugLog(" -> subscriptionId", this.id, " Increasing keepAliveCounter = ", this._keep_alive_counter, this.maxKeepAliveCount);
1115
+ }
1116
+ }
1117
+ /**
1118
+ * @private
1119
+ */
1120
+ _addNotificationMessage(notificationData, monitoredItemId) {
1121
+ // istanbul ignore next
1122
+ if (doDebug) {
1123
+ debugLog(chalk.yellow("Subscription#_addNotificationMessage"), notificationData.toString());
1124
+ }
1125
+ this._pending_notifications.push({
1126
+ monitoredItemId,
1127
+ notification: notificationData,
1128
+ publishTime: new Date(),
1129
+ start_tick: this.publishIntervalCount
1130
+ });
1131
+ }
1132
+ /**
1133
+ * @internal
1134
+ * @param monitoredItemId
1135
+ */
1136
+ _removePendingNotificationsFor(monitoredItemId) {
1137
+ const nbRemovedNotification = this._pending_notifications.filterOut((e) => e.monitoredItemId === monitoredItemId);
1138
+ if (doDebug) {
1139
+ debugLog(`Removed ${nbRemovedNotification} notifications`);
1140
+ }
1141
+ }
1142
+ /**
1143
+ * Extract the next Notification that is ready to be sent to the client.
1144
+ * @return the Notification to send._pending_notifications
1145
+ */
1146
+ _popNotificationToSend() {
1147
+ (0, node_opcua_assert_1.assert)(this._pending_notifications.size > 0);
1148
+ const notificationMessage = new node_opcua_service_subscription_2.NotificationMessage({
1149
+ sequenceNumber: 0xffffffff,
1150
+ notificationData: [],
1151
+ publishTime: new Date()
1152
+ }); //
1153
+ const dataChangeNotifications = new node_opcua_service_subscription_2.DataChangeNotification({
1154
+ monitoredItems: []
1155
+ });
1156
+ const eventNotificationList = new node_opcua_service_subscription_2.EventNotificationList({
1157
+ events: []
1158
+ });
1159
+ let statusChangeNotification;
1160
+ let i = 0;
1161
+ let hasEventFieldList = 0;
1162
+ let hasMonitoredItemNotification = 0;
1163
+ const m = this.maxNotificationsPerPublish;
1164
+ while (i < m && this._pending_notifications.size > 0) {
1165
+ if (hasEventFieldList || hasMonitoredItemNotification) {
1166
+ const notification1 = this._pending_notifications.first().notification;
1167
+ if (notification1 instanceof node_opcua_service_subscription_2.StatusChangeNotification) {
1168
+ break;
1169
+ }
1170
+ }
1171
+ const notification = this._pending_notifications.shift().notification;
1172
+ if (notification instanceof node_opcua_service_subscription_2.MonitoredItemNotification) {
1173
+ (0, node_opcua_assert_1.assert)(notification.clientHandle !== 4294967295);
1174
+ dataChangeNotifications.monitoredItems.push(notification);
1175
+ hasMonitoredItemNotification = 1;
1176
+ }
1177
+ else if (notification instanceof node_opcua_types_1.EventFieldList) {
1178
+ eventNotificationList.events.push(notification);
1179
+ hasEventFieldList = 1;
1180
+ }
1181
+ else if (notification instanceof node_opcua_service_subscription_2.StatusChangeNotification) {
1182
+ // to do
1183
+ statusChangeNotification = notification;
1184
+ break;
1185
+ }
1186
+ i += 1;
1187
+ }
1188
+ if (dataChangeNotifications.monitoredItems.length) {
1189
+ notificationMessage.notificationData.push(dataChangeNotifications);
1190
+ }
1191
+ if (eventNotificationList.events.length) {
1192
+ notificationMessage.notificationData.push(eventNotificationList);
1193
+ }
1194
+ if (statusChangeNotification) {
1195
+ notificationMessage.notificationData.push(statusChangeNotification);
1196
+ }
1197
+ return notificationMessage;
1198
+ }
1199
+ /**
1200
+ * discardOldSentNotification find all sent notification message that have expired keep-alive
1201
+ * and destroy them.
1202
+ * @private
1203
+ *
1204
+ * Subscriptions maintain a retransmission queue of sent NotificationMessages.
1205
+ * NotificationMessages are retained in this queue until they are acknowledged or until they have
1206
+ * been in the queue for a minimum of one keep-alive interval.
1207
+ *
1208
+ */
1209
+ discardOldSentNotifications() {
1210
+ // Sessions maintain a retransmission queue of sent NotificationMessages. NotificationMessages
1211
+ // are retained in this queue until they are acknowledged. The Session shall maintain a
1212
+ // retransmission queue size of at least two times the number of Publish requests per Session the
1213
+ // Server supports. Clients are required to acknowledge NotificationMessages as they are received. In the
1214
+ // case of a retransmission queue overflow, the oldest sent NotificationMessage gets deleted. If a
1215
+ // Subscription is transferred to another Session, the queued NotificationMessages for this
1216
+ // Subscription are moved from the old to the new Session.
1217
+ if (maxNotificationMessagesInQueue <= this._sent_notification_messages.length) {
1218
+ debugLog("discardOldSentNotifications = ", this._sent_notification_messages.length);
1219
+ this._sent_notification_messages.splice(this._sent_notification_messages.length - maxNotificationMessagesInQueue);
1220
+ }
1221
+ }
1222
+ /**
1223
+ * @param timestampsToReturn
1224
+ * @param monitoredItemCreateRequest
1225
+ * @param node
1226
+ * @private
1227
+ */
1228
+ _createMonitoredItemStep2(timestampsToReturn, monitoredItemCreateRequest, node) {
1229
+ // note : most of the parameter inconsistencies shall have been handled by the caller
1230
+ // any error here will raise an assert here
1231
+ (0, node_opcua_assert_1.assert)(monitoredItemCreateRequest instanceof node_opcua_service_subscription_2.MonitoredItemCreateRequest);
1232
+ const itemToMonitor = monitoredItemCreateRequest.itemToMonitor;
1233
+ // xx check if attribute Id invalid (we only support Value or EventNotifier )
1234
+ // xx assert(itemToMonitor.attributeId !== AttributeIds.INVALID);
1235
+ this.monitoredItemIdCounter += 1;
1236
+ const monitoredItemId = getNextMonitoredItemId();
1237
+ const requestedParameters = monitoredItemCreateRequest.requestedParameters;
1238
+ // adjust requestedParameters.samplingInterval
1239
+ requestedParameters.samplingInterval = this.adjustSamplingInterval(requestedParameters.samplingInterval, node);
1240
+ // reincorporate monitoredItemId and itemToMonitor into the requestedParameters
1241
+ const options = requestedParameters;
1242
+ options.monitoredItemId = monitoredItemId;
1243
+ options.itemToMonitor = itemToMonitor;
1244
+ const monitoredItem = new monitored_item_1.MonitoredItem(options);
1245
+ monitoredItem.timestampsToReturn = timestampsToReturn;
1246
+ monitoredItem.$subscription = this;
1247
+ (0, node_opcua_assert_1.assert)(monitoredItem.monitoredItemId === monitoredItemId);
1248
+ this.monitoredItems[monitoredItemId] = monitoredItem;
1249
+ (0, node_opcua_assert_1.assert)(monitoredItem.clientHandle !== 4294967295);
1250
+ const filterResult = _process_filter(node, requestedParameters.filter);
1251
+ const monitoredItemCreateResult = new node_opcua_service_subscription_2.MonitoredItemCreateResult({
1252
+ filterResult,
1253
+ monitoredItemId,
1254
+ revisedQueueSize: monitoredItem.queueSize,
1255
+ revisedSamplingInterval: monitoredItem.samplingInterval,
1256
+ statusCode: node_opcua_status_code_1.StatusCodes.Good
1257
+ });
1258
+ // this.emit("monitoredItem", monitoredItem, itemToMonitor);
1259
+ return monitoredItemCreateResult;
1260
+ }
1261
+ /**
1262
+ *
1263
+ * @param monitoredItem
1264
+ * @param monitoredItemCreateRequest
1265
+ * @private
1266
+ */
1267
+ _createMonitoredItemStep3(monitoredItem, monitoredItemCreateRequest) {
1268
+ if (!monitoredItem) {
1269
+ return;
1270
+ }
1271
+ (0, node_opcua_assert_1.assert)(monitoredItem.monitoringMode === node_opcua_service_subscription_2.MonitoringMode.Invalid);
1272
+ (0, node_opcua_assert_1.assert)(typeof monitoredItem.samplingFunc === "function", " expecting a sampling function here");
1273
+ const monitoringMode = monitoredItemCreateRequest.monitoringMode; // Disabled, Sampling, Reporting
1274
+ monitoredItem.setMonitoringMode(monitoringMode);
1275
+ }
1276
+ _harvestMonitoredItems() {
1277
+ for (const monitoredItem of Object.values(this.monitoredItems)) {
1278
+ const notifications_chunks = monitoredItem.extractMonitoredItemNotifications();
1279
+ for (const chunk of notifications_chunks) {
1280
+ this._addNotificationMessage(chunk, monitoredItem.monitoredItemId);
1281
+ }
1282
+ }
1283
+ this._hasUncollectedMonitoredItemNotifications = false;
1284
+ }
1285
+ }
1286
+ exports.Subscription = Subscription;
1287
+ Subscription.minimumPublishingInterval = 50; // fastest possible
1288
+ Subscription.defaultPublishingInterval = 1000; // one second
1289
+ Subscription.maximumPublishingInterval = 1000 * 60 * 60 * 24 * 15; // 15 days
1290
+ Subscription.maxNotificationPerPublishHighLimit = 1000;
1291
+ Subscription.maxMonitoredItemCount = 20000;
1292
+ Subscription.registry = new node_opcua_object_registry_1.ObjectRegistry();
1293
+ /**
1294
+ * extract up to maxNotificationsPerPublish notifications
1295
+ * @param the full array of monitored items
1296
+ * @param maxNotificationsPerPublish the maximum number of notification to extract
1297
+ * @return an extract of array of monitored item matching at most maxNotificationsPerPublish
1298
+ * @private
1299
+ */
1300
+ function extract_notifications_chunk(monitoredItems, maxNotificationsPerPublish) {
1301
+ let n = maxNotificationsPerPublish === 0 ? monitoredItems.size : Math.min(monitoredItems.size, maxNotificationsPerPublish);
1302
+ const chunk_monitoredItems = [];
1303
+ while (n) {
1304
+ chunk_monitoredItems.push(monitoredItems.shift());
1305
+ n--;
1306
+ }
1307
+ return chunk_monitoredItems;
1308
+ }
1309
+ function filter_instanceof(Class, e) {
1310
+ return e instanceof Class;
1311
+ }
1312
+ (0, node_opcua_assert_1.assert)(Subscription.maximumPublishingInterval < 2147483647, "maximumPublishingInterval cannot exceed (2**31-1) ms ");
1313
+ //# sourceMappingURL=server_subscription.js.map