node-opcua-server 2.71.0 → 2.72.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 (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 +26 -26
  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,531 +1,531 @@
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
- destPublishEngine.add_subscription(srcPublishEngine.detach_subscription(subscription));
126
- subscription.resetLifeTimeCounter();
127
- if (sendInitialValues) {
128
- /* A Boolean parameter with the following values:
129
- TRUE the first Publish response(s) after the TransferSubscriptions call
130
- shall contain the current values of all Monitored Items in the
131
- Subscription where the Monitoring Mode is set to Reporting.
132
- If a value is queued for a data MonitoredItem, the next value in
133
- the queue is sent in the Publish response. If no value is queued
134
- for a data MonitoredItem, the last value sent is repeated in the
135
- Publish response.
136
- FALSE the first Publish response after the TransferSubscriptions call
137
- shall contain only the value changes since the last Publish
138
- response was sent.
139
- This parameter only applies to MonitoredItems used for monitoring Attribute
140
- changes
141
- */
142
- debugLog("Resending initial values");
143
- yield subscription.resendInitialValues();
144
- }
145
- (0, node_opcua_assert_1.assert)(destPublishEngine.getSubscriptionById(subscription.id));
146
- (0, node_opcua_assert_1.assert)(!srcPublishEngine.getSubscriptionById(subscription.id));
147
- });
148
- }
149
- toString() {
150
- let str = "";
151
- str += `maxPublishRequestInQueue ${this.maxPublishRequestInQueue}\n`;
152
- str += `subscriptions ${Object.keys(this._subscriptions).join()}\n`;
153
- str += `closed subscriptions ${this._closed_subscriptions.map((s) => s.id).join()}\n`;
154
- return str;
155
- }
156
- dispose() {
157
- debugLog("ServerSidePublishEngine#dispose");
158
- (0, node_opcua_assert_1.assert)(Object.keys(this._subscriptions).length === 0, "self._subscriptions count!=0");
159
- this._subscriptions = {};
160
- (0, node_opcua_assert_1.assert)(this._closed_subscriptions.length === 0, "self._closed_subscriptions count!=0");
161
- this._closed_subscriptions = [];
162
- ServerSidePublishEngine.registry.unregister(this);
163
- }
164
- process_subscriptionAcknowledgements(subscriptionAcknowledgements) {
165
- // process acknowledgements
166
- subscriptionAcknowledgements = subscriptionAcknowledgements || [];
167
- debugLog("process_subscriptionAcknowledgements = ", subscriptionAcknowledgements);
168
- const results = subscriptionAcknowledgements.map((subscriptionAcknowledgement) => {
169
- const subscription = this.getSubscriptionById(subscriptionAcknowledgement.subscriptionId);
170
- if (!subscription) {
171
- // // try to find the session
172
- // const transferredSubscription = this._transferred_subscriptions.find(
173
- // (s) => s.subscriptionId === subscriptionAcknowledgement.subscriptionId
174
- // );
175
- // if (transferredSubscription) {
176
- // debugLog("Subscription acknowledgeNotification done in transferred subscription ");
177
- // return transferredSubscription.acknowledgeNotification(subscriptionAcknowledgement.sequenceNumber);
178
- // }
179
- return node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid;
180
- }
181
- return subscription.acknowledgeNotification(subscriptionAcknowledgement.sequenceNumber);
182
- });
183
- return results;
184
- }
185
- /**
186
- * get a array of subscription handled by the publish engine.
187
- */
188
- get subscriptions() {
189
- return Object.values(this._subscriptions);
190
- }
191
- /**
192
- */
193
- add_subscription(subscription) {
194
- (0, node_opcua_assert_1.assert)(subscription instanceof server_subscription_1.Subscription);
195
- (0, node_opcua_assert_1.assert)(isFinite(subscription.id));
196
- subscription.publishEngine = (subscription.publishEngine || this);
197
- (0, node_opcua_assert_1.assert)(subscription.publishEngine === this);
198
- (0, node_opcua_assert_1.assert)(!this._subscriptions[subscription.id]);
199
- debugLog("ServerSidePublishEngine#add_subscription - adding subscription with Id:", subscription.id);
200
- this._subscriptions[subscription.id] = subscription;
201
- // xx subscription._flushSentNotifications();
202
- return subscription;
203
- }
204
- detach_subscription(subscription) {
205
- (0, node_opcua_assert_1.assert)(subscription instanceof server_subscription_1.Subscription);
206
- (0, node_opcua_assert_1.assert)(isFinite(subscription.id));
207
- (0, node_opcua_assert_1.assert)(subscription.publishEngine === this);
208
- (0, node_opcua_assert_1.assert)(this._subscriptions[subscription.id] === subscription);
209
- delete this._subscriptions[subscription.id];
210
- subscription.publishEngine = null;
211
- debugLog("ServerSidePublishEngine#detach_subscription detaching subscription with Id:", subscription.id);
212
- return subscription;
213
- }
214
- /**
215
- */
216
- shutdown() {
217
- if (this.subscriptionCount !== 0) {
218
- debugLog(chalk.red("Shutting down pending subscription"));
219
- this.subscriptions.map((subscription) => subscription.terminate());
220
- }
221
- (0, node_opcua_assert_1.assert)(this.subscriptionCount === 0, "subscription shall be removed first before you can shutdown a publish engine");
222
- debugLog("ServerSidePublishEngine#shutdown");
223
- // purge _publish_request_queue
224
- this._publish_request_queue = [];
225
- // purge self._closed_subscriptions
226
- this._closed_subscriptions.map((subscription) => subscription.dispose());
227
- this._closed_subscriptions = [];
228
- }
229
- /**
230
- * number of pending PublishRequest available in queue
231
- */
232
- get pendingPublishRequestCount() {
233
- return this._publish_request_queue.length;
234
- }
235
- /**
236
- * number of subscriptions
237
- */
238
- get subscriptionCount() {
239
- return Object.keys(this._subscriptions).length;
240
- }
241
- get pendingClosedSubscriptionCount() {
242
- return this._closed_subscriptions.length;
243
- }
244
- get currentMonitoredItemCount() {
245
- const subscriptions = Object.values(this._subscriptions);
246
- const result = subscriptions.reduce((cumul, subscription) => {
247
- return cumul + subscription.monitoredItemCount;
248
- }, 0);
249
- (0, node_opcua_assert_1.assert)(isFinite(result));
250
- return result;
251
- }
252
- _purge_dangling_subscription(subscriptionId) {
253
- this._closed_subscriptions = this._closed_subscriptions.filter((s) => s.id !== subscriptionId);
254
- }
255
- on_close_subscription(subscription) {
256
- debugLog("ServerSidePublishEngine#on_close_subscription", subscription.id);
257
- if (subscription.hasPendingNotifications) {
258
- debugLog("ServerSidePublishEngine#on_close_subscription storing subscription", subscription.id, " to _closed_subscriptions because it has pending notification");
259
- this._closed_subscriptions.push(subscription);
260
- }
261
- else {
262
- debugLog("ServerSidePublishEngine#on_close_subscription disposing subscription", subscription.id);
263
- // subscription is no longer needed
264
- subscription.dispose();
265
- }
266
- delete this._subscriptions[subscription.id];
267
- while (this._feed_closed_subscription()) {
268
- /* keep looping */
269
- }
270
- if (this.subscriptionCount === 0 && this._closed_subscriptions.length === 0) {
271
- this.cancelPendingPublishRequest();
272
- }
273
- }
274
- /**
275
- * retrieve a subscription by id.
276
- * @param subscriptionId
277
- * @return Subscription
278
- */
279
- getSubscriptionById(subscriptionId) {
280
- return this._subscriptions[subscriptionId.toString()];
281
- }
282
- findLateSubscriptions() {
283
- const subscriptions = Object.values(this._subscriptions);
284
- return subscriptions.filter((subscription) => {
285
- return subscription.state === server_subscription_2.SubscriptionState.LATE && subscription.publishingEnabled;
286
- });
287
- }
288
- get hasLateSubscriptions() {
289
- return this.findLateSubscriptions().length > 0;
290
- }
291
- findLateSubscriptionsSortedByAge() {
292
- let late_subscriptions = this.findLateSubscriptions();
293
- late_subscriptions = (0, lodash_1.sortBy)(late_subscriptions, "timeToExpiration");
294
- return late_subscriptions;
295
- }
296
- cancelPendingPublishRequestBeforeChannelChange() {
297
- this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadSecureChannelClosed);
298
- }
299
- onSessionClose() {
300
- this.isSessionClosed = true;
301
- this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadSessionClosed);
302
- }
303
- /**
304
- * @private
305
- */
306
- cancelPendingPublishRequest() {
307
- (0, node_opcua_assert_1.assert)(this.subscriptionCount === 0);
308
- this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadNoSubscription);
309
- }
310
- /**
311
- *
312
- * @param request
313
- * @param callback
314
- * @private
315
- * @internal
316
- */
317
- _on_PublishRequest(request, callback) {
318
- callback = callback || dummy_function;
319
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
320
- // istanbul ignore next
321
- if (!(request instanceof node_opcua_types_1.PublishRequest)) {
322
- throw new Error("Internal error : expecting a Publish Request here");
323
- }
324
- const subscriptionAckResults = this.process_subscriptionAcknowledgements(request.subscriptionAcknowledgements || []);
325
- const currentTime = Date.now();
326
- const publishData = {
327
- callback,
328
- request,
329
- results: subscriptionAckResults,
330
- serverTimeWhenReceived: currentTime
331
- };
332
- if (this.isSessionClosed) {
333
- traceLog("server has received a PublishRequest but session is Closed");
334
- this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadSessionClosed);
335
- }
336
- else if (this.subscriptionCount === 0) {
337
- if (this._closed_subscriptions.length > 0 && this._closed_subscriptions[0].hasPendingNotifications) {
338
- const verif = this._publish_request_queue.length;
339
- // add the publish request to the queue for later processing
340
- this._publish_request_queue.push(publishData);
341
- const processed = this._feed_closed_subscription();
342
- //xx ( may be subscription has expired by themselves) assert(verif === this._publish_request_queue.length);
343
- //xx ( may be subscription has expired by themselves) assert(processed);
344
- return;
345
- }
346
- traceLog("server has received a PublishRequest but has no subscription opened");
347
- this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadNoSubscription);
348
- }
349
- else {
350
- // add the publish request to the queue for later processing
351
- this._publish_request_queue.push(publishData);
352
- (0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount > 0);
353
- debugLog(chalk.bgWhite.red("Adding a PublishRequest to the queue "), this._publish_request_queue.length);
354
- this._feed_closed_subscription();
355
- this._feed_late_subscription();
356
- this._handle_too_many_requests();
357
- }
358
- }
359
- _find_starving_subscription() {
360
- const late_subscriptions = this.findLateSubscriptions();
361
- function compare_subscriptions(s1, s2) {
362
- if (s1.priority === s2.priority) {
363
- return s1.timeToExpiration < s2.timeToExpiration ? 1 : 0;
364
- }
365
- return s1.priority > s2.priority ? 1 : 0;
366
- }
367
- function findLateSubscriptionSortedByPriority() {
368
- if (late_subscriptions.length === 0) {
369
- return null;
370
- }
371
- late_subscriptions.sort(compare_subscriptions);
372
- // istanbul ignore next
373
- if (doDebug) {
374
- debugLog(late_subscriptions
375
- .map((s) => "[ id = " +
376
- s.id +
377
- " prio=" +
378
- s.priority +
379
- " t=" +
380
- s.timeToExpiration +
381
- " ka=" +
382
- s.timeToKeepAlive +
383
- " m?=" +
384
- s.hasUncollectedMonitoredItemNotifications +
385
- "]")
386
- .join(" \n"));
387
- }
388
- return late_subscriptions[late_subscriptions.length - 1];
389
- }
390
- if (this._closed_subscriptions) {
391
- /** */
392
- }
393
- const starving_subscription = /* this.findSubscriptionWaitingForFirstPublish() || */ findLateSubscriptionSortedByPriority();
394
- return starving_subscription;
395
- }
396
- _feed_late_subscription() {
397
- setImmediate(() => {
398
- if (!this.pendingPublishRequestCount) {
399
- return;
400
- }
401
- const starving_subscription = this._find_starving_subscription();
402
- if (starving_subscription) {
403
- debugLog(chalk.bgWhite.red("feeding most late subscription subscriptionId = "), starving_subscription.id);
404
- starving_subscription.process_subscription();
405
- }
406
- });
407
- }
408
- _feed_closed_subscription() {
409
- if (!this.pendingPublishRequestCount) {
410
- return false;
411
- }
412
- if (this._closed_subscriptions.length === 0) {
413
- debugLog("ServerSidePublishEngine#_feed_closed_subscription -> nothing to do");
414
- return false;
415
- }
416
- // process closed subscription
417
- const closed_subscription = this._closed_subscriptions[0];
418
- (0, node_opcua_assert_1.assert)(closed_subscription.hasPendingNotifications);
419
- debugLog("ServerSidePublishEngine#_feed_closed_subscription for closed_subscription ", closed_subscription.id);
420
- closed_subscription === null || closed_subscription === void 0 ? void 0 : closed_subscription._publish_pending_notifications();
421
- if (!(closed_subscription === null || closed_subscription === void 0 ? void 0 : closed_subscription.hasPendingNotifications)) {
422
- closed_subscription.dispose();
423
- this._closed_subscriptions.shift();
424
- }
425
- return true;
426
- }
427
- _send_error_for_request(publishData, statusCode) {
428
- _assertValidPublishData(publishData);
429
- const publishResponse = new node_opcua_types_1.PublishResponse({
430
- responseHeader: { serviceResult: statusCode }
431
- });
432
- this._send_response_for_request(publishData, publishResponse);
433
- }
434
- _cancelPendingPublishRequest(statusCode) {
435
- if (this._publish_request_queue) {
436
- debugLog(chalk.red("Cancelling pending PublishRequest with statusCode "), statusCode.toString(), " length =", this._publish_request_queue.length);
437
- }
438
- else {
439
- debugLog(chalk.red("No pending PublishRequest to cancel"));
440
- }
441
- for (const publishData of this._publish_request_queue) {
442
- this._send_error_for_request(publishData, statusCode);
443
- }
444
- this._publish_request_queue = [];
445
- }
446
- _handle_too_many_requests() {
447
- if (this.pendingPublishRequestCount > this.maxPublishRequestInQueue) {
448
- traceLog("server has received too many PublishRequest", this.pendingPublishRequestCount, "/", this.maxPublishRequestInQueue);
449
- (0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount === this.maxPublishRequestInQueue + 1);
450
- // When a Server receives a new Publish request that exceeds its limit it shall de-queue the oldest Publish
451
- // request and return a response with the result set to Bad_TooManyPublishRequests.
452
- // dequeue oldest request
453
- const publishData = this._publish_request_queue.shift();
454
- this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadTooManyPublishRequests);
455
- }
456
- }
457
- /**
458
- * call by a subscription when no notification message is available after the keep alive delay has
459
- * expired.
460
- *
461
- * @method send_keep_alive_response
462
- * @param subscriptionId
463
- * @param future_sequence_number
464
- * @return true if a publish response has been sent
465
- */
466
- send_keep_alive_response(subscriptionId, future_sequence_number) {
467
- // this keep-alive Message informs the Client that the Subscription is still active.
468
- // Each keep-alive Message is a response to a Publish request in which the notification Message
469
- // parameter does not contain any Notifications and that contains the sequence number of the next
470
- // Notification Message that is to be sent.
471
- const subscription = this.getSubscriptionById(subscriptionId);
472
- /* istanbul ignore next */
473
- if (!subscription) {
474
- traceLog("send_keep_alive_response => invalid subscriptionId = ", subscriptionId);
475
- return false;
476
- }
477
- // let check if we have available PublishRequest to send the keep alive
478
- if (this.pendingPublishRequestCount === 0 || subscription.hasPendingNotifications) {
479
- // we cannot send the keep alive PublishResponse
480
- traceLog("send_keep_alive_response => cannot send keep-alive (no PublishRequest left) subscriptionId = ", subscriptionId);
481
- return false;
482
- }
483
- debugLog(`Sending keep alive response for subscription id ${subscription.id} ${subscription.publishingInterval} ${subscription.maxKeepAliveCount}`);
484
- this._send_response(subscription, new node_opcua_types_1.PublishResponse({
485
- availableSequenceNumbers: subscription.getAvailableSequenceNumbers(),
486
- moreNotifications: false,
487
- notificationMessage: {
488
- sequenceNumber: future_sequence_number
489
- },
490
- subscriptionId
491
- }));
492
- return true;
493
- }
494
- _send_response(subscription, response) {
495
- (0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount > 0);
496
- (0, node_opcua_assert_1.assert)(response.subscriptionId !== 0xffffff);
497
- const publishData = this._publish_request_queue.shift();
498
- this._send_response_for_request(publishData, response);
499
- }
500
- _on_tick() {
501
- this._cancelTimeoutRequests();
502
- }
503
- _cancelTimeoutRequests() {
504
- if (this._publish_request_queue.length === 0) {
505
- return;
506
- }
507
- // filter out timeout requests
508
- const parts = (0, lodash_1.partition)(this._publish_request_queue, timeout_filter);
509
- this._publish_request_queue = parts[1]; // still valid
510
- const invalid_published_request = parts[0];
511
- for (const publishData of invalid_published_request) {
512
- if (doDebug) {
513
- debugLog(chalk.cyan(" CANCELING TIMEOUT PUBLISH REQUEST "));
514
- }
515
- this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadTimeout);
516
- }
517
- }
518
- _send_response_for_request(publishData, response) {
519
- if (doDebug) {
520
- debugLog("_send_response_for_request ", response.toString());
521
- }
522
- _assertValidPublishData(publishData);
523
- // xx assert(response.responseHeader.requestHandle !== 0,"expecting a valid requestHandle");
524
- response.results = publishData.results;
525
- response.responseHeader.requestHandle = publishData.request.requestHeader.requestHandle;
526
- publishData.callback(publishData.request, response);
527
- }
528
- }
529
- exports.ServerSidePublishEngine = ServerSidePublishEngine;
530
- 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
+ destPublishEngine.add_subscription(srcPublishEngine.detach_subscription(subscription));
126
+ subscription.resetLifeTimeCounter();
127
+ if (sendInitialValues) {
128
+ /* A Boolean parameter with the following values:
129
+ TRUE the first Publish response(s) after the TransferSubscriptions call
130
+ shall contain the current values of all Monitored Items in the
131
+ Subscription where the Monitoring Mode is set to Reporting.
132
+ If a value is queued for a data MonitoredItem, the next value in
133
+ the queue is sent in the Publish response. If no value is queued
134
+ for a data MonitoredItem, the last value sent is repeated in the
135
+ Publish response.
136
+ FALSE the first Publish response after the TransferSubscriptions call
137
+ shall contain only the value changes since the last Publish
138
+ response was sent.
139
+ This parameter only applies to MonitoredItems used for monitoring Attribute
140
+ changes
141
+ */
142
+ debugLog("Resending initial values");
143
+ yield subscription.resendInitialValues();
144
+ }
145
+ (0, node_opcua_assert_1.assert)(destPublishEngine.getSubscriptionById(subscription.id));
146
+ (0, node_opcua_assert_1.assert)(!srcPublishEngine.getSubscriptionById(subscription.id));
147
+ });
148
+ }
149
+ toString() {
150
+ let str = "";
151
+ str += `maxPublishRequestInQueue ${this.maxPublishRequestInQueue}\n`;
152
+ str += `subscriptions ${Object.keys(this._subscriptions).join()}\n`;
153
+ str += `closed subscriptions ${this._closed_subscriptions.map((s) => s.id).join()}\n`;
154
+ return str;
155
+ }
156
+ dispose() {
157
+ debugLog("ServerSidePublishEngine#dispose");
158
+ (0, node_opcua_assert_1.assert)(Object.keys(this._subscriptions).length === 0, "self._subscriptions count!=0");
159
+ this._subscriptions = {};
160
+ (0, node_opcua_assert_1.assert)(this._closed_subscriptions.length === 0, "self._closed_subscriptions count!=0");
161
+ this._closed_subscriptions = [];
162
+ ServerSidePublishEngine.registry.unregister(this);
163
+ }
164
+ process_subscriptionAcknowledgements(subscriptionAcknowledgements) {
165
+ // process acknowledgements
166
+ subscriptionAcknowledgements = subscriptionAcknowledgements || [];
167
+ debugLog("process_subscriptionAcknowledgements = ", subscriptionAcknowledgements);
168
+ const results = subscriptionAcknowledgements.map((subscriptionAcknowledgement) => {
169
+ const subscription = this.getSubscriptionById(subscriptionAcknowledgement.subscriptionId);
170
+ if (!subscription) {
171
+ // // try to find the session
172
+ // const transferredSubscription = this._transferred_subscriptions.find(
173
+ // (s) => s.subscriptionId === subscriptionAcknowledgement.subscriptionId
174
+ // );
175
+ // if (transferredSubscription) {
176
+ // debugLog("Subscription acknowledgeNotification done in transferred subscription ");
177
+ // return transferredSubscription.acknowledgeNotification(subscriptionAcknowledgement.sequenceNumber);
178
+ // }
179
+ return node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid;
180
+ }
181
+ return subscription.acknowledgeNotification(subscriptionAcknowledgement.sequenceNumber);
182
+ });
183
+ return results;
184
+ }
185
+ /**
186
+ * get a array of subscription handled by the publish engine.
187
+ */
188
+ get subscriptions() {
189
+ return Object.values(this._subscriptions);
190
+ }
191
+ /**
192
+ */
193
+ add_subscription(subscription) {
194
+ (0, node_opcua_assert_1.assert)(subscription instanceof server_subscription_1.Subscription);
195
+ (0, node_opcua_assert_1.assert)(isFinite(subscription.id));
196
+ subscription.publishEngine = (subscription.publishEngine || this);
197
+ (0, node_opcua_assert_1.assert)(subscription.publishEngine === this);
198
+ (0, node_opcua_assert_1.assert)(!this._subscriptions[subscription.id]);
199
+ debugLog("ServerSidePublishEngine#add_subscription - adding subscription with Id:", subscription.id);
200
+ this._subscriptions[subscription.id] = subscription;
201
+ // xx subscription._flushSentNotifications();
202
+ return subscription;
203
+ }
204
+ detach_subscription(subscription) {
205
+ (0, node_opcua_assert_1.assert)(subscription instanceof server_subscription_1.Subscription);
206
+ (0, node_opcua_assert_1.assert)(isFinite(subscription.id));
207
+ (0, node_opcua_assert_1.assert)(subscription.publishEngine === this);
208
+ (0, node_opcua_assert_1.assert)(this._subscriptions[subscription.id] === subscription);
209
+ delete this._subscriptions[subscription.id];
210
+ subscription.publishEngine = null;
211
+ debugLog("ServerSidePublishEngine#detach_subscription detaching subscription with Id:", subscription.id);
212
+ return subscription;
213
+ }
214
+ /**
215
+ */
216
+ shutdown() {
217
+ if (this.subscriptionCount !== 0) {
218
+ debugLog(chalk.red("Shutting down pending subscription"));
219
+ this.subscriptions.map((subscription) => subscription.terminate());
220
+ }
221
+ (0, node_opcua_assert_1.assert)(this.subscriptionCount === 0, "subscription shall be removed first before you can shutdown a publish engine");
222
+ debugLog("ServerSidePublishEngine#shutdown");
223
+ // purge _publish_request_queue
224
+ this._publish_request_queue = [];
225
+ // purge self._closed_subscriptions
226
+ this._closed_subscriptions.map((subscription) => subscription.dispose());
227
+ this._closed_subscriptions = [];
228
+ }
229
+ /**
230
+ * number of pending PublishRequest available in queue
231
+ */
232
+ get pendingPublishRequestCount() {
233
+ return this._publish_request_queue.length;
234
+ }
235
+ /**
236
+ * number of subscriptions
237
+ */
238
+ get subscriptionCount() {
239
+ return Object.keys(this._subscriptions).length;
240
+ }
241
+ get pendingClosedSubscriptionCount() {
242
+ return this._closed_subscriptions.length;
243
+ }
244
+ get currentMonitoredItemCount() {
245
+ const subscriptions = Object.values(this._subscriptions);
246
+ const result = subscriptions.reduce((cumul, subscription) => {
247
+ return cumul + subscription.monitoredItemCount;
248
+ }, 0);
249
+ (0, node_opcua_assert_1.assert)(isFinite(result));
250
+ return result;
251
+ }
252
+ _purge_dangling_subscription(subscriptionId) {
253
+ this._closed_subscriptions = this._closed_subscriptions.filter((s) => s.id !== subscriptionId);
254
+ }
255
+ on_close_subscription(subscription) {
256
+ debugLog("ServerSidePublishEngine#on_close_subscription", subscription.id);
257
+ if (subscription.hasPendingNotifications) {
258
+ debugLog("ServerSidePublishEngine#on_close_subscription storing subscription", subscription.id, " to _closed_subscriptions because it has pending notification");
259
+ this._closed_subscriptions.push(subscription);
260
+ }
261
+ else {
262
+ debugLog("ServerSidePublishEngine#on_close_subscription disposing subscription", subscription.id);
263
+ // subscription is no longer needed
264
+ subscription.dispose();
265
+ }
266
+ delete this._subscriptions[subscription.id];
267
+ while (this._feed_closed_subscription()) {
268
+ /* keep looping */
269
+ }
270
+ if (this.subscriptionCount === 0 && this._closed_subscriptions.length === 0) {
271
+ this.cancelPendingPublishRequest();
272
+ }
273
+ }
274
+ /**
275
+ * retrieve a subscription by id.
276
+ * @param subscriptionId
277
+ * @return Subscription
278
+ */
279
+ getSubscriptionById(subscriptionId) {
280
+ return this._subscriptions[subscriptionId.toString()];
281
+ }
282
+ findLateSubscriptions() {
283
+ const subscriptions = Object.values(this._subscriptions);
284
+ return subscriptions.filter((subscription) => {
285
+ return subscription.state === server_subscription_2.SubscriptionState.LATE && subscription.publishingEnabled;
286
+ });
287
+ }
288
+ get hasLateSubscriptions() {
289
+ return this.findLateSubscriptions().length > 0;
290
+ }
291
+ findLateSubscriptionsSortedByAge() {
292
+ let late_subscriptions = this.findLateSubscriptions();
293
+ late_subscriptions = (0, lodash_1.sortBy)(late_subscriptions, "timeToExpiration");
294
+ return late_subscriptions;
295
+ }
296
+ cancelPendingPublishRequestBeforeChannelChange() {
297
+ this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadSecureChannelClosed);
298
+ }
299
+ onSessionClose() {
300
+ this.isSessionClosed = true;
301
+ this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadSessionClosed);
302
+ }
303
+ /**
304
+ * @private
305
+ */
306
+ cancelPendingPublishRequest() {
307
+ (0, node_opcua_assert_1.assert)(this.subscriptionCount === 0);
308
+ this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadNoSubscription);
309
+ }
310
+ /**
311
+ *
312
+ * @param request
313
+ * @param callback
314
+ * @private
315
+ * @internal
316
+ */
317
+ _on_PublishRequest(request, callback) {
318
+ callback = callback || dummy_function;
319
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
320
+ // istanbul ignore next
321
+ if (!(request instanceof node_opcua_types_1.PublishRequest)) {
322
+ throw new Error("Internal error : expecting a Publish Request here");
323
+ }
324
+ const subscriptionAckResults = this.process_subscriptionAcknowledgements(request.subscriptionAcknowledgements || []);
325
+ const currentTime = Date.now();
326
+ const publishData = {
327
+ callback,
328
+ request,
329
+ results: subscriptionAckResults,
330
+ serverTimeWhenReceived: currentTime
331
+ };
332
+ if (this.isSessionClosed) {
333
+ traceLog("server has received a PublishRequest but session is Closed");
334
+ this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadSessionClosed);
335
+ }
336
+ else if (this.subscriptionCount === 0) {
337
+ if (this._closed_subscriptions.length > 0 && this._closed_subscriptions[0].hasPendingNotifications) {
338
+ const verif = this._publish_request_queue.length;
339
+ // add the publish request to the queue for later processing
340
+ this._publish_request_queue.push(publishData);
341
+ const processed = this._feed_closed_subscription();
342
+ //xx ( may be subscription has expired by themselves) assert(verif === this._publish_request_queue.length);
343
+ //xx ( may be subscription has expired by themselves) assert(processed);
344
+ return;
345
+ }
346
+ traceLog("server has received a PublishRequest but has no subscription opened");
347
+ this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadNoSubscription);
348
+ }
349
+ else {
350
+ // add the publish request to the queue for later processing
351
+ this._publish_request_queue.push(publishData);
352
+ (0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount > 0);
353
+ debugLog(chalk.bgWhite.red("Adding a PublishRequest to the queue "), this._publish_request_queue.length);
354
+ this._feed_closed_subscription();
355
+ this._feed_late_subscription();
356
+ this._handle_too_many_requests();
357
+ }
358
+ }
359
+ _find_starving_subscription() {
360
+ const late_subscriptions = this.findLateSubscriptions();
361
+ function compare_subscriptions(s1, s2) {
362
+ if (s1.priority === s2.priority) {
363
+ return s1.timeToExpiration < s2.timeToExpiration ? 1 : 0;
364
+ }
365
+ return s1.priority > s2.priority ? 1 : 0;
366
+ }
367
+ function findLateSubscriptionSortedByPriority() {
368
+ if (late_subscriptions.length === 0) {
369
+ return null;
370
+ }
371
+ late_subscriptions.sort(compare_subscriptions);
372
+ // istanbul ignore next
373
+ if (doDebug) {
374
+ debugLog(late_subscriptions
375
+ .map((s) => "[ id = " +
376
+ s.id +
377
+ " prio=" +
378
+ s.priority +
379
+ " t=" +
380
+ s.timeToExpiration +
381
+ " ka=" +
382
+ s.timeToKeepAlive +
383
+ " m?=" +
384
+ s.hasUncollectedMonitoredItemNotifications +
385
+ "]")
386
+ .join(" \n"));
387
+ }
388
+ return late_subscriptions[late_subscriptions.length - 1];
389
+ }
390
+ if (this._closed_subscriptions) {
391
+ /** */
392
+ }
393
+ const starving_subscription = /* this.findSubscriptionWaitingForFirstPublish() || */ findLateSubscriptionSortedByPriority();
394
+ return starving_subscription;
395
+ }
396
+ _feed_late_subscription() {
397
+ setImmediate(() => {
398
+ if (!this.pendingPublishRequestCount) {
399
+ return;
400
+ }
401
+ const starving_subscription = this._find_starving_subscription();
402
+ if (starving_subscription) {
403
+ debugLog(chalk.bgWhite.red("feeding most late subscription subscriptionId = "), starving_subscription.id);
404
+ starving_subscription.process_subscription();
405
+ }
406
+ });
407
+ }
408
+ _feed_closed_subscription() {
409
+ if (!this.pendingPublishRequestCount) {
410
+ return false;
411
+ }
412
+ if (this._closed_subscriptions.length === 0) {
413
+ debugLog("ServerSidePublishEngine#_feed_closed_subscription -> nothing to do");
414
+ return false;
415
+ }
416
+ // process closed subscription
417
+ const closed_subscription = this._closed_subscriptions[0];
418
+ (0, node_opcua_assert_1.assert)(closed_subscription.hasPendingNotifications);
419
+ debugLog("ServerSidePublishEngine#_feed_closed_subscription for closed_subscription ", closed_subscription.id);
420
+ closed_subscription === null || closed_subscription === void 0 ? void 0 : closed_subscription._publish_pending_notifications();
421
+ if (!(closed_subscription === null || closed_subscription === void 0 ? void 0 : closed_subscription.hasPendingNotifications)) {
422
+ closed_subscription.dispose();
423
+ this._closed_subscriptions.shift();
424
+ }
425
+ return true;
426
+ }
427
+ _send_error_for_request(publishData, statusCode) {
428
+ _assertValidPublishData(publishData);
429
+ const publishResponse = new node_opcua_types_1.PublishResponse({
430
+ responseHeader: { serviceResult: statusCode }
431
+ });
432
+ this._send_response_for_request(publishData, publishResponse);
433
+ }
434
+ _cancelPendingPublishRequest(statusCode) {
435
+ if (this._publish_request_queue) {
436
+ debugLog(chalk.red("Cancelling pending PublishRequest with statusCode "), statusCode.toString(), " length =", this._publish_request_queue.length);
437
+ }
438
+ else {
439
+ debugLog(chalk.red("No pending PublishRequest to cancel"));
440
+ }
441
+ for (const publishData of this._publish_request_queue) {
442
+ this._send_error_for_request(publishData, statusCode);
443
+ }
444
+ this._publish_request_queue = [];
445
+ }
446
+ _handle_too_many_requests() {
447
+ if (this.pendingPublishRequestCount > this.maxPublishRequestInQueue) {
448
+ traceLog("server has received too many PublishRequest", this.pendingPublishRequestCount, "/", this.maxPublishRequestInQueue);
449
+ (0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount === this.maxPublishRequestInQueue + 1);
450
+ // When a Server receives a new Publish request that exceeds its limit it shall de-queue the oldest Publish
451
+ // request and return a response with the result set to Bad_TooManyPublishRequests.
452
+ // dequeue oldest request
453
+ const publishData = this._publish_request_queue.shift();
454
+ this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadTooManyPublishRequests);
455
+ }
456
+ }
457
+ /**
458
+ * call by a subscription when no notification message is available after the keep alive delay has
459
+ * expired.
460
+ *
461
+ * @method send_keep_alive_response
462
+ * @param subscriptionId
463
+ * @param future_sequence_number
464
+ * @return true if a publish response has been sent
465
+ */
466
+ send_keep_alive_response(subscriptionId, future_sequence_number) {
467
+ // this keep-alive Message informs the Client that the Subscription is still active.
468
+ // Each keep-alive Message is a response to a Publish request in which the notification Message
469
+ // parameter does not contain any Notifications and that contains the sequence number of the next
470
+ // Notification Message that is to be sent.
471
+ const subscription = this.getSubscriptionById(subscriptionId);
472
+ /* istanbul ignore next */
473
+ if (!subscription) {
474
+ traceLog("send_keep_alive_response => invalid subscriptionId = ", subscriptionId);
475
+ return false;
476
+ }
477
+ // let check if we have available PublishRequest to send the keep alive
478
+ if (this.pendingPublishRequestCount === 0 || subscription.hasPendingNotifications) {
479
+ // we cannot send the keep alive PublishResponse
480
+ traceLog("send_keep_alive_response => cannot send keep-alive (no PublishRequest left) subscriptionId = ", subscriptionId);
481
+ return false;
482
+ }
483
+ debugLog(`Sending keep alive response for subscription id ${subscription.id} ${subscription.publishingInterval} ${subscription.maxKeepAliveCount}`);
484
+ this._send_response(subscription, new node_opcua_types_1.PublishResponse({
485
+ availableSequenceNumbers: subscription.getAvailableSequenceNumbers(),
486
+ moreNotifications: false,
487
+ notificationMessage: {
488
+ sequenceNumber: future_sequence_number
489
+ },
490
+ subscriptionId
491
+ }));
492
+ return true;
493
+ }
494
+ _send_response(subscription, response) {
495
+ (0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount > 0);
496
+ (0, node_opcua_assert_1.assert)(response.subscriptionId !== 0xffffff);
497
+ const publishData = this._publish_request_queue.shift();
498
+ this._send_response_for_request(publishData, response);
499
+ }
500
+ _on_tick() {
501
+ this._cancelTimeoutRequests();
502
+ }
503
+ _cancelTimeoutRequests() {
504
+ if (this._publish_request_queue.length === 0) {
505
+ return;
506
+ }
507
+ // filter out timeout requests
508
+ const parts = (0, lodash_1.partition)(this._publish_request_queue, timeout_filter);
509
+ this._publish_request_queue = parts[1]; // still valid
510
+ const invalid_published_request = parts[0];
511
+ for (const publishData of invalid_published_request) {
512
+ if (doDebug) {
513
+ debugLog(chalk.cyan(" CANCELING TIMEOUT PUBLISH REQUEST "));
514
+ }
515
+ this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadTimeout);
516
+ }
517
+ }
518
+ _send_response_for_request(publishData, response) {
519
+ if (doDebug) {
520
+ debugLog("_send_response_for_request ", response.toString());
521
+ }
522
+ _assertValidPublishData(publishData);
523
+ // xx assert(response.responseHeader.requestHandle !== 0,"expecting a valid requestHandle");
524
+ response.results = publishData.results;
525
+ response.responseHeader.requestHandle = publishData.request.requestHeader.requestHandle;
526
+ publishData.callback(publishData.request, response);
527
+ }
528
+ }
529
+ exports.ServerSidePublishEngine = ServerSidePublishEngine;
530
+ ServerSidePublishEngine.registry = new node_opcua_object_registry_1.ObjectRegistry();
531
531
  //# sourceMappingURL=server_publish_engine.js.map