node-opcua-server 2.71.0 → 2.72.2

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