-
-
Notifications
You must be signed in to change notification settings - Fork 478
/
server_subscription.js
1679 lines (1301 loc) · 58.5 KB
/
server_subscription.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
/**
* @module opcua.server
*/
const Dequeue = require("dequeue");
const subscription_service = require("node-opcua-service-subscription");
const DataChangeNotification = subscription_service.DataChangeNotification;
const EventNotificationList = subscription_service.EventNotificationList;
const NotificationMessage = subscription_service.NotificationMessage;
const StatusChangeNotification = subscription_service.StatusChangeNotification;
const MonitoringMode = subscription_service.MonitoringMode;
const NodeId = require("node-opcua-nodeid").NodeId;
const StatusCodes = require("node-opcua-status-code").StatusCodes;
const Enum = require("node-opcua-enum").Enum;
const assert = require("node-opcua-assert").assert;
const NodeClass = require("node-opcua-data-model").NodeClass;
const _ = require("underscore");
const AttributeIds = require("node-opcua-data-model").AttributeIds;
const SequenceNumberGenerator = require("node-opcua-secure-channel").SequenceNumberGenerator;
const EventEmitter = require("events").EventEmitter;
const util = require("util");
const SessionContext = require("node-opcua-address-space").SessionContext;
const EventFilter = require("node-opcua-service-filter").EventFilter;
const DataChangeFilter = require("node-opcua-service-subscription").DataChangeFilter;
const AggregateFilter = require("node-opcua-service-subscription").AggregateFilter;
const UAVariable = require("node-opcua-address-space").UAVariable;
const validateFilter = require("./validate_filter").validateFilter;
const isValidDataEncoding = require("node-opcua-data-model").isValidDataEncoding;
const debugLog = require("node-opcua-debug").make_debugLog(__filename);
const doDebug = require("node-opcua-debug").checkDebugFlag(__filename);
const SubscriptionState = new Enum([
"CLOSED", // The Subscription has not yet been created or has terminated.
"CREATING", // The Subscription is being created
"NORMAL", // The Subscription is cyclically checking for Notifications from its MonitoredItems.
// The keep-alive counter is not used in this state.
"LATE", // The publishing timer has expired and there are Notifications available or a keep-alive Message is
// ready to be sent, but there are no Publish requests queued. When in this state, the next Publish
// request is processed when it is received. The keep-alive counter is not used in this state.
"KEEPALIVE",// The Subscription is cyclically checking for Notification
// alive counter to count down to 0 from its maximum.
"TERMINATED"
]);
exports.SubscriptionState = SubscriptionState;
const SessionDiagnosticsDataType = require("node-opcua-common").SessionDiagnosticsDataType;
function _adjust_publishing_interval(publishingInterval) {
publishingInterval = publishingInterval || Subscription.defaultPublishingInterval;
publishingInterval = Math.max(publishingInterval, Subscription.minimumPublishingInterval);
publishingInterval = Math.min(publishingInterval, Subscription.maximumPublishingInterval);
return publishingInterval;
}
const minimumMaxKeepAliveCount = 2;
const maximumMaxKeepAliveCount = 12000;
function _adjust_maxKeepAliveCount(maxKeepAliveCount/*,publishingInterval*/) {
maxKeepAliveCount = maxKeepAliveCount || minimumMaxKeepAliveCount;
maxKeepAliveCount = Math.max(maxKeepAliveCount, minimumMaxKeepAliveCount);
maxKeepAliveCount = Math.min(maxKeepAliveCount, maximumMaxKeepAliveCount);
return maxKeepAliveCount;
}
function _adjust_lifeTimeCount(lifeTimeCount, maxKeepAliveCount, publishingInterval) {
lifeTimeCount = lifeTimeCount || 1;
// let's make sure that lifeTimeCount is at least three time maxKeepAliveCount
// Note : the specs say ( part 3 - CreateSubscriptionParameter )
// "The lifetime count shall be a minimum of three times the keep keep-alive count."
lifeTimeCount = Math.max(lifeTimeCount, maxKeepAliveCount * 3);
const minTicks = Math.ceil(5 * 1000 / (publishingInterval)); // we want 5 seconds min
lifeTimeCount = Math.max(minTicks, lifeTimeCount);
return lifeTimeCount;
}
function _adjust_publishinEnable(publishingEnabled) {
return (publishingEnabled === null || publishingEnabled === undefined) ? true : !!publishingEnabled;
}
function _adjust_maxNotificationsPerPublish(maxNotificationsPerPublish) {
maxNotificationsPerPublish += 0;
assert(_.isNumber(maxNotificationsPerPublish));
return (maxNotificationsPerPublish >= 0) ? maxNotificationsPerPublish : 0;
}
// verify that the injected publishEngine provides the expected services
// regarding the Subscription requirements...
function _assert_valid_publish_engine(publishEngine) {
assert(_.isObject(publishEngine));
assert(_.isNumber(publishEngine.pendingPublishRequestCount));
assert(_.isFunction(publishEngine.send_notification_message));
assert(_.isFunction(publishEngine.send_keep_alive_response));
assert(_.isFunction(publishEngine.on_close_subscription));
}
const SubscriptionDiagnosticsDataType = require("node-opcua-common").SubscriptionDiagnosticsDataType;
function createSubscriptionDiagnostics(self) {
assert(self instanceof Subscription);
self.subscriptionDiagnostics = new SubscriptionDiagnosticsDataType({});
self.subscriptionDiagnostics.$subscription = self;
// "sessionId"
self.subscriptionDiagnostics.__defineGetter__("sessionId", function () {
return this.$subscription.getSessionId();
});
self.subscriptionDiagnostics.__defineGetter__("subscriptionId", function () {
return this.$subscription.id;
});
self.subscriptionDiagnostics.__defineGetter__("priority", function () {
return this.$subscription.priority;
});
self.subscriptionDiagnostics.__defineGetter__("publishingInterval", function () {
return this.$subscription.publishingInterval;
});
self.subscriptionDiagnostics.__defineGetter__("maxLifetimeCount", function () {
return this.$subscription.lifeTimeCount;
});
self.subscriptionDiagnostics.__defineGetter__("maxKeepAliveCount", function () {
return this.$subscription.maxKeepAliveCount;
});
self.subscriptionDiagnostics.__defineGetter__("maxNotificationsPerPublish", function () {
return this.$subscription.maxNotificationsPerPublish;
});
self.subscriptionDiagnostics.__defineGetter__("publishingEnabled", function () {
return this.$subscription.publishingEnabled;
});
self.subscriptionDiagnostics.__defineGetter__("monitoredItemCount", function () {
return this.$subscription.monitoredItemCount;
});
self.subscriptionDiagnostics.__defineGetter__("nextSequenceNumber", function () {
return this.$subscription._get_future_sequence_number();
});
self.subscriptionDiagnostics.__defineGetter__("disabledMonitoredItemCount", function () {
return this.$subscription.disabledMonitoredItemCount;
});
/* those member of self.subscriptionDiagnostics are handled directly
modifyCount
enableCount,
disableCount,
republishRequestCount,
notificationsCount,
publishRequestCount,
dataChangeNotificationsCount,
eventNotificationsCount,
*/
/*
those members are not updated yet in the code :
"republishMessageRequestCount",
"republishMessageCount",
"transferRequestCount",
"transferredToAltClientCount",
"transferredToSameClientCount",
"latePublishRequestCount",
"currentKeepAliveCount",
"currentLifetimeCount",
"unacknowledgedMessageCount",
"discardedMessageCount",
"monitoringQueueOverflowCount",
"eventQueueOverFlowCount"
*/
// add object in Variable SubscriptionDiagnosticArray (i=2290) ( Array of SubscriptionDiagnostics)
// add properties in Variable to reflect
}
/**
* The Subscription class used in the OPCUA server side.
* @class Subscription
* @param {Object} options
* @param options.id {Integer} - a unique identifier
* @param options.publishingInterval {Integer} - [optional](default:1000) the publishing interval.
* @param options.maxKeepAliveCount {Integer} - [optional](default:10) the max KeepAlive Count.
* @param options.lifeTimeCount {Integer} - [optional](default:10) the max Life Time Count
* @param options.publishingEnabled {Boolean} - [optional](default:true)
* @param options.sessionId {NodeId} - [optional]
* @param options.maxNotificationsPerPublish {Integer} - [optional](default:0)
* @param options.priority {Byte}
* @constructor
*/
function Subscription(options) {
options = options || {};
EventEmitter.apply(this, arguments);
const subscription = this;
Subscription.registry.register(subscription);
subscription.sessionId = options.sessionId|| NodeId.nullNodeId;
assert(subscription.sessionId instanceof NodeId,"expecting a sessionId NodeId");
subscription.publishEngine = options.publishEngine;
_assert_valid_publish_engine(subscription.publishEngine);
subscription.id = options.id || "<invalid_id>";
subscription.priority = options.priority || 0;
/**
* the Subscription publishing interval
* @property publishingInterval
* @type {number}
* @default 1000
*/
subscription.publishingInterval = _adjust_publishing_interval(options.publishingInterval);
/**
* The keep alive count defines how many times the publish interval need to
* expires without having notifications available before the server send an
* empty message.
* OPCUA Spec says: a value of 0 is invalid.
* @property maxKeepAliveCount
* @type {number}
* @default 10
*
*/
subscription.maxKeepAliveCount = _adjust_maxKeepAliveCount(options.maxKeepAliveCount, subscription.publishingInterval);
subscription.resetKeepAliveCounter();
/**
* The life time count defines how many times the publish interval expires without
* having a connection to the client to deliver data.
* If the life time count reaches maxKeepAliveCount, the subscription will
* automatically terminate.
* OPCUA Spec: The life-time count shall be a minimum of three times the keep keep-alive count.
*
* Note: this has to be interpreted as without having a PublishRequest available
* @property lifeTimeCount
* @type {Number}
* @default 1
*/
subscription.lifeTimeCount = _adjust_lifeTimeCount(options.lifeTimeCount, subscription.maxKeepAliveCount, subscription.publishingInterval);
/**
* The maximum number of notifications that the Client wishes to receive in a
* single Publish response. A value of zero indicates that there is no limit.
* The number of notifications per Publish is the sum of monitoredItems in the
* DataChangeNotification and events in the EventNotificationList.
*
* @property maxNotificationsPerPublish
* @type {Number}
* #default 0
*/
subscription.maxNotificationsPerPublish = _adjust_maxNotificationsPerPublish(options.maxNotificationsPerPublish);
subscription._life_time_counter = 0;
subscription.resetLifeTimeCounter();
// notification message that are ready to be sent to the client
subscription._pending_notifications = new Dequeue();
subscription._sent_notifications = [];
subscription._sequence_number_generator = new SequenceNumberGenerator();
// initial state of the subscription
subscription.state = SubscriptionState.CREATING;
subscription.publishIntervalCount = 0;
subscription.monitoredItems = {}; // monitored item map
/**
* number of monitored Item
* @property monitoredItemIdCounter
* @type {Number}
*/
subscription.monitoredItemIdCounter = 0;
subscription.publishingEnabled = _adjust_publishinEnable(options.publishingEnabled);
subscription.subscriptionDiagnostics = null;
createSubscriptionDiagnostics(subscription);
// A boolean value that is set to TRUE to mean that either a NotificationMessage or a keep-alive Message has been
// sent on the Subscription. It is a flag that is used to ensure that either a NotificationMessage or a keep-alive
// Message is sent out the first time the publishing timer expires.
subscription.messageSent = false;
subscription._unacknowledgedMessageCount = 0;
subscription.timerId = null;
subscription._start_timer();
}
util.inherits(Subscription, EventEmitter);
Subscription.minimumPublishingInterval = 50; // fastest possible
Subscription.defaultPublishingInterval = 1000; // one second
Subscription.maximumPublishingInterval = 1000 * 60 * 60 * 24 * 15; // 15 days
assert(Subscription.maximumPublishingInterval < 2147483647, "maximumPublishingInterval cannot exceed (2**31-1) ms ");
const ObjectRegistry = require("node-opcua-object-registry").ObjectRegistry;
Subscription.registry = new ObjectRegistry();
Subscription.prototype.getSessionId = function () {
const subscription = this;
return subscription.sessionId;
};
Subscription.prototype.toString = function () {
const subscription = this;
let str = "Subscription:\n";
str += " subscriptionId " + subscription.id + "\n";
str += " sessionId " + subscription.getSessionId().toString() + "\n";
str += " publishingEnabled " + subscription.publishingEnabled + "\n";
str += " maxKeepAliveCount " + subscription.maxKeepAliveCount + "\n";
str += " publishingInterval " + subscription.publishingInterval + "\n";
str += " lifeTimeCount " + subscription.lifeTimeCount + "\n";
str += " maxKeepAliveCount " + subscription.maxKeepAliveCount + "\n";
return str;
};
/**
* @method modify
* @param param {Object}
* @param param.requestedPublishingInterval {Duration} requestedPublishingInterval =0 means fastest possible
* @param param.requestedLifetimeCount {Counter} requestedLifetimeCount ===0 means no change
* @param param.requestedMaxKeepAliveCount {Counter} requestedMaxKeepAliveCount ===0 means no change
* @param param.maxNotificationsPerPublish {Counter}
* @param param.priority {Byte}
*
*/
Subscription.prototype.modify = function (param) {
const subscription = this;
// update diagnostic counter
subscription.subscriptionDiagnostics.modifyCount += 1;
const publishingInterval_old = subscription.publishingInterval;
param.requestedPublishingInterval = param.requestedPublishingInterval || 0;
param.requestedMaxKeepAliveCount = param.requestedMaxKeepAliveCount || subscription.maxKeepAliveCount;
param.requestedLifetimeCount = param.requestedLifetimeCount || subscription.lifeTimeCount;
subscription.publishingInterval = _adjust_publishing_interval(param.requestedPublishingInterval);
subscription.maxKeepAliveCount = _adjust_maxKeepAliveCount(param.requestedMaxKeepAliveCount, subscription.publishingInterval);
subscription.lifeTimeCount = _adjust_lifeTimeCount(param.requestedLifetimeCount, subscription.maxKeepAliveCount, subscription.publishingInterval);
subscription.maxNotificationsPerPublish = param.maxNotificationsPerPublish;
subscription.priority = param.priority;
subscription.resetLifeTimeAndKeepAliveCounters();
if (publishingInterval_old !== subscription.publishingInterval) {
// todo
}
subscription._stop_timer();
subscription._start_timer();
};
Subscription.prototype._stop_timer = function () {
const subscription = this;
if (subscription.timerId) {
debugLog("Subscription#_stop_timer subscriptionId=".bgWhite.blue, subscription.id);
clearInterval(subscription.timerId);
subscription.timerId = null;
}
};
Subscription.prototype._start_timer = function () {
const subscription = this;
debugLog("Subscription#_start_timer subscriptionId=".bgWhite.blue, subscription.id, " publishingInterval = ", subscription.publishingInterval);
assert(subscription.timerId === null);
// from the spec:
// When a Subscription is created, the first Message is sent at the end of the first publishing cycle to
// inform the Client that the Subscription is operational. A NotificationMessage is sent if there are
// Notifications ready to be reported. If there are none, a keep-alive Message is sent instead that
// contains a sequence number of 1, indicating that the first NotificationMessage has not yet been sent.
// This is the only time a keep-alive Message is sent without waiting for the maximum keep-alive count
// to be reached, as specified in (f) above.
// make sure that a keep-alive Message will be send at the end of the first publishing cycle
// if there are no Notifications ready.
subscription._keep_alive_counter = subscription.maxKeepAliveCount;
assert(subscription.publishingInterval >= Subscription.minimumPublishingInterval);
subscription.timerId = setInterval(subscription._tick.bind(subscription), subscription.publishingInterval);
};
// counter
Subscription.prototype._get_next_sequence_number = function () {
return this._sequence_number_generator ? this._sequence_number_generator.next() : 0;
};
// counter
Subscription.prototype._get_future_sequence_number = function () {
return this._sequence_number_generator ? this._sequence_number_generator.future() : 0;
};
Subscription.prototype.setPublishingMode = function (publishingEnabled) {
this.publishingEnabled = !!publishingEnabled;
// update diagnostics
if (this.publishingEnabled) {
this.subscriptionDiagnostics.enableCount += 1;
} else {
this.subscriptionDiagnostics.disableCount += 1;
}
this.resetLifeTimeCounter();
if (!publishingEnabled && this.state !== SubscriptionState.CLOSED) {
this.state = SubscriptionState.NORMAL;
}
return StatusCodes.Good;
};
/**
* _publish_pending_notifications send a "notification" event:
*
* @method _publish_pending_notifications *
* @private
*
*/
Subscription.prototype._publish_pending_notifications = function () {
const subscription = this;
const publishEngine = subscription.publishEngine;
const subscriptionId = subscription.id;
// preconditions
assert(publishEngine.pendingPublishRequestCount > 0);
assert(subscription.hasPendingNotifications);
function _count_notification_message(notifData) {
if (notifData instanceof DataChangeNotification) {
subscription.subscriptionDiagnostics.dataChangeNotificationsCount += 1;
} else if (notifData instanceof EventNotificationList) {
subscription.subscriptionDiagnostics.eventNotificationsCount += 1;
} else {
// TODO
}
}
// todo : get rid of this....
subscription.emit("notification");
const notificationMessage = subscription._popNotificationToSend().notification;
subscription.emit("notificationMessage", notificationMessage);
assert(_.isArray(notificationMessage.notificationData));
notificationMessage.notificationData.forEach(_count_notification_message);
assert(notificationMessage.hasOwnProperty("sequenceNumber"));
assert(notificationMessage.hasOwnProperty("notificationData"));
const moreNotifications = (subscription.hasPendingNotifications);
// update diagnostics
if (subscription.subscriptionDiagnostics) {
subscription.subscriptionDiagnostics.notificationsCount += 1;
subscription.subscriptionDiagnostics.publishRequestCount += 1;
}
publishEngine.send_notification_message({
subscriptionId: subscriptionId,
sequenceNumber: notificationMessage.sequenceNumber,
notificationData: notificationMessage.notificationData,
moreNotifications: moreNotifications
}, false);
subscription.messageSent = true;
subscription._unacknowledgedMessageCount++;
subscription.resetLifeTimeAndKeepAliveCounters();
if (doDebug) {
debugLog("Subscription sending a notificationMessage subscriptionId=", subscriptionId,
"sequenceNumber = ", notificationMessage.sequenceNumber.toString());
// debugLog(notificationMessage.toString());
}
if (subscription.state !== SubscriptionState.CLOSED) {
assert(notificationMessage.notificationData.length > 0, "We are not expecting a keep-alive message here");
subscription.state = SubscriptionState.NORMAL;
debugLog("subscription " + subscription.id + " set to NORMAL".bgYellow);
}
};
Subscription.prototype._process_keepAlive = function () {
const subscription = this;
//xx assert(!self.publishingEnabled || (!self.hasPendingNotifications && !self.hasMonitoredItemNotifications));
subscription.increaseKeepAliveCounter();
if (subscription.keepAliveCounterHasExpired) {
if (subscription._sendKeepAliveResponse()) {
subscription.resetLifeTimeAndKeepAliveCounters();
} else {
debugLog(" -> subscription.state === LATE , because keepAlive Response cannot be send due to lack of PublishRequest");
subscription.state = SubscriptionState.LATE;
}
}
};
Subscription.prototype.process_subscription = function () {
const subscription = this;
assert(subscription.publishEngine.pendingPublishRequestCount > 0);
if (!subscription.publishingEnabled) {
// no publish to do, except keep alive
subscription._process_keepAlive();
return;
}
if (!subscription.hasPendingNotifications && subscription.hasMonitoredItemNotifications) {
// collect notification from monitored items
subscription._harvestMonitoredItems();
}
// let process them first
if (subscription.hasPendingNotifications) {
subscription._publish_pending_notifications();
if (subscription.state === SubscriptionState.NORMAL && subscription.hasPendingNotifications) {
// istanbul ignore next
if (doDebug) {
debugLog(" -> pendingPublishRequestCount > 0 && normal state => re-trigger tick event immediately ");
}
// let process an new publish request
setImmediate(subscription._tick.bind(subscription));
}
} else {
subscription._process_keepAlive();
}
};
function w(s, w) {
return ("000" + s).substr(-w);
}
function t(d) {
return w(d.getHours(), 2) + ":" + w(d.getMinutes(), 2) + ":" + w(d.getSeconds(), 2) + ":" + w(d.getMilliseconds(), 3);
}
/**
* @method _tick
* @private
*/
Subscription.prototype._tick = function () {
const subscription = this;
debugLog("Subscription#_tick aborted=", subscription.aborted, "state=", subscription.state.toString());
if (subscription.aborted) {
//xx console.log(" Log aborteds")
//xx // underlying channel has been aborted ...
//xx self.publishEngine.cancelPendingPublishRequestBeforeChannelChange();
//xx // let's still increase lifetime counter to detect timeout
}
if (subscription.state === SubscriptionState.CLOSED) {
console.log("Warning: Subscription#_tick called while subscription is CLOSED");
return;
}
subscription.discardOldSentNotifications();
// istanbul ignore next
if (doDebug) {
debugLog((t(new Date()) + " " + subscription._life_time_counter + "/" + subscription.lifeTimeCount + " Subscription#_tick").cyan, " processing subscriptionId=", subscription.id, "hasMonitoredItemNotifications = ", subscription.hasMonitoredItemNotifications, " publishingIntervalCount =", subscription.publishIntervalCount);
}
if (subscription.publishEngine._on_tick) {
subscription.publishEngine._on_tick();
}
subscription.publishIntervalCount += 1;
subscription.increaseLifeTimeCounter();
if (subscription.lifeTimeHasExpired) {
/* istanbul ignore next */
if (doDebug) {
debugLog("Subscription " + subscription.id + " has expired !!!!! => Terminating".red.bold);
}
/**
* notify the subscription owner that the subscription has expired by exceeding its life time.
* @event expired
*
*/
subscription.emit("expired");
// notify new terminated status only when subscription has timeout.
debugLog("adding StatusChangeNotification notification message for BadTimeout subscription = ", subscription.id);
subscription._addNotificationMessage([new StatusChangeNotification({ status: StatusCodes.BadTimeout})]);
// kill timer and delete monitored items and transfer pending notification messages
subscription.terminate();
return;
}
const publishEngine = subscription.publishEngine;
// istanbul ignore next
if (doDebug) {
debugLog("Subscription#_tick self._pending_notifications= ", subscription._pending_notifications.length);
}
if (publishEngine.pendingPublishRequestCount === 0 && (subscription.hasPendingNotifications || subscription.hasMonitoredItemNotifications)) {
// istanbul ignore next
if (doDebug) {
debugLog("subscription set to LATE hasPendingNotifications = ", subscription.hasPendingNotifications, " hasMonitoredItemNotifications =", subscription.hasMonitoredItemNotifications);
}
subscription.state = SubscriptionState.LATE;
return;
}
if (publishEngine.pendingPublishRequestCount > 0) {
if (subscription.hasPendingNotifications) {
// simply pop pending notification and send it
subscription.process_subscription();
} else if (subscription.hasMonitoredItemNotifications) {
subscription.process_subscription();
} else {
subscription._process_keepAlive();
}
} else {
subscription._process_keepAlive();
}
};
/**
* @method _sendKeepAliveResponse
* @private
*/
Subscription.prototype._sendKeepAliveResponse = function () {
const subscription = this;
const future_sequence_number = subscription._get_future_sequence_number();
debugLog(" -> Subscription#_sendKeepAliveResponse subscriptionId", subscription.id);
if (subscription.publishEngine.send_keep_alive_response(subscription.id, future_sequence_number)) {
subscription.messageSent = true;
/**
* notify the subscription owner that a keepalive message has to be sent.
* @event keepalive
*
*/
subscription.emit("keepalive", future_sequence_number);
subscription.state = SubscriptionState.KEEPALIVE;
return true;
}
return false;
};
/**
* @method resetKeepAliveCounter
* @private
* Reset the Lifetime Counter Variable to the value specified for the lifetime of a Subscription in
* the CreateSubscription Service( 5.13.2).
*/
Subscription.prototype.resetKeepAliveCounter = function () {
const subscription = this;
subscription._keep_alive_counter = 0;
// istanbul ignore next
if (doDebug) {
debugLog(" -> subscriptionId", subscription.id, " Resetting keepAliveCounter = ", subscription._keep_alive_counter, subscription.maxKeepAliveCount);
}
};
/**
* @method increaseKeepAliveCounter
* @private
*/
Subscription.prototype.increaseKeepAliveCounter = function () {
const subscription = this;
subscription._keep_alive_counter += 1;
// istanbul ignore next
if (doDebug) {
debugLog(" -> subscriptionId", subscription.id, " Increasing keepAliveCounter = ", subscription._keep_alive_counter, subscription.maxKeepAliveCount);
}
};
/**
* @property keepAliveCounterHasExpired
* @private
* @type {Boolean} true if the keep alive counter has reach its limit.
*/
Subscription.prototype.__defineGetter__("keepAliveCounterHasExpired", function () {
const subscription = this;
return subscription._keep_alive_counter >= subscription.maxKeepAliveCount;
});
/**
* Reset the Lifetime Counter Variable to the value specified for the lifetime of a Subscription in
* the CreateSubscription Service( 5.13.2).
* @method resetLifeTimeCounter
* @private
*/
Subscription.prototype.resetLifeTimeCounter = function () {
const subscription = this;
subscription._life_time_counter = 0;
};
/**
* @method increaseLifeTimeCounter
* @private
*/
Subscription.prototype.increaseLifeTimeCounter = function () {
const subscription = this;
subscription._life_time_counter += 1;
};
/**
* True if the subscription life time has expired.
*
* @property lifeTimeHasExpired
* @type {boolean} - true if the subscription life time has expired.
*/
Subscription.prototype.__defineGetter__("lifeTimeHasExpired", function () {
const subscription = this;
assert(subscription.lifeTimeCount > 0);
return subscription._life_time_counter >= subscription.lifeTimeCount;
});
/**
* number of milliseconds before this subscription times out (lifeTimeHasExpired === true);
* @property timeToExpiration
* @type {Number}
*/
Subscription.prototype.__defineGetter__("timeToExpiration", function () {
const subscription = this;
return (subscription.lifeTimeCount - subscription._life_time_counter) * subscription.publishingInterval;
});
Subscription.prototype.__defineGetter__("timeToKeepAlive", function () {
const subscription = this;
return (subscription.maxKeepAliveCount - subscription._keep_alive_counter) * subscription.publishingInterval;
});
/**
*
* the server invokes the resetLifeTimeAndKeepAliveCounters method of the subscription
* when the server has send a Publish Response, so that the subscription
* can reset its life time counter.
*
* @method resetLifeTimeAndKeepAliveCounters
*
*/
Subscription.prototype.resetLifeTimeAndKeepAliveCounters = function () {
const subscription = this;
subscription.resetLifeTimeCounter();
subscription.resetKeepAliveCounter();
};
/**
* Terminates the subscription.
* @method terminate
*
* Calling this method will also remove any monitored items.
*
*/
Subscription.prototype.terminate = function () {
assert(arguments.length === 0);
const subscription = this;
debugLog("Subscription#terminate status", subscription.state);
if (subscription.state === SubscriptionState.CLOSED) {
// todo verify if asserting is required here
return;
}
assert(subscription.state !== SubscriptionState.CLOSED, "terminate already called ?");
// stop timer
subscription._stop_timer();
debugLog("terminating Subscription ", subscription.id, " with ", subscription.monitoredItemCount, " monitored items");
// dispose all monitoredItem
const keys = Object.keys(subscription.monitoredItems);
for (const key of keys) {
const status = subscription.removeMonitoredItem(key);
assert(status === StatusCodes.Good);
}
assert(subscription.monitoredItemCount === 0);
if (subscription.$session) {
subscription.$session._unexposeSubscriptionDiagnostics(subscription);
}
subscription.state = SubscriptionState.CLOSED;
/**
* notify the subscription owner that the subscription has been terminated.
* @event "terminated"
*/
subscription.emit("terminated");
subscription.publishEngine.on_close_subscription(subscription);
};
Subscription.prototype.dispose = function () {
const subscription = this;
if (doDebug) {
debugLog("Subscription#dispose" ,subscription.id, subscription.monitoredItemCount);
}
assert(subscription.monitoredItemCount === 0, "MonitoredItems haven't been deleted first !!!");
assert(subscription.timerId === null, "Subscription timer haven't been terminated");
if (subscription.subscriptionDiagnostics) {
subscription.subscriptionDiagnostics.$subscription = null;
subscription.subscriptionDiagnostics = null;
}
subscription.publishEngine = null;
subscription._pending_notifications = null;
subscription._sent_notifications = null;
subscription.sessionId = null;
subscription._sequence_number_generator = null;
subscription.$session = null;
subscription.removeAllListeners();
Subscription.registry.unregister(subscription);
};
Subscription.prototype.__defineGetter__("aborted", function () {
const subscription = this;
const session = subscription.$session;
if (!session) {
return true;
}
return session.aborted;
});
function assert_validNotificationData(n) {
assert(
n instanceof DataChangeNotification ||
n instanceof EventNotificationList ||
n instanceof StatusChangeNotification
);
}
/**
* @method _addNotificationMessage
* @param notificationData {Array<DataChangeNotification|EventNotificationList|StatusChangeNotification>}
*/
Subscription.prototype._addNotificationMessage = function (notificationData) {
assert(_.isArray(notificationData));
assert(notificationData.length === 1 || notificationData.length === 2); // as per spec part 3.
// istanbul ignore next
if (doDebug) {
debugLog("Subscription#_addNotificationMessage".yellow, notificationData.toString());
}
const subscription = this;
assert(_.isObject(notificationData[0]));
assert_validNotificationData(notificationData[0]);
if (notificationData.length === 2) {
assert_validNotificationData(notificationData[1]);
}
const notification_message = new NotificationMessage({
sequenceNumber: subscription._get_next_sequence_number(),
publishTime: new Date(),
notificationData: notificationData
});
subscription._pending_notifications.push({
notification: notification_message,
start_tick: subscription.publishIntervalCount,
publishTime: new Date(),
sequenceNumber: notification_message.sequenceNumber
});
debugLog("pending notification to send ", subscription._pending_notifications.length);
};
Subscription.prototype.getMessageForSequenceNumber = function (sequenceNumber) {
const subscription = this;
function filter_func(e) {
return e.sequenceNumber === sequenceNumber;
}
const notification_message = _.find(subscription._sent_notifications, filter_func);
if (!notification_message) {
return null;
}
return notification_message;
};
/**
* Extract the next Notification that is ready to be sent to the client.
* @method _popNotificationToSend
* @return {NotificationMessage} the Notification to send._pending_notifications
*/
Subscription.prototype._popNotificationToSend = function () {
const subscription = this;
assert(subscription._pending_notifications.length > 0);
const notification_message = subscription._pending_notifications.shift();
subscription._sent_notifications.push(notification_message);
return notification_message;
};
/**
* returns true if the notification has expired
* @method notificationHasExpired
* @param notification
* @return {boolean}
*/
Subscription.prototype.notificationHasExpired = function (notification) {
const subscription = this;
assert(notification.hasOwnProperty("start_tick"));
assert(_.isFinite(notification.start_tick + subscription.maxKeepAliveCount));
return (notification.start_tick + subscription.maxKeepAliveCount) < subscription.publishIntervalCount;
};
const maxNotificationMessagesInQueue = 100;
/**
* discardOldSentNotification find all sent notification message that have expired keep-alive
* and destroy them.