node-opcua-server
Version:
pure nodejs OPCUA SDK - module server
539 lines • 27.5 kB
JavaScript
"use strict";
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _ServerSidePublishEngine_instances, _ServerSidePublishEngine__find_starving_subscription, _ServerSidePublishEngine__feed_late_subscription, _ServerSidePublishEngine__feed_closed_subscription, _ServerSidePublishEngine__handle_too_many_requests;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServerSidePublishEngine = void 0;
/**
* @module node-opcua-server
*/
// tslint:disable:no-console
const events_1 = require("events");
const chalk_1 = __importDefault(require("chalk"));
const lodash_1 = require("lodash");
const node_opcua_assert_1 = require("node-opcua-assert");
const node_opcua_debug_1 = require("node-opcua-debug");
const node_opcua_object_registry_1 = require("node-opcua-object-registry");
const node_opcua_status_code_1 = require("node-opcua-status-code");
const node_opcua_types_1 = require("node-opcua-types");
const server_subscription_1 = require("./server_subscription");
const server_subscription_2 = require("./server_subscription");
const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
function traceLog(...args) {
if (!doDebug) {
return;
}
const a = args.map((x) => x);
a.unshift(chalk_1.default.yellow(" TRACE "));
debugLog(...a);
}
function _assertValidPublishData(publishData) {
(0, node_opcua_assert_1.assert)(publishData.request instanceof node_opcua_types_1.PublishRequest);
(0, node_opcua_assert_1.assert)(typeof publishData.serverTimeWhenReceived === "number");
(0, node_opcua_assert_1.assert)(Array.isArray(publishData.results));
(0, node_opcua_assert_1.assert)(typeof publishData.callback === "function");
}
function dummy_function() {
/* empty */
}
function addDate(date, delta) {
return new Date(date.getTime() + delta);
}
function timeout_filter(publishData) {
const request = publishData.request;
const results = publishData.results;
if (!request.requestHeader.timeoutHint) {
// no limits
return false;
}
const serverTimeWhenReceived = publishData.serverTimeWhenReceived;
// remark : do not use request.requestHeader.timestamp! here as this is a client date and server and client clocks might differ
const expected_timeout_time = addDate(new Date(serverTimeWhenReceived), request.requestHeader.timeoutHint);
return expected_timeout_time.getTime() < Date.now();
}
/***
* a Publish Engine for a given session
*/
class ServerSidePublishEngine extends events_1.EventEmitter {
/**
* @private
*/
static transferSubscriptionsToOrphan(srcPublishEngine, destPublishEngine) {
debugLog(chalk_1.default.yellow("ServerSidePublishEngine#transferSubscriptionsToOrphan! " + "start transferring long live subscriptions to orphan"));
for (const subscription of Object.values(srcPublishEngine._subscriptions)) {
(0, node_opcua_assert_1.assert)(subscription.publishEngine === srcPublishEngine);
if (subscription.$session) {
subscription.$session._unexposeSubscriptionDiagnostics(subscription);
}
else {
console.warn("Warning: subscription", subscription.id, " has no session attached!!!");
}
ServerSidePublishEngine.transferSubscription(subscription, destPublishEngine, false);
}
(0, node_opcua_assert_1.assert)(srcPublishEngine.subscriptionCount === 0);
debugLog(chalk_1.default.yellow("ServerSidePublishEngine#transferSubscriptionsToOrphan! " + "end transferring long lived subscriptions to orphan"));
}
/**
* @param subscription
* @param destPublishEngine
* @param sendInitialValues true if initial values should be sent
* @private
*/
static async transferSubscription(subscription, destPublishEngine, sendInitialValues) {
const srcPublishEngine = subscription.publishEngine;
(0, node_opcua_assert_1.assert)(!destPublishEngine.getSubscriptionById(subscription.id));
(0, node_opcua_assert_1.assert)(srcPublishEngine.getSubscriptionById(subscription.id));
// remove pending StatusChangeNotification on the same session that may exist already
destPublishEngine._purge_dangling_subscription(subscription.id);
debugLog(chalk_1.default.cyan("ServerSidePublishEngine.transferSubscription live subscriptionId ="), subscription.subscriptionId);
// xx const internalNotification = subscription._flushSentNotifications();
debugLog(chalk_1.default.cyan("ServerSidePublishEngine.transferSubscription with = "), subscription.getAvailableSequenceNumbers());
// If the Server transfers the Subscription to the new Session, the Server shall issue a
// StatusChangeNotification notificationMessage with the status code Good_SubscriptionTransferred
// to the old Session.
subscription.notifyTransfer();
const tmp = srcPublishEngine.detach_subscription(subscription);
destPublishEngine.add_subscription(tmp);
subscription.resetLifeTimeCounter();
if (sendInitialValues) {
/* A Boolean parameter with the following values:
TRUE the first Publish response(s) after the TransferSubscriptions call
shall contain the current values of all Monitored Items in the
Subscription where the Monitoring Mode is set to Reporting.
If a value is queued for a data MonitoredItem, the next value in
the queue is sent in the Publish response. If no value is queued
for a data MonitoredItem, the last value sent is repeated in the
Publish response.
FALSE the first Publish response after the TransferSubscriptions call
shall contain only the value changes since the last Publish
response was sent.
This parameter only applies to MonitoredItems used for monitoring Attribute
changes
*/
debugLog("Resending initial values");
await subscription.resendInitialValues();
}
(0, node_opcua_assert_1.assert)(destPublishEngine.getSubscriptionById(subscription.id));
(0, node_opcua_assert_1.assert)(!srcPublishEngine.getSubscriptionById(subscription.id));
return subscription;
}
constructor(options) {
super();
_ServerSidePublishEngine_instances.add(this);
this.maxPublishRequestInQueue = 0;
this.isSessionClosed = false;
this._publish_request_queue = [];
this._closed_subscriptions = [];
options = options || {};
ServerSidePublishEngine.registry.register(this);
// a queue of pending publish request send by the client
// waiting to be used by the server to send notification
this._publish_request_queue = []; // { request :/*PublishRequest*/{},
this._subscriptions = {};
// _closed_subscriptions contains a collection of Subscription that
// have expired but that still need to send some pending notification
// to the client.
// Once publish requests will be received from the client
// the notifications of those subscriptions will be processed so that
// they can be properly disposed.
this._closed_subscriptions = [];
this.maxPublishRequestInQueue = options.maxPublishRequestInQueue || 100;
this.isSessionClosed = false;
}
toString() {
let str = "";
str += `maxPublishRequestInQueue ${this.maxPublishRequestInQueue}\n`;
str += `subscriptions ${Object.keys(this._subscriptions).join()}\n`;
str += `closed subscriptions ${this._closed_subscriptions.map((s) => s.id).join()}\n`;
return str;
}
dispose() {
debugLog("ServerSidePublishEngine#dispose");
(0, node_opcua_assert_1.assert)(Object.keys(this._subscriptions).length === 0, "self._subscriptions count!=0");
this._subscriptions = {};
(0, node_opcua_assert_1.assert)(this._closed_subscriptions.length === 0, "self._closed_subscriptions count!=0");
this._closed_subscriptions = [];
ServerSidePublishEngine.registry.unregister(this);
}
process_subscriptionAcknowledgements(subscriptionAcknowledgements) {
// process acknowledgements
subscriptionAcknowledgements = subscriptionAcknowledgements || [];
debugLog("process_subscriptionAcknowledgements = ", subscriptionAcknowledgements);
const results = subscriptionAcknowledgements.map((subscriptionAcknowledgement) => {
const subscription = this.getSubscriptionById(subscriptionAcknowledgement.subscriptionId);
if (!subscription) {
// // try to find the session
// const transferredSubscription = this._transferred_subscriptions.find(
// (s) => s.subscriptionId === subscriptionAcknowledgement.subscriptionId
// );
// if (transferredSubscription) {
// debugLog("Subscription acknowledgeNotification done in transferred subscription ");
// return transferredSubscription.acknowledgeNotification(subscriptionAcknowledgement.sequenceNumber);
// }
return node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid;
}
return subscription.acknowledgeNotification(subscriptionAcknowledgement.sequenceNumber);
});
return results;
}
/**
* get a array of subscription handled by the publish engine.
*/
get subscriptions() {
return Object.values(this._subscriptions);
}
/**
*/
add_subscription(subscription) {
(0, node_opcua_assert_1.assert)(subscription instanceof server_subscription_1.Subscription);
(0, node_opcua_assert_1.assert)(isFinite(subscription.id));
subscription.publishEngine = (subscription.publishEngine || this);
(0, node_opcua_assert_1.assert)(subscription.publishEngine === this);
(0, node_opcua_assert_1.assert)(!this._subscriptions[subscription.id]);
debugLog("ServerSidePublishEngine#add_subscription - adding subscription with Id:", subscription.id);
this._subscriptions[subscription.id] = subscription;
// xx subscription._flushSentNotifications();
return subscription;
}
detach_subscription(subscription) {
(0, node_opcua_assert_1.assert)(subscription instanceof server_subscription_1.Subscription);
(0, node_opcua_assert_1.assert)(isFinite(subscription.id));
(0, node_opcua_assert_1.assert)(subscription.publishEngine === this);
(0, node_opcua_assert_1.assert)(this._subscriptions[subscription.id] === subscription);
delete this._subscriptions[subscription.id];
subscription.publishEngine = null;
debugLog("ServerSidePublishEngine#detach_subscription detaching subscription with Id:", subscription.id);
return subscription;
}
/**
*/
shutdown() {
if (this.subscriptionCount !== 0) {
debugLog(chalk_1.default.red("Shutting down pending subscription"));
this.subscriptions.map((subscription) => subscription.terminate());
}
(0, node_opcua_assert_1.assert)(this.subscriptionCount === 0, "subscription shall be removed first before you can shutdown a publish engine");
debugLog("ServerSidePublishEngine#shutdown");
// purge _publish_request_queue
this._publish_request_queue = [];
// purge self._closed_subscriptions
this._closed_subscriptions.map((subscription) => subscription.dispose());
this._closed_subscriptions = [];
}
/**
* number of pending PublishRequest available in queue
*/
get pendingPublishRequestCount() {
return this._publish_request_queue.length;
}
/**
* number of subscriptions
*/
get subscriptionCount() {
return Object.keys(this._subscriptions).length;
}
get pendingClosedSubscriptionCount() {
return this._closed_subscriptions.length;
}
get currentMonitoredItemCount() {
const subscriptions = Object.values(this._subscriptions);
const result = subscriptions.reduce((sum, subscription) => {
return sum + subscription.monitoredItemCount;
}, 0);
(0, node_opcua_assert_1.assert)(isFinite(result));
return result;
}
_purge_dangling_subscription(subscriptionId) {
this._closed_subscriptions = this._closed_subscriptions.filter((s) => s.id !== subscriptionId);
}
on_close_subscription(subscription) {
doDebug && debugLog("ServerSidePublishEngine#on_close_subscription", subscription.id);
if (subscription.hasPendingNotifications) {
doDebug &&
debugLog("ServerSidePublishEngine#on_close_subscription storing subscription", subscription.id, " to _closed_subscriptions because it has pending notification");
this._closed_subscriptions.push(subscription);
}
else {
doDebug && debugLog("ServerSidePublishEngine#on_close_subscription disposing subscription", subscription.id);
// subscription is no longer needed
subscription.dispose();
}
delete this._subscriptions[subscription.id];
while (__classPrivateFieldGet(this, _ServerSidePublishEngine_instances, "m", _ServerSidePublishEngine__feed_closed_subscription).call(this)) {
/* keep looping */
}
if (this.subscriptionCount === 0 && this._closed_subscriptions.length === 0) {
this.cancelPendingPublishRequest();
}
}
/**
* retrieve a subscription by id.
* @param subscriptionId
* @return Subscription
*/
getSubscriptionById(subscriptionId) {
return this._subscriptions[subscriptionId.toString()];
}
findLateSubscriptions() {
const subscriptions = Object.values(this._subscriptions);
return subscriptions.filter((subscription) => {
return (subscription.state === server_subscription_2.SubscriptionState.LATE || !subscription.messageSent) && subscription.publishingEnabled;
});
}
get hasLateSubscriptions() {
return this.findLateSubscriptions().length > 0;
}
findLateSubscriptionsSortedByAge() {
let late_subscriptions = this.findLateSubscriptions();
late_subscriptions = (0, lodash_1.sortBy)(late_subscriptions, "timeToExpiration");
return late_subscriptions;
}
cancelPendingPublishRequestBeforeChannelChange() {
this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadSecureChannelClosed);
}
onSessionClose() {
this.isSessionClosed = true;
this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadSessionClosed);
}
/**
* @private
*/
cancelPendingPublishRequest() {
(0, node_opcua_assert_1.assert)(this.subscriptionCount === 0);
this._cancelPendingPublishRequest(node_opcua_status_code_1.StatusCodes.BadNoSubscription);
}
/**
*
* @param request
* @param callback
* @private
* @internal
*/
_on_PublishRequest(request, callback) {
callback = callback || dummy_function;
(0, node_opcua_assert_1.assert)(typeof callback === "function");
// istanbul ignore next
if (!(request instanceof node_opcua_types_1.PublishRequest)) {
throw new Error("Internal error : expecting a Publish Request here");
}
const subscriptionAckResults = this.process_subscriptionAcknowledgements(request.subscriptionAcknowledgements || []);
const currentTime = Date.now();
const publishData = {
callback,
request,
results: subscriptionAckResults,
serverTimeWhenReceived: currentTime
};
if (this.isSessionClosed) {
traceLog("server has received a PublishRequest but session is Closed");
this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadSessionClosed);
}
else if (this.subscriptionCount === 0) {
if (this._closed_subscriptions.length > 0 && this._closed_subscriptions[0].hasPendingNotifications) {
const verif = this._publish_request_queue.length;
// add the publish request to the queue for later processing
this._publish_request_queue.push(publishData);
const processed = __classPrivateFieldGet(this, _ServerSidePublishEngine_instances, "m", _ServerSidePublishEngine__feed_closed_subscription).call(this);
//xx ( may be subscription has expired by themselves) assert(verif === this._publish_request_queue.length);
//xx ( may be subscription has expired by themselves) assert(processed);
return;
}
traceLog("server has received a PublishRequest but has no subscription opened");
this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadNoSubscription);
}
else {
// add the publish request to the queue for later processing
this._publish_request_queue.push(publishData);
(0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount > 0);
debugLog(chalk_1.default.bgWhite.red("Adding a PublishRequest to the queue "), this._publish_request_queue.length);
__classPrivateFieldGet(this, _ServerSidePublishEngine_instances, "m", _ServerSidePublishEngine__feed_closed_subscription).call(this);
__classPrivateFieldGet(this, _ServerSidePublishEngine_instances, "m", _ServerSidePublishEngine__feed_late_subscription).call(this);
__classPrivateFieldGet(this, _ServerSidePublishEngine_instances, "m", _ServerSidePublishEngine__handle_too_many_requests).call(this);
}
}
_send_error_for_request(publishData, statusCode) {
_assertValidPublishData(publishData);
const response = new node_opcua_types_1.ServiceFault({
responseHeader: { serviceResult: statusCode }
});
this._send_response_for_request(publishData, response);
}
_cancelPendingPublishRequest(statusCode) {
if (this._publish_request_queue) {
debugLog(chalk_1.default.red("Cancelling pending PublishRequest with statusCode "), statusCode.toString(), " length =", this._publish_request_queue.length);
}
else {
debugLog(chalk_1.default.red("No pending PublishRequest to cancel"));
}
for (const publishData of this._publish_request_queue) {
this._send_error_for_request(publishData, statusCode);
}
this._publish_request_queue = [];
}
/**
* call by a subscription when no notification message is available after the keep alive delay has
* expired.
*
* @param subscriptionId
* @param future_sequence_number
* @return true if a publish response has been sent
*/
send_keep_alive_response(subscriptionId, future_sequence_number) {
// this keep-alive Message informs the Client that the Subscription is still active.
// Each keep-alive Message is a response to a Publish request in which the notification Message
// parameter does not contain any Notifications and that contains the sequence number of the next
// Notification Message that is to be sent.
const subscription = this.getSubscriptionById(subscriptionId);
/* istanbul ignore next */
if (!subscription) {
traceLog("send_keep_alive_response => invalid subscriptionId = ", subscriptionId);
return false;
}
// let check if we have available PublishRequest to send the keep alive
if (this.pendingPublishRequestCount === 0 || subscription.hasPendingNotifications) {
// we cannot send the keep alive PublishResponse
traceLog("send_keep_alive_response => cannot send keep-alive (no PublishRequest left) subscriptionId = ", subscriptionId);
return false;
}
debugLog(`Sending keep alive response for subscription id ${subscription.id} ${subscription.publishingInterval} ${subscription.maxKeepAliveCount}`);
this._send_response(subscription, new node_opcua_types_1.PublishResponse({
availableSequenceNumbers: subscription.getAvailableSequenceNumbers(),
moreNotifications: false,
notificationMessage: {
sequenceNumber: future_sequence_number
},
subscriptionId
}));
return true;
}
_send_response(subscription, response) {
(0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount > 0);
(0, node_opcua_assert_1.assert)(response.subscriptionId !== 0xffffff);
const publishData = this._publish_request_queue.shift();
this._send_valid_response_for_request(publishData, response);
}
_on_tick() {
this._cancelTimeoutRequests();
}
_cancelTimeoutRequests() {
if (this._publish_request_queue.length === 0) {
return;
}
// filter out timeout requests
const parts = (0, lodash_1.partition)(this._publish_request_queue, timeout_filter);
this._publish_request_queue = parts[1]; // still valid
const invalid_published_request = parts[0];
for (const publishData of invalid_published_request) {
// istanbul ignore next
if (doDebug) {
debugLog(chalk_1.default.cyan(" CANCELING TIMEOUT PUBLISH REQUEST "));
}
this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadTimeout);
}
}
_send_response_for_request(publishData, response) {
response.responseHeader.requestHandle = publishData.request.requestHeader.requestHandle;
publishData.callback(publishData.request, response);
}
_send_valid_response_for_request(publishData, response) {
// istanbul ignore next
if (doDebug) {
debugLog("_send_response_for_request ", response.toString());
}
_assertValidPublishData(publishData);
// xx assert(response.responseHeader.requestHandle !== 0,"expecting a valid requestHandle");
response.results = publishData.results;
this._send_response_for_request(publishData, response);
}
}
exports.ServerSidePublishEngine = ServerSidePublishEngine;
_ServerSidePublishEngine_instances = new WeakSet(), _ServerSidePublishEngine__find_starving_subscription = function _ServerSidePublishEngine__find_starving_subscription() {
const late_subscriptions = this.findLateSubscriptions();
function compare_subscriptions(s1, s2) {
if (s1.priority === s2.priority) {
return s1.timeToExpiration < s2.timeToExpiration ? 1 : 0;
}
return s1.priority > s2.priority ? 1 : 0;
}
function findLateSubscriptionSortedByPriority() {
if (late_subscriptions.length === 0) {
return null;
}
late_subscriptions.sort(compare_subscriptions);
// istanbul ignore next
if (doDebug) {
debugLog(late_subscriptions
.map((s) => "[ id = " +
s.id +
" prio=" +
s.priority +
" t=" +
s.timeToExpiration +
" ka=" +
s.timeToKeepAlive +
" m?=" +
s.hasUncollectedMonitoredItemNotifications +
" " +
server_subscription_2.SubscriptionState[s.state] +
" " +
s.messageSent +
"]")
.join(" \n"));
}
return late_subscriptions[late_subscriptions.length - 1];
}
if (this._closed_subscriptions) {
/** */
}
const starving_subscription = /* this.findSubscriptionWaitingForFirstPublish() || */ findLateSubscriptionSortedByPriority();
return starving_subscription;
}, _ServerSidePublishEngine__feed_late_subscription = function _ServerSidePublishEngine__feed_late_subscription() {
setImmediate(() => {
if (!this.pendingPublishRequestCount) {
return;
}
const starving_subscription = __classPrivateFieldGet(this, _ServerSidePublishEngine_instances, "m", _ServerSidePublishEngine__find_starving_subscription).call(this);
if (starving_subscription) {
doDebug &&
debugLog(chalk_1.default.bgWhite.red("feeding most late subscription subscriptionId = "), starving_subscription.id);
starving_subscription.process_subscription();
}
});
}, _ServerSidePublishEngine__feed_closed_subscription = function _ServerSidePublishEngine__feed_closed_subscription() {
if (!this.pendingPublishRequestCount) {
return false;
}
if (this._closed_subscriptions.length === 0) {
debugLog("ServerSidePublishEngine#_feed_closed_subscription -> nothing to do");
return false;
}
// process closed subscription
const closed_subscription = this._closed_subscriptions[0];
(0, node_opcua_assert_1.assert)(closed_subscription.hasPendingNotifications);
debugLog("ServerSidePublishEngine#_feed_closed_subscription for closed_subscription ", closed_subscription.id);
closed_subscription?._publish_pending_notifications();
if (!closed_subscription?.hasPendingNotifications) {
closed_subscription.dispose();
this._closed_subscriptions.shift();
}
return true;
}, _ServerSidePublishEngine__handle_too_many_requests = function _ServerSidePublishEngine__handle_too_many_requests() {
if (this.pendingPublishRequestCount > this.maxPublishRequestInQueue) {
traceLog("server has received too many PublishRequest", this.pendingPublishRequestCount, "/", this.maxPublishRequestInQueue);
(0, node_opcua_assert_1.assert)(this.pendingPublishRequestCount === this.maxPublishRequestInQueue + 1);
// When a Server receives a new Publish request that exceeds its limit it shall de-queue the oldest Publish
// request and return a response with the result set to Bad_TooManyPublishRequests.
// dequeue oldest request
const publishData = this._publish_request_queue.shift();
this._send_error_for_request(publishData, node_opcua_status_code_1.StatusCodes.BadTooManyPublishRequests);
}
};
ServerSidePublishEngine.registry = new node_opcua_object_registry_1.ObjectRegistry();
//# sourceMappingURL=server_publish_engine.js.map