-
-
Notifications
You must be signed in to change notification settings - Fork 480
/
base_node_private.ts
679 lines (576 loc) · 22.3 KB
/
base_node_private.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
/**
* @module node-opcua-address-space.Private
*/
// tslint:disable:no-bitwise
import * as chalk from "chalk";
import * as _ from "underscore";
import { assert } from "node-opcua-assert";
import {
AccessLevelFlag,
BrowseDirection, coerceLocalizedText,
coerceQualifiedName,
LocalizedText, NodeClass,
ResultMask
} from "node-opcua-data-model";
import { NodeId, resolveNodeId, sameNodeId } from "node-opcua-nodeid";
import { ReferenceDescription } from "node-opcua-types";
import {
AddressSpace,
SessionContext, UAConditionBase,
UADataType,
UAObjectType as UAObjectTypePublic,
UAReferenceType as UAReferenceTypePublic
} from "../source";
import { BaseNode as BaseNodePublic } from "../source";
import { BaseNode } from "./base_node";
import { UANamespace_process_modelling_rule } from "./namespace_private";
import { Reference } from "./reference";
import { UAMethod } from "./ua_method";
import { UAObject } from "./ua_object";
import { UAObjectType } from "./ua_object_type";
import { UAVariable } from "./ua_variable";
import { UAVariableType } from "./ua_variable_type";
const g_weakMap = new WeakMap();
interface BaseNodeCache {
__address_space: AddressSpace | null;
_back_referenceIdx: any;
_browseFilter?: (this: BaseNode, context?: SessionContext) => boolean;
_cache: any;
_description?: LocalizedText;
_displayName: LocalizedText[];
_parent?: BaseNodePublic | null;
_referenceIdx: any;
_subtype_idxVersion: number;
_subtype_idx: any;
}
export function BaseNode_initPrivate(self: BaseNode): BaseNodeCache {
const _private: BaseNodeCache = {
__address_space: null,
_back_referenceIdx: {},
_browseFilter: undefined,
_cache: {},
_description: undefined,
_displayName: [],
_parent: undefined,
_referenceIdx: {},
_subtype_idx: {},
_subtype_idxVersion: 0,
};
g_weakMap.set(self, _private);
return _private;
}
export function BaseNode_removePrivate(self: BaseNode): void {
// there is no need to delete object from weakmap
// the GC will take care of this in due course
// g_weakMap.delete(self);
}
export function BaseNode_getPrivate(self: BaseNode): BaseNodeCache {
return g_weakMap.get(self);
}
const hasTypeDefinition_ReferenceTypeNodeId = resolveNodeId("HasTypeDefinition");
export interface ToStringOption {
level: number;
cycleDetector: any;
padding: string;
add(someline: string): void;
indent(a: string, b: string | null): void;
}
export class ToStringBuilder implements ToStringOption {
public level: number = 0;
public cycleDetector: any = {};
public padding: string = "";
private str: string[] = [];
constructor() {
//
this.str = [];
}
public add(line: string): void {
this.str.push(line);
}
public toString(): string {
return this.str.join("\n");
}
public indent(str: string, padding: string | null): string {
padding = padding || " ";
return str.split("\n").map((r) => {
return padding + r;
}).join("\n");
}
}
function set_as_processed(
options: ToStringOption,
nodeId: NodeId
) {
options.cycleDetector[nodeId.toString()] = nodeId;
}
function is_already_processed(
options: ToStringOption,
nodeId: NodeId
): boolean {
return !!options.cycleDetector[nodeId.toString()];
}
export function BaseNode_toString(
this: BaseNode,
options: ToStringOption
) {
options.level = options.level || 1;
set_as_processed(options, this.nodeId);
options.add("");
options.add(options.padding + chalk.yellow(" nodeId : ") + this.nodeId.toString());
options.add(options.padding + chalk.yellow(" nodeClass : ") + NodeClass[this.nodeClass] + " (" + this.nodeClass + ")");
options.add(options.padding + chalk.yellow(" browseName : ") + this.browseName.toString());
options.add(options.padding + chalk.yellow(" displayName : ") + this.displayName
.map((f) => f.locale + " " + f.text).join(" | "));
options.add(options.padding + chalk.yellow(" description : ")
+ (this.description ? this.description.toString() : ""));
}
export function BaseNode_References_toString(
this: BaseNode,
options: ToStringOption
) {
const _private = BaseNode_getPrivate(this);
const dispOptions = {
addressSpace: this.addressSpace
};
const addressSpace = this.addressSpace;
options.add(options.padding + chalk.yellow(" references : ") + " length =" +
Object.keys(_private._referenceIdx).length);
function dump_reference(follow: boolean, reference: Reference | null) {
if (!reference) {
return;
}
const o = Reference.resolveReferenceNode(addressSpace, reference);
const name = o ? o.browseName.toString() : "<???>";
options.add(options.padding +
chalk.yellow(" +-> ") +
reference.toString(dispOptions) +
" " + chalk.cyan(name));
// ignore HasTypeDefinition as it has been already handled
if (sameNodeId(reference.referenceType, hasTypeDefinition_ReferenceTypeNodeId) &&
reference.nodeId.namespace === 0) {
return;
}
if (o) {
if (!is_already_processed(options, o.nodeId)) {
set_as_processed(options, o.nodeId);
if (options.level > 1 && follow) {
const rr = (o as any).toString({
cycleDetector: options.cycleDetector,
level: options.level - 1,
padding: options.padding + " ",
});
options.add(rr);
}
}
}
}
// direct reference
_.forEach(_private._referenceIdx, dump_reference.bind(null, true));
const br = _.map(_private._back_referenceIdx, (x: Reference) => x);
options.add(options.padding +
chalk.yellow(" back_references : ") +
chalk.cyan(" length =") + br.length +
chalk.grey(" ( references held by other nodes involving this node)"));
// backward reference
br.forEach(dump_reference.bind(null, false));
}
function _UAType_toString(
this: UAReferenceTypePublic | UADataType | UAObjectType | UAVariableType,
options: ToStringOption
): void {
if (this.subtypeOfObj) {
options.add(options.padding + chalk.yellow(" subtypeOf : ") +
this.subtypeOfObj.browseName.toString() + " (" + this.subtypeOfObj.nodeId.toString() + ")");
}
}
function _UAInstance_toString(
this: UAVariable | UAMethod | UAObject,
options: ToStringOption
): void {
if (this.typeDefinitionObj) {
options.add(options.padding + chalk.yellow(" typeDefinition : ") +
this.typeDefinitionObj.browseName.toString() + " (" + this.typeDefinitionObj.nodeId.toString() + ")");
}
}
export function UAVariableType_toString(
this: UAVariableType,
options: ToStringOption
): void {
BaseNode_toString.call(this, options);
_UAType_toString.call(this, options);
VariableOrVariableType_toString.call(this, options);
BaseNode_References_toString.call(this, options);
}
export function UAVariable_toString(
this: UAVariable,
options: ToStringOption
): void {
BaseNode_toString.call(this, options);
_UAInstance_toString.call(this, options);
VariableOrVariableType_toString.call(this, options);
BaseNode_References_toString.call(this, options);
}
export function UAObject_toString(
this: UAObject,
options: ToStringOption
): void {
BaseNode_toString.call(this, options);
_UAInstance_toString.call(this, options);
BaseNode_References_toString.call(this, options);
}
export function UAObjectType_toString(
this: UAObjectType,
options: ToStringOption
): void {
BaseNode_toString.call(this, options);
_UAType_toString.call(this, options);
BaseNode_References_toString.call(this, options);
}
function accessLevelFlagToString(flag: AccessLevelFlag): string {
const str: string[] = [];
if (flag & AccessLevelFlag.CurrentRead) { str.push("CurrentRead"); }
if (flag & AccessLevelFlag.CurrentWrite) { str.push("CurrentWrite"); }
if (flag & AccessLevelFlag.HistoryRead) { str.push("HistoryRead"); }
if (flag & AccessLevelFlag.HistoryWrite) { str.push("HistoryWrite"); }
if (flag & AccessLevelFlag.SemanticChange) { str.push("SemanticChange"); }
if (flag & AccessLevelFlag.StatusWrite) { str.push("StatusWrite"); }
if (flag & AccessLevelFlag.TimestampWrite) { str.push("TimestampWrite"); }
return str.join(" | ");
}
export function VariableOrVariableType_toString(
this: UAVariableType | UAVariable,
options: ToStringOption
) {
assert(options);
const _private = BaseNode_getPrivate(this);
if (this.dataType) {
const addressSpace = this.addressSpace;
const d = addressSpace.findNode(this.dataType);
const n = d ? "(" + d.browseName.toString() + ")" : " (???)";
options.add(options.padding + chalk.yellow(" dataType : ") + this.dataType + " " + n);
}
if (this.nodeClass === NodeClass.Variable) {
if (this._dataValue) {
options.add(options.padding + chalk.yellow(" value : ") + "\n" +
options.indent(this._dataValue.toString(), options.padding + " | "));
}
}
if (this.accessLevel) {
options.add(options.padding + chalk.yellow(" accessLevel : ") + " " +
accessLevelFlagToString(this.accessLevel));
}
if (this.userAccessLevel) {
options.add(options.padding + chalk.yellow(" userAccessLevel : ") + " " +
accessLevelFlagToString(this.userAccessLevel));
}
if (this.hasOwnProperty("valueRank")) {
options.add(options.padding + chalk.yellow(" valueRank : ") + " " +
this.valueRank.toString());
}
if (this.minimumSamplingInterval !== undefined) {
options.add(options.padding + chalk.yellow(" minimumSamplingInterval : ") + " " +
this.minimumSamplingInterval.toString() + " ms");
}
}
/**
* clone properties and methods
* @private
*/
function _clone_collection_new(
this: BaseNodePublic,
newParent: BaseNodePublic,
collectionRef: any,
optionalFilter: any,
extraInfo: any
): void {
const addressSpace = newParent.addressSpace;
assert(!optionalFilter || (_.isFunction(optionalFilter.shouldKeep) && _.isFunction(optionalFilter.filterFor)));
for (const reference of collectionRef) {
const node = Reference.resolveReferenceNode(addressSpace, reference);
// ensure node is of the correct type,
// it may happen that the xmlnodeset2 file was malformed
// istanbul ignore next
if (!_.isFunction((node as any).clone)) {
// tslint:disable-next-line:no-console
console.log(
chalk.red("Warning : cannot clone node ") +
node.browseName.toString() +
" of class " + NodeClass[node.nodeClass].toString() +
" while cloning " + newParent.browseName.toString());
continue;
}
if (optionalFilter && !optionalFilter.shouldKeep(node)) {
continue; // skip this node
}
assert(reference.isForward);
assert(reference.referenceType instanceof NodeId, "" + reference.referenceType.toString());
const options = {
references: [
{ referenceType: reference.referenceType, isForward: false, nodeId: newParent.nodeId }
]
};
const clone = (node as any).clone(options, optionalFilter, extraInfo);
if (extraInfo) {
extraInfo.registerClonedObject(node, clone);
}
}
}
export function _clone_children_references(
this: BaseNodePublic,
newParent: BaseNodePublic,
optionalFilter: any,
extraInfo: any): void {
// find all reference that derives from the Aggregates
const aggregatesRef = this.findReferencesEx("Aggregates", BrowseDirection.Forward);
_clone_collection_new.call(this, newParent, aggregatesRef, optionalFilter, extraInfo);
}
export function _clone_non_hierarchical_references(
this: BaseNode,
newParent: BaseNodePublic,
optionalFilter: any,
extraInfo: any
) {
// clone only some non hierarchical_references that we do want to clone
// such as
// HasSubStateMachine
assert(newParent instanceof BaseNode);
// find all reference that derives from the HasSubStateMachine
const references = this.findReferencesEx("HasSubStateMachine", BrowseDirection.Forward);
_clone_collection_new.call(this, newParent, references, optionalFilter, extraInfo);
}
/**
* @method _clone
* @private
*/
export function _clone(
this: UAObject | UAVariable | UAMethod,
Constructor: any,
options: any,
optionalFilter: any,
extraInfo: any
): BaseNode {
assert(_.isFunction(Constructor));
assert(_.isObject(options));
assert(!extraInfo || (_.isObject(extraInfo) && _.isFunction(extraInfo.registerClonedObject)));
assert(!(this as any).subtypeOf, "We do not do cloning of Type yet");
options = _.extend(options, {
addressSpace: this.addressSpace,
browseName: this.browseName,
description: this.description,
displayName: this.displayName,
});
options.references = options.references || [];
if (this.typeDefinition) {
options.references.push({
isForward: true,
nodeId: this.typeDefinition,
referenceType: "HasTypeDefinition",
});
}
if (!options.modellingRule) {
if (this.modellingRule) {
const modellingRuleNode = this.findReferencesAsObject("HasModellingRule")[0];
assert(modellingRuleNode);
options.references.push({
isForward: true,
nodeId: modellingRuleNode.nodeId,
referenceType: "HasModellingRule",
});
}
} else {
UANamespace_process_modelling_rule(options.references, options.modellingRule);
}
options.nodeId = this.addressSpace.getOwnNamespace()._construct_nodeId(options);
assert(options.nodeId instanceof NodeId);
const cloneObj = new Constructor(options);
this.addressSpace._register(cloneObj);
const newFilter = optionalFilter ? optionalFilter.filterFor(cloneObj) : null;
_clone_children_references.call(this, cloneObj, newFilter, extraInfo);
_clone_non_hierarchical_references.call(this, cloneObj, newFilter, extraInfo);
cloneObj.propagate_back_references();
cloneObj.install_extra_properties();
return cloneObj;
}
export function _handle_HierarchicalReference(
node: BaseNode,
reference: Reference,
) {
const _private = BaseNode_getPrivate(node);
if (_private._cache._childByNameMap) {
const addressSpace = node.addressSpace;
const referenceType = Reference.resolveReferenceType(addressSpace, reference);
if (referenceType) {
const HierarchicalReferencesType = addressSpace.findReferenceType("HierarchicalReferences");
// xx console.log ("HierarchicalReferencesType",HierarchicalReferencesType.toString());
if (referenceType.isSupertypeOf(HierarchicalReferencesType!)) {
assert(reference.isForward);
const targetNode = Reference.resolveReferenceNode(addressSpace, reference);
// Xx console.log(" adding object to map");
_private._cache._childByNameMap[targetNode.browseName!.name!.toString()] = targetNode;
}
}
}
}
function _remove_HierarchicalReference(
node: BaseNode,
reference: Reference
) {
const _private = BaseNode_getPrivate(node);
if (_private._cache._childByNameMap) {
const addressSpace = node.addressSpace;
const referenceType = Reference.resolveReferenceType(addressSpace, reference);
if (referenceType) {
const HierarchicalReferencesType = addressSpace.findReferenceType("HierarchicalReferences");
if (referenceType.isSupertypeOf(HierarchicalReferencesType!)) {
assert(reference.isForward);
const targetNode = Reference.resolveReferenceNode(addressSpace, reference);
// Xx console.log(" adding object to map");
delete _private._cache._childByNameMap[targetNode.browseName!.name!.toString()];
}
}
}
}
function _makeReferenceDescription(
addressSpace: AddressSpace,
reference: Reference,
resultMask: number
): ReferenceDescription {
const isForward = reference.isForward;
const referenceTypeId = Reference.resolveReferenceType(addressSpace, reference).nodeId;
assert(referenceTypeId instanceof NodeId);
const obj = Reference.resolveReferenceNode(addressSpace, reference) as any;
let data: any = {};
if (!obj) {
// cannot find reference node
data = {
isForward,
nodeId: reference.nodeId,
referenceTypeId: (resultMask & ResultMask.ReferenceType) ? referenceTypeId : null,
typeDefinition: null
};
} else {
assert(reference.nodeId, " obj.nodeId");
data = {
browseName: (resultMask & ResultMask.BrowseName) ? coerceQualifiedName(obj.browseName) : null,
displayName: (resultMask & ResultMask.DisplayName) ? coerceLocalizedText(obj.displayName[0]) : null,
isForward: (resultMask & ResultMask.IsForward) ? isForward : false,
nodeClass: (resultMask & ResultMask.NodeClass) ? obj.nodeClass : NodeClass.Unspecified,
nodeId: obj.nodeId,
referenceTypeId: (resultMask & ResultMask.ReferenceType) ? referenceTypeId : null,
typeDefinition: (resultMask & ResultMask.TypeDefinition) ? obj.typeDefinition : null
};
}
if (data.typeDefinition === null) {
data.typeDefinition = NodeId.nullNodeId;
}
const referenceDescription = new ReferenceDescription(data);
return referenceDescription;
}
export function _constructReferenceDescription(
addressSpace: AddressSpace,
references: Reference[],
resultMask: number
): ReferenceDescription[] {
assert(_.isArray(references));
return references.map((reference: Reference) => _makeReferenceDescription(addressSpace, reference, resultMask));
}
export function BaseNode_remove_backward_reference(this: BaseNode, reference: Reference): void {
const _private = BaseNode_getPrivate(this);
_remove_HierarchicalReference(this, reference);
const h = reference.hash;
if (_private._back_referenceIdx && _private._back_referenceIdx[h]) {
// note : h may not exist in _back_referenceIdx since we are not indexing
// _back_referenceIdx to UAObjectType and UAVariableType for performance reasons
_private._back_referenceIdx[h].dispose();
delete _private._back_referenceIdx[h];
}
reference.dispose();
}
export function BaseNode_add_backward_reference(
this: BaseNode,
reference: Reference
): void {
const _private = BaseNode_getPrivate(this);
const h = reference.hash;
assert(_.isString(h));
// istanbul ignore next
if (_private._referenceIdx[h]) {
// the reference exists already in the forward references
// this append for instance when the XML NotSetFile has redundant <Reference>
// in this case there is nothing to do
return;
}
// istanbul ignore next
if (_private._back_referenceIdx[h]) {
const opts = { addressSpace: this.addressSpace };
// tslint:disable-next-line:no-console
console.warn(" Warning !", this.browseName.toString());
// tslint:disable-next-line:no-console
console.warn(" ", reference.toString(opts));
// tslint:disable-next-line:no-console
console.warn(" already found in ===>");
// tslint:disable-next-line:no-console
console.warn(_.map(_private._back_referenceIdx, (c: Reference) => c.toString(opts)).join("\n"));
// tslint:disable-next-line:no-console
console.warn("===>");
throw new Error("reference exists already in _back_references");
}
if (!reference._referenceType) {
const stop_here = 1;
}
// assert(reference._referenceType instanceof ReferenceType);
_private._back_referenceIdx[h] = reference;
_handle_HierarchicalReference(this, reference);
(this as any)._clear_caches();
}
function _get_idx(referenceType: UAReferenceTypePublic): any {
const possibleReferenceTypes = referenceType.getAllSubtypes();
// create a index of reference type with browseName as key for faster search
const keys: any = {};
for (const refType of possibleReferenceTypes) {
keys[refType.nodeId.toString()] = refType;
}
return keys;
}
export const ReferenceTypeCounter = { count: 0 };
/**
* getSubtypeIndex
* @returns {null|*}
* @private
*/
export function getSubtypeIndex(this: UAReferenceTypePublic): any {
const _cache = BaseNode_getPrivate(this as any as BaseNode);
if (_cache._subtype_idxVersion < ReferenceTypeCounter.count) {
// the cache need to be invalidated
_cache._subtype_idx = null;
} else {
// tslint:disable:no-empty
}
if (!_cache._subtype_idx) {
_cache._subtype_idx = _get_idx(this);
_cache._subtype_idxVersion = ReferenceTypeCounter.count;
}
return _cache._subtype_idx;
}
export function apply_condition_refresh(this: BaseNode, _cache?: any) {
// visit all notifiers recursively
_cache = _cache || {};
const notifiers = this.getNotifiers();
const eventSources = this.getEventSources();
const conditions = this.findReferencesAsObject("HasCondition", true);
for (const condition of conditions) {
if (condition instanceof UAConditionBase) {
condition._resend_conditionEvents();
}
}
const arr = ([] as UAObject[]).concat(notifiers as UAObject[], eventSources as UAObject[]);
for (const notifier of arr) {
const key = notifier.nodeId.toString();
if (!_cache[key]) {
_cache[key] = notifier;
if (notifier._conditionRefresh) {
notifier._conditionRefresh(_cache);
}
}
}
}