node-opcua-server 2.75.0 → 2.76.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) 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/filter/check_where_clause_on_address_space.d.ts +3 -3
  6. package/dist/filter/check_where_clause_on_address_space.js +22 -22
  7. package/dist/filter/extract_event_fields.d.ts +10 -10
  8. package/dist/filter/extract_event_fields.js +17 -17
  9. package/dist/helper.d.ts +10 -10
  10. package/dist/helper.js +75 -75
  11. package/dist/history_server_capabilities.d.ts +35 -35
  12. package/dist/history_server_capabilities.js +43 -43
  13. package/dist/i_channel_data.d.ts +13 -13
  14. package/dist/i_channel_data.js +2 -2
  15. package/dist/i_register_server_manager.d.ts +16 -16
  16. package/dist/i_register_server_manager.js +2 -2
  17. package/dist/i_server_side_publish_engine.d.ts +36 -36
  18. package/dist/i_server_side_publish_engine.js +49 -49
  19. package/dist/i_socket_data.d.ts +11 -11
  20. package/dist/i_socket_data.js +2 -2
  21. package/dist/index.d.ts +16 -16
  22. package/dist/index.js +32 -32
  23. package/dist/monitored_item.d.ts +177 -177
  24. package/dist/monitored_item.js +1001 -1001
  25. package/dist/node_sampler.d.ts +3 -3
  26. package/dist/node_sampler.js +75 -75
  27. package/dist/opcua_server.d.ts +747 -650
  28. package/dist/opcua_server.js +2431 -2396
  29. package/dist/opcua_server.js.map +1 -1
  30. package/dist/queue.d.ts +11 -11
  31. package/dist/queue.js +71 -71
  32. package/dist/register_server_manager.d.ts +96 -96
  33. package/dist/register_server_manager.js +584 -584
  34. package/dist/register_server_manager_hidden.d.ts +17 -17
  35. package/dist/register_server_manager_hidden.js +27 -27
  36. package/dist/register_server_manager_mdns_only.d.ts +22 -22
  37. package/dist/register_server_manager_mdns_only.js +55 -55
  38. package/dist/server_capabilities.d.ts +148 -148
  39. package/dist/server_capabilities.js +92 -92
  40. package/dist/server_end_point.d.ts +183 -183
  41. package/dist/server_end_point.js +817 -817
  42. package/dist/server_engine.d.ts +317 -317
  43. package/dist/server_engine.js +1716 -1716
  44. package/dist/server_publish_engine.d.ts +113 -113
  45. package/dist/server_publish_engine.js +541 -541
  46. package/dist/server_publish_engine_for_orphan_subscriptions.d.ts +16 -16
  47. package/dist/server_publish_engine_for_orphan_subscriptions.js +51 -51
  48. package/dist/server_session.d.ts +182 -182
  49. package/dist/server_session.js +739 -739
  50. package/dist/server_subscription.d.ts +421 -421
  51. package/dist/server_subscription.js +1346 -1346
  52. package/dist/sessions_compatible_for_transfer.d.ts +2 -2
  53. package/dist/sessions_compatible_for_transfer.js +39 -39
  54. package/dist/user_manager.d.ts +32 -32
  55. package/dist/user_manager.js +74 -74
  56. package/dist/user_manager_ua.d.ts +3 -3
  57. package/dist/user_manager_ua.js +39 -39
  58. package/dist/validate_filter.d.ts +5 -5
  59. package/dist/validate_filter.js +60 -60
  60. package/package.json +47 -49
  61. package/source/opcua_server.ts +154 -14
@@ -1,542 +1,542 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.ServerSidePublishEngine = void 0;
13
- /**
14
- * @module node-opcua-server
15
- */
16
- // tslint:disable:no-console
17
- const events_1 = require("events");
18
- const chalk = require("chalk");
19
- const lodash_1 = require("lodash");
20
- const node_opcua_assert_1 = require("node-opcua-assert");
21
- const node_opcua_debug_1 = require("node-opcua-debug");
22
- const node_opcua_object_registry_1 = require("node-opcua-object-registry");
23
- const node_opcua_status_code_1 = require("node-opcua-status-code");
24
- const node_opcua_types_1 = require("node-opcua-types");
25
- const server_subscription_1 = require("./server_subscription");
26
- const server_subscription_2 = require("./server_subscription");
27
- const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
28
- const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
29
- function traceLog(...args) {
30
- if (!doDebug) {
31
- return;
32
- }
33
- const a = args.map((x) => x);
34
- a.unshift(chalk.yellow(" TRACE "));
35
- debugLog(...a);
36
- }
37
- function _assertValidPublishData(publishData) {
38
- (0, node_opcua_assert_1.assert)(publishData.request instanceof node_opcua_types_1.PublishRequest);
39
- (0, node_opcua_assert_1.assert)(typeof publishData.serverTimeWhenReceived === "number");
40
- (0, node_opcua_assert_1.assert)(Array.isArray(publishData.results));
41
- (0, node_opcua_assert_1.assert)(typeof publishData.callback === "function");
42
- }
43
- function dummy_function() {
44
- /* empty */
45
- }
46
- function addDate(date, delta) {
47
- return new Date(date.getTime() + delta);
48
- }
49
- function timeout_filter(publishData) {
50
- const request = publishData.request;
51
- const results = publishData.results;
52
- if (!request.requestHeader.timeoutHint) {
53
- // no limits
54
- return false;
55
- }
56
- const serverTimeWhenReceived = publishData.serverTimeWhenReceived;
57
- // remark : do not use request.requestHeader.timestamp! here as this is a client date and server and client clocks might differ
58
- const expected_timeout_time = addDate(new Date(serverTimeWhenReceived), request.requestHeader.timeoutHint);
59
- return expected_timeout_time.getTime() < Date.now();
60
- }
61
- /***
62
- * a Publish Engine for a given session
63
- */
64
- class ServerSidePublishEngine extends events_1.EventEmitter {
65
- constructor(options) {
66
- super();
67
- this.maxPublishRequestInQueue = 0;
68
- this.isSessionClosed = false;
69
- this._publish_request_queue = [];
70
- this._closed_subscriptions = [];
71
- options = options || {};
72
- ServerSidePublishEngine.registry.register(this);
73
- // a queue of pending publish request send by the client
74
- // waiting to be used by the server to send notification
75
- this._publish_request_queue = []; // { request :/*PublishRequest*/{},
76
- this._subscriptions = {};
77
- // _closed_subscriptions contains a collection of Subscription that
78
- // have expired but that still need to send some pending notification
79
- // to the client.
80
- // Once publish requests will be received from the client
81
- // the notifications of those subscriptions will be processed so that
82
- // they can be properly disposed.
83
- this._closed_subscriptions = [];
84
- this.maxPublishRequestInQueue = options.maxPublishRequestInQueue || 100;
85
- this.isSessionClosed = false;
86
- }
87
- /**
88
- * @private
89
- */
90
- static transferSubscriptionsToOrphan(srcPublishEngine, destPublishEngine) {
91
- debugLog(chalk.yellow("ServerSidePublishEngine#transferSubscriptionsToOrphan! " + "start transferring long live subscriptions to orphan"));
92
- for (const subscription of Object.values(srcPublishEngine._subscriptions)) {
93
- (0, node_opcua_assert_1.assert)(subscription.publishEngine === srcPublishEngine);
94
- if (subscription.$session) {
95
- subscription.$session._unexposeSubscriptionDiagnostics(subscription);
96
- }
97
- else {
98
- console.warn("Warning: subscription", subscription.id, " has no session attached!!!");
99
- }
100
- ServerSidePublishEngine.transferSubscription(subscription, destPublishEngine, false);
101
- }
102
- (0, node_opcua_assert_1.assert)(srcPublishEngine.subscriptionCount === 0);
103
- debugLog(chalk.yellow("ServerSidePublishEngine#transferSubscriptionsToOrphan! " + "end transferring long lived subscriptions to orphan"));
104
- }
105
- /**
106
- * @param subscription
107
- * @param destPublishEngine
108
- * @param sendInitialValues true if initial values should be sent
109
- * @private
110
- */
111
- static transferSubscription(subscription, destPublishEngine, sendInitialValues) {
112
- return __awaiter(this, void 0, void 0, function* () {
113
- const srcPublishEngine = subscription.publishEngine;
114
- (0, node_opcua_assert_1.assert)(!destPublishEngine.getSubscriptionById(subscription.id));
115
- (0, node_opcua_assert_1.assert)(srcPublishEngine.getSubscriptionById(subscription.id));
116
- // remove pending StatusChangeNotification on the same session that may exist already
117
- destPublishEngine._purge_dangling_subscription(subscription.id);
118
- debugLog(chalk.cyan("ServerSidePublishEngine.transferSubscription live subscriptionId ="), subscription.subscriptionId);
119
- // xx const internalNotification = subscription._flushSentNotifications();
120
- debugLog(chalk.cyan("ServerSidePublishEngine.transferSubscription with = "), subscription.getAvailableSequenceNumbers());
121
- // If the Server transfers the Subscription to the new Session, the Server shall issue a
122
- // StatusChangeNotification notificationMessage with the status code Good_SubscriptionTransferred
123
- // to the old Session.
124
- subscription.notifyTransfer();
125
- const tmp = srcPublishEngine.detach_subscription(subscription);
126
- destPublishEngine.add_subscription(tmp);
127
- subscription.resetLifeTimeCounter();
128
- if (sendInitialValues) {
129
- /* A Boolean parameter with the following values:
130
- TRUE the first Publish response(s) after the TransferSubscriptions call
131
- shall contain the current values of all Monitored Items in the
132
- Subscription where the Monitoring Mode is set to Reporting.
133
- If a value is queued for a data MonitoredItem, the next value in
134
- the queue is sent in the Publish response. If no value is queued
135
- for a data MonitoredItem, the last value sent is repeated in the
136
- Publish response.
137
- FALSE the first Publish response after the TransferSubscriptions call
138
- shall contain only the value changes since the last Publish
139
- response was sent.
140
- This parameter only applies to MonitoredItems used for monitoring Attribute
141
- changes
142
- */
143
- debugLog("Resending initial values");
144
- yield subscription.resendInitialValues();
145
- }
146
- (0, node_opcua_assert_1.assert)(destPublishEngine.getSubscriptionById(subscription.id));
147
- (0, node_opcua_assert_1.assert)(!srcPublishEngine.getSubscriptionById(subscription.id));
148
- return subscription;
149
- });
150
- }
151
- toString() {
152
- let str = "";
153
- str += `maxPublishRequestInQueue ${this.maxPublishRequestInQueue}\n`;
154
- str += `subscriptions ${Object.keys(this._subscriptions).join()}\n`;
155
- str += `closed subscriptions ${this._closed_subscriptions.map((s) => s.id).join()}\n`;
156
- return str;
157
- }
158
- dispose() {
159
- debugLog("ServerSidePublishEngine#dispose");
160
- (0, node_opcua_assert_1.assert)(Object.keys(this._subscriptions).length === 0, "self._subscriptions count!=0");
161
- this._subscriptions = {};
162
- (0, node_opcua_assert_1.assert)(this._closed_subscriptions.length === 0, "self._closed_subscriptions count!=0");
163
- this._closed_subscriptions = [];
164
- ServerSidePublishEngine.registry.unregister(this);
165
- }
166
- process_subscriptionAcknowledgements(subscriptionAcknowledgements) {
167
- // process acknowledgements
168
- subscriptionAcknowledgements = subscriptionAcknowledgements || [];
169
- debugLog("process_subscriptionAcknowledgements = ", subscriptionAcknowledgements);
170
- const results = subscriptionAcknowledgements.map((subscriptionAcknowledgement) => {
171
- const subscription = this.getSubscriptionById(subscriptionAcknowledgement.subscriptionId);
172
- if (!subscription) {
173
- // // try to find the session
174
- // const transferredSubscription = this._transferred_subscriptions.find(
175
- // (s) => s.subscriptionId === subscriptionAcknowledgement.subscriptionId
176
- // );
177
- // if (transferredSubscription) {
178
- // debugLog("Subscription acknowledgeNotification done in transferred subscription ");
179
- // return transferredSubscription.acknowledgeNotification(subscriptionAcknowledgement.sequenceNumber);
180
- // }
181
- return node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid;
182
- }
183
- return subscription.acknowledgeNotification(subscriptionAcknowledgement.sequenceNumber);
184
- });
185
- return results;
186
- }
187
- /**
188
- * get a array of subscription handled by the publish engine.
189
- */
190
- get subscriptions() {
191
- return Object.values(this._subscriptions);
192
- }
193
- /**
194
- */
195
- add_subscription(subscription) {
196
- (0, node_opcua_assert_1.assert)(subscription instanceof server_subscription_1.Subscription);
197
- (0, node_opcua_assert_1.assert)(isFinite(subscription.id));
198
- subscription.publishEngine = (subscription.publishEngine || this);
199
- (0, node_opcua_assert_1.assert)(subscription.publishEngine === this);
200
- (0, node_opcua_assert_1.assert)(!this._subscriptions[subscription.id]);
201
- debugLog("ServerSidePublishEngine#add_subscription - adding subscription with Id:", subscription.id);
202
- this._subscriptions[subscription.id] = subscription;
203
- // xx subscription._flushSentNotifications();
204
- return subscription;
205
- }
206
- detach_subscription(subscription) {
207
- (0, node_opcua_assert_1.assert)(subscription instanceof server_subscription_1.Subscription);
208
- (0, node_opcua_assert_1.assert)(isFinite(subscription.id));
209
- (0, node_opcua_assert_1.assert)(subscription.publishEngine === this);
210
- (0, node_opcua_assert_1.assert)(this._subscriptions[subscription.id] === subscription);
211
- delete this._subscriptions[subscription.id];
212
- subscription.publishEngine = null;
213
- debugLog("ServerSidePublishEngine#detach_subscription detaching subscription with Id:", subscription.id);
214
- return subscription;
215
- }
216
- /**
217
- */
218
- shutdown() {
219
- if (this.subscriptionCount !== 0) {
220
- debugLog(chalk.red("Shutting down pending subscription"));
221
- this.subscriptions.map((subscription) => subscription.terminate());
222
- }
223
- (0, node_opcua_assert_1.assert)(this.subscriptionCount === 0, "subscription shall be removed first before you can shutdown a publish engine");
224
- debugLog("ServerSidePublishEngine#shutdown");
225
- // purge _publish_request_queue
226
- this._publish_request_queue = [];
227
- // purge self._closed_subscriptions
228
- this._closed_subscriptions.map((subscription) => subscription.dispose());
229
- this._closed_subscriptions = [];
230
- }
231
- /**
232
- * number of pending PublishRequest available in queue
233
- */
234
- get pendingPublishRequestCount() {
235
- return this._publish_request_queue.length;
236
- }
237
- /**
238
- * number of subscriptions
239
- */
240
- get subscriptionCount() {
241
- return Object.keys(this._subscriptions).length;
242
- }
243
- get pendingClosedSubscriptionCount() {
244
- return this._closed_subscriptions.length;
245
- }
246
- get currentMonitoredItemCount() {
247
- const subscriptions = Object.values(this._subscriptions);
248
- const result = subscriptions.reduce((cumul, subscription) => {
249
- return cumul + subscription.monitoredItemCount;
250
- }, 0);
251
- (0, node_opcua_assert_1.assert)(isFinite(result));
252
- return result;
253
- }
254
- _purge_dangling_subscription(subscriptionId) {
255
- this._closed_subscriptions = this._closed_subscriptions.filter((s) => s.id !== subscriptionId);
256
- }
257
- on_close_subscription(subscription) {
258
- doDebug && debugLog("ServerSidePublishEngine#on_close_subscription", subscription.id);
259
- if (subscription.hasPendingNotifications) {
260
- doDebug &&
261
- debugLog("ServerSidePublishEngine#on_close_subscription storing subscription", subscription.id, " to _closed_subscriptions because it has pending notification");
262
- this._closed_subscriptions.push(subscription);
263
- }
264
- else {
265
- doDebug && debugLog("ServerSidePublishEngine#on_close_subscription disposing subscription", subscription.id);
266
- // subscription is no longer needed
267
- subscription.dispose();
268
- }
269
- delete this._subscriptions[subscription.id];
270
- while (this._feed_closed_subscription()) {
271
- /* keep looping */
272
- }
273
- if (this.subscriptionCount === 0 && this._closed_subscriptions.length === 0) {
274
- this.cancelPendingPublishRequest();
275
- }
276
- }
277
- /**
278
- * retrieve a subscription by id.
279
- * @param subscriptionId
280
- * @return Subscription
281
- */
282
- getSubscriptionById(subscriptionId) {
283
- return this._subscriptions[subscriptionId.toString()];
284
- }
285
- findLateSubscriptions() {
286
- const subscriptions = Object.values(this._subscriptions);
287
- return subscriptions.filter((subscription) => {
288
- return (subscription.state === server_subscription_2.SubscriptionState.LATE || !subscription.messageSent) && subscription.publishingEnabled;
289
- });
290
- }
291
- get hasLateSubscriptions() {
292
- return this.findLateSubscriptions().length > 0;
293
- }
294
- findLateSubscriptionsSortedByAge() {
295
- let late_subscriptions = this.findLateSubscriptions();
296
- late_subscriptions = (0, lodash_1.sortBy)(late_subscriptions, "timeToExpiration");
297
- return late_subscriptions;
298
- }
299
- cancelPendingPublishRequestBeforeChannelChange() {
300
- this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadSecureChannelClosed);
301
- }
302
- onSessionClose() {
303
- this.isSessionClosed = true;
304
- this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadSessionClosed);
305
- }
306
- /**
307
- * @private
308
- */
309
- cancelPendingPublishRequest() {
310
- (0, node_opcua_assert_1.assert)(this.subscriptionCount === 0);
311
- this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadNoSubscription);
312
- }
313
- /**
314
- *
315
- * @param request
316
- * @param callback
317
- * @private
318
- * @internal
319
- */
320
- _on_PublishRequest(request, callback) {
321
- callback = callback || dummy_function;
322
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
323
- // istanbul ignore next
324
- if (!(request instanceof node_opcua_types_1.PublishRequest)) {
325
- throw new Error("Internal error : expecting a Publish Request here");
326
- }
327
- const subscriptionAckResults = this.process_subscriptionAcknowledgements(request.subscriptionAcknowledgements || []);
328
- const currentTime = Date.now();
329
- const publishData = {
330
- callback,
331
- request,
332
- results: subscriptionAckResults,
333
- serverTimeWhenReceived: currentTime
334
- };
335
- if (this.isSessionClosed) {
336
- traceLog("server has received a PublishRequest but session is Closed");
337
- this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadSessionClosed);
338
- }
339
- else if (this.subscriptionCount === 0) {
340
- if (this._closed_subscriptions.length > 0 && this._closed_subscriptions[0].hasPendingNotifications) {
341
- const verif = this._publish_request_queue.length;
342
- // add the publish request to the queue for later processing
343
- this._publish_request_queue.push(publishData);
344
- const processed = this._feed_closed_subscription();
345
- //xx ( may be subscription has expired by themselves) assert(verif === this._publish_request_queue.length);
346
- //xx ( may be subscription has expired by themselves) assert(processed);
347
- return;
348
- }
349
- traceLog("server has received a PublishRequest but has no subscription opened");
350
- this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadNoSubscription);
351
- }
352
- else {
353
- // add the publish request to the queue for later processing
354
- this._publish_request_queue.push(publishData);
355
- (0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount > 0);
356
- debugLog(chalk.bgWhite.red("Adding a PublishRequest to the queue "), this._publish_request_queue.length);
357
- this._feed_closed_subscription();
358
- this._feed_late_subscription();
359
- this._handle_too_many_requests();
360
- }
361
- }
362
- _find_starving_subscription() {
363
- const late_subscriptions = this.findLateSubscriptions();
364
- function compare_subscriptions(s1, s2) {
365
- if (s1.priority === s2.priority) {
366
- return s1.timeToExpiration < s2.timeToExpiration ? 1 : 0;
367
- }
368
- return s1.priority > s2.priority ? 1 : 0;
369
- }
370
- function findLateSubscriptionSortedByPriority() {
371
- if (late_subscriptions.length === 0) {
372
- return null;
373
- }
374
- late_subscriptions.sort(compare_subscriptions);
375
- // istanbul ignore next
376
- if (doDebug) {
377
- debugLog(late_subscriptions
378
- .map((s) => "[ id = " +
379
- s.id +
380
- " prio=" +
381
- s.priority +
382
- " t=" +
383
- s.timeToExpiration +
384
- " ka=" +
385
- s.timeToKeepAlive +
386
- " m?=" +
387
- s.hasUncollectedMonitoredItemNotifications +
388
- " " +
389
- server_subscription_2.SubscriptionState[s.state] +
390
- " " +
391
- s.messageSent +
392
- "]")
393
- .join(" \n"));
394
- }
395
- return late_subscriptions[late_subscriptions.length - 1];
396
- }
397
- if (this._closed_subscriptions) {
398
- /** */
399
- }
400
- const starving_subscription = /* this.findSubscriptionWaitingForFirstPublish() || */ findLateSubscriptionSortedByPriority();
401
- return starving_subscription;
402
- }
403
- _feed_late_subscription() {
404
- setImmediate(() => {
405
- if (!this.pendingPublishRequestCount) {
406
- return;
407
- }
408
- const starving_subscription = this._find_starving_subscription();
409
- if (starving_subscription) {
410
- doDebug &&
411
- debugLog(chalk.bgWhite.red("feeding most late subscription subscriptionId = "), starving_subscription.id);
412
- starving_subscription.process_subscription();
413
- }
414
- });
415
- }
416
- _feed_closed_subscription() {
417
- if (!this.pendingPublishRequestCount) {
418
- return false;
419
- }
420
- if (this._closed_subscriptions.length === 0) {
421
- debugLog("ServerSidePublishEngine#_feed_closed_subscription -> nothing to do");
422
- return false;
423
- }
424
- // process closed subscription
425
- const closed_subscription = this._closed_subscriptions[0];
426
- (0, node_opcua_assert_1.assert)(closed_subscription.hasPendingNotifications);
427
- debugLog("ServerSidePublishEngine#_feed_closed_subscription for closed_subscription ", closed_subscription.id);
428
- closed_subscription === null || closed_subscription === void 0 ? void 0 : closed_subscription._publish_pending_notifications();
429
- if (!(closed_subscription === null || closed_subscription === void 0 ? void 0 : closed_subscription.hasPendingNotifications)) {
430
- closed_subscription.dispose();
431
- this._closed_subscriptions.shift();
432
- }
433
- return true;
434
- }
435
- _send_error_for_request(publishData, statusCode) {
436
- _assertValidPublishData(publishData);
437
- const response = new node_opcua_types_1.ServiceFault({
438
- responseHeader: { serviceResult: statusCode }
439
- });
440
- this._send_response_for_request(publishData, response);
441
- }
442
- _cancelPendingPublishRequest(statusCode) {
443
- if (this._publish_request_queue) {
444
- debugLog(chalk.red("Cancelling pending PublishRequest with statusCode "), statusCode.toString(), " length =", this._publish_request_queue.length);
445
- }
446
- else {
447
- debugLog(chalk.red("No pending PublishRequest to cancel"));
448
- }
449
- for (const publishData of this._publish_request_queue) {
450
- this._send_error_for_request(publishData, statusCode);
451
- }
452
- this._publish_request_queue = [];
453
- }
454
- _handle_too_many_requests() {
455
- if (this.pendingPublishRequestCount > this.maxPublishRequestInQueue) {
456
- traceLog("server has received too many PublishRequest", this.pendingPublishRequestCount, "/", this.maxPublishRequestInQueue);
457
- (0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount === this.maxPublishRequestInQueue + 1);
458
- // When a Server receives a new Publish request that exceeds its limit it shall de-queue the oldest Publish
459
- // request and return a response with the result set to Bad_TooManyPublishRequests.
460
- // dequeue oldest request
461
- const publishData = this._publish_request_queue.shift();
462
- this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadTooManyPublishRequests);
463
- }
464
- }
465
- /**
466
- * call by a subscription when no notification message is available after the keep alive delay has
467
- * expired.
468
- *
469
- * @method send_keep_alive_response
470
- * @param subscriptionId
471
- * @param future_sequence_number
472
- * @return true if a publish response has been sent
473
- */
474
- send_keep_alive_response(subscriptionId, future_sequence_number) {
475
- // this keep-alive Message informs the Client that the Subscription is still active.
476
- // Each keep-alive Message is a response to a Publish request in which the notification Message
477
- // parameter does not contain any Notifications and that contains the sequence number of the next
478
- // Notification Message that is to be sent.
479
- const subscription = this.getSubscriptionById(subscriptionId);
480
- /* istanbul ignore next */
481
- if (!subscription) {
482
- traceLog("send_keep_alive_response => invalid subscriptionId = ", subscriptionId);
483
- return false;
484
- }
485
- // let check if we have available PublishRequest to send the keep alive
486
- if (this.pendingPublishRequestCount === 0 || subscription.hasPendingNotifications) {
487
- // we cannot send the keep alive PublishResponse
488
- traceLog("send_keep_alive_response => cannot send keep-alive (no PublishRequest left) subscriptionId = ", subscriptionId);
489
- return false;
490
- }
491
- debugLog(`Sending keep alive response for subscription id ${subscription.id} ${subscription.publishingInterval} ${subscription.maxKeepAliveCount}`);
492
- this._send_response(subscription, new node_opcua_types_1.PublishResponse({
493
- availableSequenceNumbers: subscription.getAvailableSequenceNumbers(),
494
- moreNotifications: false,
495
- notificationMessage: {
496
- sequenceNumber: future_sequence_number
497
- },
498
- subscriptionId
499
- }));
500
- return true;
501
- }
502
- _send_response(subscription, response) {
503
- (0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount > 0);
504
- (0, node_opcua_assert_1.assert)(response.subscriptionId !== 0xffffff);
505
- const publishData = this._publish_request_queue.shift();
506
- this._send_valid_response_for_request(publishData, response);
507
- }
508
- _on_tick() {
509
- this._cancelTimeoutRequests();
510
- }
511
- _cancelTimeoutRequests() {
512
- if (this._publish_request_queue.length === 0) {
513
- return;
514
- }
515
- // filter out timeout requests
516
- const parts = (0, lodash_1.partition)(this._publish_request_queue, timeout_filter);
517
- this._publish_request_queue = parts[1]; // still valid
518
- const invalid_published_request = parts[0];
519
- for (const publishData of invalid_published_request) {
520
- if (doDebug) {
521
- debugLog(chalk.cyan(" CANCELING TIMEOUT PUBLISH REQUEST "));
522
- }
523
- this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadTimeout);
524
- }
525
- }
526
- _send_response_for_request(publishData, response) {
527
- response.responseHeader.requestHandle = publishData.request.requestHeader.requestHandle;
528
- publishData.callback(publishData.request, response);
529
- }
530
- _send_valid_response_for_request(publishData, response) {
531
- if (doDebug) {
532
- debugLog("_send_response_for_request ", response.toString());
533
- }
534
- _assertValidPublishData(publishData);
535
- // xx assert(response.responseHeader.requestHandle !== 0,"expecting a valid requestHandle");
536
- response.results = publishData.results;
537
- this._send_response_for_request(publishData, response);
538
- }
539
- }
540
- exports.ServerSidePublishEngine = ServerSidePublishEngine;
541
- ServerSidePublishEngine.registry = new node_opcua_object_registry_1.ObjectRegistry();
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ServerSidePublishEngine = void 0;
13
+ /**
14
+ * @module node-opcua-server
15
+ */
16
+ // tslint:disable:no-console
17
+ const events_1 = require("events");
18
+ const chalk = require("chalk");
19
+ const lodash_1 = require("lodash");
20
+ const node_opcua_assert_1 = require("node-opcua-assert");
21
+ const node_opcua_debug_1 = require("node-opcua-debug");
22
+ const node_opcua_object_registry_1 = require("node-opcua-object-registry");
23
+ const node_opcua_status_code_1 = require("node-opcua-status-code");
24
+ const node_opcua_types_1 = require("node-opcua-types");
25
+ const server_subscription_1 = require("./server_subscription");
26
+ const server_subscription_2 = require("./server_subscription");
27
+ const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
28
+ const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
29
+ function traceLog(...args) {
30
+ if (!doDebug) {
31
+ return;
32
+ }
33
+ const a = args.map((x) => x);
34
+ a.unshift(chalk.yellow(" TRACE "));
35
+ debugLog(...a);
36
+ }
37
+ function _assertValidPublishData(publishData) {
38
+ (0, node_opcua_assert_1.assert)(publishData.request instanceof node_opcua_types_1.PublishRequest);
39
+ (0, node_opcua_assert_1.assert)(typeof publishData.serverTimeWhenReceived === "number");
40
+ (0, node_opcua_assert_1.assert)(Array.isArray(publishData.results));
41
+ (0, node_opcua_assert_1.assert)(typeof publishData.callback === "function");
42
+ }
43
+ function dummy_function() {
44
+ /* empty */
45
+ }
46
+ function addDate(date, delta) {
47
+ return new Date(date.getTime() + delta);
48
+ }
49
+ function timeout_filter(publishData) {
50
+ const request = publishData.request;
51
+ const results = publishData.results;
52
+ if (!request.requestHeader.timeoutHint) {
53
+ // no limits
54
+ return false;
55
+ }
56
+ const serverTimeWhenReceived = publishData.serverTimeWhenReceived;
57
+ // remark : do not use request.requestHeader.timestamp! here as this is a client date and server and client clocks might differ
58
+ const expected_timeout_time = addDate(new Date(serverTimeWhenReceived), request.requestHeader.timeoutHint);
59
+ return expected_timeout_time.getTime() < Date.now();
60
+ }
61
+ /***
62
+ * a Publish Engine for a given session
63
+ */
64
+ class ServerSidePublishEngine extends events_1.EventEmitter {
65
+ constructor(options) {
66
+ super();
67
+ this.maxPublishRequestInQueue = 0;
68
+ this.isSessionClosed = false;
69
+ this._publish_request_queue = [];
70
+ this._closed_subscriptions = [];
71
+ options = options || {};
72
+ ServerSidePublishEngine.registry.register(this);
73
+ // a queue of pending publish request send by the client
74
+ // waiting to be used by the server to send notification
75
+ this._publish_request_queue = []; // { request :/*PublishRequest*/{},
76
+ this._subscriptions = {};
77
+ // _closed_subscriptions contains a collection of Subscription that
78
+ // have expired but that still need to send some pending notification
79
+ // to the client.
80
+ // Once publish requests will be received from the client
81
+ // the notifications of those subscriptions will be processed so that
82
+ // they can be properly disposed.
83
+ this._closed_subscriptions = [];
84
+ this.maxPublishRequestInQueue = options.maxPublishRequestInQueue || 100;
85
+ this.isSessionClosed = false;
86
+ }
87
+ /**
88
+ * @private
89
+ */
90
+ static transferSubscriptionsToOrphan(srcPublishEngine, destPublishEngine) {
91
+ debugLog(chalk.yellow("ServerSidePublishEngine#transferSubscriptionsToOrphan! " + "start transferring long live subscriptions to orphan"));
92
+ for (const subscription of Object.values(srcPublishEngine._subscriptions)) {
93
+ (0, node_opcua_assert_1.assert)(subscription.publishEngine === srcPublishEngine);
94
+ if (subscription.$session) {
95
+ subscription.$session._unexposeSubscriptionDiagnostics(subscription);
96
+ }
97
+ else {
98
+ console.warn("Warning: subscription", subscription.id, " has no session attached!!!");
99
+ }
100
+ ServerSidePublishEngine.transferSubscription(subscription, destPublishEngine, false);
101
+ }
102
+ (0, node_opcua_assert_1.assert)(srcPublishEngine.subscriptionCount === 0);
103
+ debugLog(chalk.yellow("ServerSidePublishEngine#transferSubscriptionsToOrphan! " + "end transferring long lived subscriptions to orphan"));
104
+ }
105
+ /**
106
+ * @param subscription
107
+ * @param destPublishEngine
108
+ * @param sendInitialValues true if initial values should be sent
109
+ * @private
110
+ */
111
+ static transferSubscription(subscription, destPublishEngine, sendInitialValues) {
112
+ return __awaiter(this, void 0, void 0, function* () {
113
+ const srcPublishEngine = subscription.publishEngine;
114
+ (0, node_opcua_assert_1.assert)(!destPublishEngine.getSubscriptionById(subscription.id));
115
+ (0, node_opcua_assert_1.assert)(srcPublishEngine.getSubscriptionById(subscription.id));
116
+ // remove pending StatusChangeNotification on the same session that may exist already
117
+ destPublishEngine._purge_dangling_subscription(subscription.id);
118
+ debugLog(chalk.cyan("ServerSidePublishEngine.transferSubscription live subscriptionId ="), subscription.subscriptionId);
119
+ // xx const internalNotification = subscription._flushSentNotifications();
120
+ debugLog(chalk.cyan("ServerSidePublishEngine.transferSubscription with = "), subscription.getAvailableSequenceNumbers());
121
+ // If the Server transfers the Subscription to the new Session, the Server shall issue a
122
+ // StatusChangeNotification notificationMessage with the status code Good_SubscriptionTransferred
123
+ // to the old Session.
124
+ subscription.notifyTransfer();
125
+ const tmp = srcPublishEngine.detach_subscription(subscription);
126
+ destPublishEngine.add_subscription(tmp);
127
+ subscription.resetLifeTimeCounter();
128
+ if (sendInitialValues) {
129
+ /* A Boolean parameter with the following values:
130
+ TRUE the first Publish response(s) after the TransferSubscriptions call
131
+ shall contain the current values of all Monitored Items in the
132
+ Subscription where the Monitoring Mode is set to Reporting.
133
+ If a value is queued for a data MonitoredItem, the next value in
134
+ the queue is sent in the Publish response. If no value is queued
135
+ for a data MonitoredItem, the last value sent is repeated in the
136
+ Publish response.
137
+ FALSE the first Publish response after the TransferSubscriptions call
138
+ shall contain only the value changes since the last Publish
139
+ response was sent.
140
+ This parameter only applies to MonitoredItems used for monitoring Attribute
141
+ changes
142
+ */
143
+ debugLog("Resending initial values");
144
+ yield subscription.resendInitialValues();
145
+ }
146
+ (0, node_opcua_assert_1.assert)(destPublishEngine.getSubscriptionById(subscription.id));
147
+ (0, node_opcua_assert_1.assert)(!srcPublishEngine.getSubscriptionById(subscription.id));
148
+ return subscription;
149
+ });
150
+ }
151
+ toString() {
152
+ let str = "";
153
+ str += `maxPublishRequestInQueue ${this.maxPublishRequestInQueue}\n`;
154
+ str += `subscriptions ${Object.keys(this._subscriptions).join()}\n`;
155
+ str += `closed subscriptions ${this._closed_subscriptions.map((s) => s.id).join()}\n`;
156
+ return str;
157
+ }
158
+ dispose() {
159
+ debugLog("ServerSidePublishEngine#dispose");
160
+ (0, node_opcua_assert_1.assert)(Object.keys(this._subscriptions).length === 0, "self._subscriptions count!=0");
161
+ this._subscriptions = {};
162
+ (0, node_opcua_assert_1.assert)(this._closed_subscriptions.length === 0, "self._closed_subscriptions count!=0");
163
+ this._closed_subscriptions = [];
164
+ ServerSidePublishEngine.registry.unregister(this);
165
+ }
166
+ process_subscriptionAcknowledgements(subscriptionAcknowledgements) {
167
+ // process acknowledgements
168
+ subscriptionAcknowledgements = subscriptionAcknowledgements || [];
169
+ debugLog("process_subscriptionAcknowledgements = ", subscriptionAcknowledgements);
170
+ const results = subscriptionAcknowledgements.map((subscriptionAcknowledgement) => {
171
+ const subscription = this.getSubscriptionById(subscriptionAcknowledgement.subscriptionId);
172
+ if (!subscription) {
173
+ // // try to find the session
174
+ // const transferredSubscription = this._transferred_subscriptions.find(
175
+ // (s) => s.subscriptionId === subscriptionAcknowledgement.subscriptionId
176
+ // );
177
+ // if (transferredSubscription) {
178
+ // debugLog("Subscription acknowledgeNotification done in transferred subscription ");
179
+ // return transferredSubscription.acknowledgeNotification(subscriptionAcknowledgement.sequenceNumber);
180
+ // }
181
+ return node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid;
182
+ }
183
+ return subscription.acknowledgeNotification(subscriptionAcknowledgement.sequenceNumber);
184
+ });
185
+ return results;
186
+ }
187
+ /**
188
+ * get a array of subscription handled by the publish engine.
189
+ */
190
+ get subscriptions() {
191
+ return Object.values(this._subscriptions);
192
+ }
193
+ /**
194
+ */
195
+ add_subscription(subscription) {
196
+ (0, node_opcua_assert_1.assert)(subscription instanceof server_subscription_1.Subscription);
197
+ (0, node_opcua_assert_1.assert)(isFinite(subscription.id));
198
+ subscription.publishEngine = (subscription.publishEngine || this);
199
+ (0, node_opcua_assert_1.assert)(subscription.publishEngine === this);
200
+ (0, node_opcua_assert_1.assert)(!this._subscriptions[subscription.id]);
201
+ debugLog("ServerSidePublishEngine#add_subscription - adding subscription with Id:", subscription.id);
202
+ this._subscriptions[subscription.id] = subscription;
203
+ // xx subscription._flushSentNotifications();
204
+ return subscription;
205
+ }
206
+ detach_subscription(subscription) {
207
+ (0, node_opcua_assert_1.assert)(subscription instanceof server_subscription_1.Subscription);
208
+ (0, node_opcua_assert_1.assert)(isFinite(subscription.id));
209
+ (0, node_opcua_assert_1.assert)(subscription.publishEngine === this);
210
+ (0, node_opcua_assert_1.assert)(this._subscriptions[subscription.id] === subscription);
211
+ delete this._subscriptions[subscription.id];
212
+ subscription.publishEngine = null;
213
+ debugLog("ServerSidePublishEngine#detach_subscription detaching subscription with Id:", subscription.id);
214
+ return subscription;
215
+ }
216
+ /**
217
+ */
218
+ shutdown() {
219
+ if (this.subscriptionCount !== 0) {
220
+ debugLog(chalk.red("Shutting down pending subscription"));
221
+ this.subscriptions.map((subscription) => subscription.terminate());
222
+ }
223
+ (0, node_opcua_assert_1.assert)(this.subscriptionCount === 0, "subscription shall be removed first before you can shutdown a publish engine");
224
+ debugLog("ServerSidePublishEngine#shutdown");
225
+ // purge _publish_request_queue
226
+ this._publish_request_queue = [];
227
+ // purge self._closed_subscriptions
228
+ this._closed_subscriptions.map((subscription) => subscription.dispose());
229
+ this._closed_subscriptions = [];
230
+ }
231
+ /**
232
+ * number of pending PublishRequest available in queue
233
+ */
234
+ get pendingPublishRequestCount() {
235
+ return this._publish_request_queue.length;
236
+ }
237
+ /**
238
+ * number of subscriptions
239
+ */
240
+ get subscriptionCount() {
241
+ return Object.keys(this._subscriptions).length;
242
+ }
243
+ get pendingClosedSubscriptionCount() {
244
+ return this._closed_subscriptions.length;
245
+ }
246
+ get currentMonitoredItemCount() {
247
+ const subscriptions = Object.values(this._subscriptions);
248
+ const result = subscriptions.reduce((cumul, subscription) => {
249
+ return cumul + subscription.monitoredItemCount;
250
+ }, 0);
251
+ (0, node_opcua_assert_1.assert)(isFinite(result));
252
+ return result;
253
+ }
254
+ _purge_dangling_subscription(subscriptionId) {
255
+ this._closed_subscriptions = this._closed_subscriptions.filter((s) => s.id !== subscriptionId);
256
+ }
257
+ on_close_subscription(subscription) {
258
+ doDebug && debugLog("ServerSidePublishEngine#on_close_subscription", subscription.id);
259
+ if (subscription.hasPendingNotifications) {
260
+ doDebug &&
261
+ debugLog("ServerSidePublishEngine#on_close_subscription storing subscription", subscription.id, " to _closed_subscriptions because it has pending notification");
262
+ this._closed_subscriptions.push(subscription);
263
+ }
264
+ else {
265
+ doDebug && debugLog("ServerSidePublishEngine#on_close_subscription disposing subscription", subscription.id);
266
+ // subscription is no longer needed
267
+ subscription.dispose();
268
+ }
269
+ delete this._subscriptions[subscription.id];
270
+ while (this._feed_closed_subscription()) {
271
+ /* keep looping */
272
+ }
273
+ if (this.subscriptionCount === 0 && this._closed_subscriptions.length === 0) {
274
+ this.cancelPendingPublishRequest();
275
+ }
276
+ }
277
+ /**
278
+ * retrieve a subscription by id.
279
+ * @param subscriptionId
280
+ * @return Subscription
281
+ */
282
+ getSubscriptionById(subscriptionId) {
283
+ return this._subscriptions[subscriptionId.toString()];
284
+ }
285
+ findLateSubscriptions() {
286
+ const subscriptions = Object.values(this._subscriptions);
287
+ return subscriptions.filter((subscription) => {
288
+ return (subscription.state === server_subscription_2.SubscriptionState.LATE || !subscription.messageSent) && subscription.publishingEnabled;
289
+ });
290
+ }
291
+ get hasLateSubscriptions() {
292
+ return this.findLateSubscriptions().length > 0;
293
+ }
294
+ findLateSubscriptionsSortedByAge() {
295
+ let late_subscriptions = this.findLateSubscriptions();
296
+ late_subscriptions = (0, lodash_1.sortBy)(late_subscriptions, "timeToExpiration");
297
+ return late_subscriptions;
298
+ }
299
+ cancelPendingPublishRequestBeforeChannelChange() {
300
+ this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadSecureChannelClosed);
301
+ }
302
+ onSessionClose() {
303
+ this.isSessionClosed = true;
304
+ this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadSessionClosed);
305
+ }
306
+ /**
307
+ * @private
308
+ */
309
+ cancelPendingPublishRequest() {
310
+ (0, node_opcua_assert_1.assert)(this.subscriptionCount === 0);
311
+ this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadNoSubscription);
312
+ }
313
+ /**
314
+ *
315
+ * @param request
316
+ * @param callback
317
+ * @private
318
+ * @internal
319
+ */
320
+ _on_PublishRequest(request, callback) {
321
+ callback = callback || dummy_function;
322
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
323
+ // istanbul ignore next
324
+ if (!(request instanceof node_opcua_types_1.PublishRequest)) {
325
+ throw new Error("Internal error : expecting a Publish Request here");
326
+ }
327
+ const subscriptionAckResults = this.process_subscriptionAcknowledgements(request.subscriptionAcknowledgements || []);
328
+ const currentTime = Date.now();
329
+ const publishData = {
330
+ callback,
331
+ request,
332
+ results: subscriptionAckResults,
333
+ serverTimeWhenReceived: currentTime
334
+ };
335
+ if (this.isSessionClosed) {
336
+ traceLog("server has received a PublishRequest but session is Closed");
337
+ this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadSessionClosed);
338
+ }
339
+ else if (this.subscriptionCount === 0) {
340
+ if (this._closed_subscriptions.length > 0 && this._closed_subscriptions[0].hasPendingNotifications) {
341
+ const verif = this._publish_request_queue.length;
342
+ // add the publish request to the queue for later processing
343
+ this._publish_request_queue.push(publishData);
344
+ const processed = this._feed_closed_subscription();
345
+ //xx ( may be subscription has expired by themselves) assert(verif === this._publish_request_queue.length);
346
+ //xx ( may be subscription has expired by themselves) assert(processed);
347
+ return;
348
+ }
349
+ traceLog("server has received a PublishRequest but has no subscription opened");
350
+ this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadNoSubscription);
351
+ }
352
+ else {
353
+ // add the publish request to the queue for later processing
354
+ this._publish_request_queue.push(publishData);
355
+ (0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount > 0);
356
+ debugLog(chalk.bgWhite.red("Adding a PublishRequest to the queue "), this._publish_request_queue.length);
357
+ this._feed_closed_subscription();
358
+ this._feed_late_subscription();
359
+ this._handle_too_many_requests();
360
+ }
361
+ }
362
+ _find_starving_subscription() {
363
+ const late_subscriptions = this.findLateSubscriptions();
364
+ function compare_subscriptions(s1, s2) {
365
+ if (s1.priority === s2.priority) {
366
+ return s1.timeToExpiration < s2.timeToExpiration ? 1 : 0;
367
+ }
368
+ return s1.priority > s2.priority ? 1 : 0;
369
+ }
370
+ function findLateSubscriptionSortedByPriority() {
371
+ if (late_subscriptions.length === 0) {
372
+ return null;
373
+ }
374
+ late_subscriptions.sort(compare_subscriptions);
375
+ // istanbul ignore next
376
+ if (doDebug) {
377
+ debugLog(late_subscriptions
378
+ .map((s) => "[ id = " +
379
+ s.id +
380
+ " prio=" +
381
+ s.priority +
382
+ " t=" +
383
+ s.timeToExpiration +
384
+ " ka=" +
385
+ s.timeToKeepAlive +
386
+ " m?=" +
387
+ s.hasUncollectedMonitoredItemNotifications +
388
+ " " +
389
+ server_subscription_2.SubscriptionState[s.state] +
390
+ " " +
391
+ s.messageSent +
392
+ "]")
393
+ .join(" \n"));
394
+ }
395
+ return late_subscriptions[late_subscriptions.length - 1];
396
+ }
397
+ if (this._closed_subscriptions) {
398
+ /** */
399
+ }
400
+ const starving_subscription = /* this.findSubscriptionWaitingForFirstPublish() || */ findLateSubscriptionSortedByPriority();
401
+ return starving_subscription;
402
+ }
403
+ _feed_late_subscription() {
404
+ setImmediate(() => {
405
+ if (!this.pendingPublishRequestCount) {
406
+ return;
407
+ }
408
+ const starving_subscription = this._find_starving_subscription();
409
+ if (starving_subscription) {
410
+ doDebug &&
411
+ debugLog(chalk.bgWhite.red("feeding most late subscription subscriptionId = "), starving_subscription.id);
412
+ starving_subscription.process_subscription();
413
+ }
414
+ });
415
+ }
416
+ _feed_closed_subscription() {
417
+ if (!this.pendingPublishRequestCount) {
418
+ return false;
419
+ }
420
+ if (this._closed_subscriptions.length === 0) {
421
+ debugLog("ServerSidePublishEngine#_feed_closed_subscription -> nothing to do");
422
+ return false;
423
+ }
424
+ // process closed subscription
425
+ const closed_subscription = this._closed_subscriptions[0];
426
+ (0, node_opcua_assert_1.assert)(closed_subscription.hasPendingNotifications);
427
+ debugLog("ServerSidePublishEngine#_feed_closed_subscription for closed_subscription ", closed_subscription.id);
428
+ closed_subscription === null || closed_subscription === void 0 ? void 0 : closed_subscription._publish_pending_notifications();
429
+ if (!(closed_subscription === null || closed_subscription === void 0 ? void 0 : closed_subscription.hasPendingNotifications)) {
430
+ closed_subscription.dispose();
431
+ this._closed_subscriptions.shift();
432
+ }
433
+ return true;
434
+ }
435
+ _send_error_for_request(publishData, statusCode) {
436
+ _assertValidPublishData(publishData);
437
+ const response = new node_opcua_types_1.ServiceFault({
438
+ responseHeader: { serviceResult: statusCode }
439
+ });
440
+ this._send_response_for_request(publishData, response);
441
+ }
442
+ _cancelPendingPublishRequest(statusCode) {
443
+ if (this._publish_request_queue) {
444
+ debugLog(chalk.red("Cancelling pending PublishRequest with statusCode "), statusCode.toString(), " length =", this._publish_request_queue.length);
445
+ }
446
+ else {
447
+ debugLog(chalk.red("No pending PublishRequest to cancel"));
448
+ }
449
+ for (const publishData of this._publish_request_queue) {
450
+ this._send_error_for_request(publishData, statusCode);
451
+ }
452
+ this._publish_request_queue = [];
453
+ }
454
+ _handle_too_many_requests() {
455
+ if (this.pendingPublishRequestCount > this.maxPublishRequestInQueue) {
456
+ traceLog("server has received too many PublishRequest", this.pendingPublishRequestCount, "/", this.maxPublishRequestInQueue);
457
+ (0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount === this.maxPublishRequestInQueue + 1);
458
+ // When a Server receives a new Publish request that exceeds its limit it shall de-queue the oldest Publish
459
+ // request and return a response with the result set to Bad_TooManyPublishRequests.
460
+ // dequeue oldest request
461
+ const publishData = this._publish_request_queue.shift();
462
+ this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadTooManyPublishRequests);
463
+ }
464
+ }
465
+ /**
466
+ * call by a subscription when no notification message is available after the keep alive delay has
467
+ * expired.
468
+ *
469
+ * @method send_keep_alive_response
470
+ * @param subscriptionId
471
+ * @param future_sequence_number
472
+ * @return true if a publish response has been sent
473
+ */
474
+ send_keep_alive_response(subscriptionId, future_sequence_number) {
475
+ // this keep-alive Message informs the Client that the Subscription is still active.
476
+ // Each keep-alive Message is a response to a Publish request in which the notification Message
477
+ // parameter does not contain any Notifications and that contains the sequence number of the next
478
+ // Notification Message that is to be sent.
479
+ const subscription = this.getSubscriptionById(subscriptionId);
480
+ /* istanbul ignore next */
481
+ if (!subscription) {
482
+ traceLog("send_keep_alive_response => invalid subscriptionId = ", subscriptionId);
483
+ return false;
484
+ }
485
+ // let check if we have available PublishRequest to send the keep alive
486
+ if (this.pendingPublishRequestCount === 0 || subscription.hasPendingNotifications) {
487
+ // we cannot send the keep alive PublishResponse
488
+ traceLog("send_keep_alive_response => cannot send keep-alive (no PublishRequest left) subscriptionId = ", subscriptionId);
489
+ return false;
490
+ }
491
+ debugLog(`Sending keep alive response for subscription id ${subscription.id} ${subscription.publishingInterval} ${subscription.maxKeepAliveCount}`);
492
+ this._send_response(subscription, new node_opcua_types_1.PublishResponse({
493
+ availableSequenceNumbers: subscription.getAvailableSequenceNumbers(),
494
+ moreNotifications: false,
495
+ notificationMessage: {
496
+ sequenceNumber: future_sequence_number
497
+ },
498
+ subscriptionId
499
+ }));
500
+ return true;
501
+ }
502
+ _send_response(subscription, response) {
503
+ (0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount > 0);
504
+ (0, node_opcua_assert_1.assert)(response.subscriptionId !== 0xffffff);
505
+ const publishData = this._publish_request_queue.shift();
506
+ this._send_valid_response_for_request(publishData, response);
507
+ }
508
+ _on_tick() {
509
+ this._cancelTimeoutRequests();
510
+ }
511
+ _cancelTimeoutRequests() {
512
+ if (this._publish_request_queue.length === 0) {
513
+ return;
514
+ }
515
+ // filter out timeout requests
516
+ const parts = (0, lodash_1.partition)(this._publish_request_queue, timeout_filter);
517
+ this._publish_request_queue = parts[1]; // still valid
518
+ const invalid_published_request = parts[0];
519
+ for (const publishData of invalid_published_request) {
520
+ if (doDebug) {
521
+ debugLog(chalk.cyan(" CANCELING TIMEOUT PUBLISH REQUEST "));
522
+ }
523
+ this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadTimeout);
524
+ }
525
+ }
526
+ _send_response_for_request(publishData, response) {
527
+ response.responseHeader.requestHandle = publishData.request.requestHeader.requestHandle;
528
+ publishData.callback(publishData.request, response);
529
+ }
530
+ _send_valid_response_for_request(publishData, response) {
531
+ if (doDebug) {
532
+ debugLog("_send_response_for_request ", response.toString());
533
+ }
534
+ _assertValidPublishData(publishData);
535
+ // xx assert(response.responseHeader.requestHandle !== 0,"expecting a valid requestHandle");
536
+ response.results = publishData.results;
537
+ this._send_response_for_request(publishData, response);
538
+ }
539
+ }
540
+ exports.ServerSidePublishEngine = ServerSidePublishEngine;
541
+ ServerSidePublishEngine.registry = new node_opcua_object_registry_1.ObjectRegistry();
542
542
  //# sourceMappingURL=server_publish_engine.js.map