node-opcua-transport 2.76.0 → 2.76.2

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 (37) hide show
  1. package/dist/source/AcknowledgeMessage.d.ts +27 -27
  2. package/dist/source/AcknowledgeMessage.js +78 -78
  3. package/dist/source/HelloMessage.d.ts +27 -27
  4. package/dist/source/HelloMessage.js +94 -94
  5. package/dist/source/TCPErrorMessage.d.ts +18 -18
  6. package/dist/source/TCPErrorMessage.js +46 -46
  7. package/dist/source/client_tcp_transport.d.ts +86 -86
  8. package/dist/source/client_tcp_transport.js +331 -331
  9. package/dist/source/index.d.ts +13 -13
  10. package/dist/source/index.js +29 -29
  11. package/dist/source/message_builder_base.d.ts +112 -112
  12. package/dist/source/message_builder_base.js +244 -244
  13. package/dist/source/server_tcp_transport.d.ts +44 -44
  14. package/dist/source/server_tcp_transport.js +228 -228
  15. package/dist/source/status_codes.d.ts +100 -100
  16. package/dist/source/status_codes.js +110 -110
  17. package/dist/source/tcp_transport.d.ts +136 -136
  18. package/dist/source/tcp_transport.js +376 -376
  19. package/dist/source/tools.d.ts +14 -14
  20. package/dist/source/tools.js +103 -103
  21. package/dist/source/utils.d.ts +3 -3
  22. package/dist/source/utils.js +9 -9
  23. package/dist/test-fixtures/fixture_full_tcp_packets.d.ts +21 -21
  24. package/dist/test-fixtures/fixture_full_tcp_packets.js +41 -41
  25. package/dist/test-fixtures/index.d.ts +1 -1
  26. package/dist/test-fixtures/index.js +17 -17
  27. package/dist/test_helpers/direct_transport.d.ts +18 -18
  28. package/dist/test_helpers/direct_transport.js +62 -62
  29. package/dist/test_helpers/fake_server.d.ts +19 -19
  30. package/dist/test_helpers/fake_server.js +54 -54
  31. package/dist/test_helpers/half_com_channel.d.ts +17 -17
  32. package/dist/test_helpers/half_com_channel.js +31 -31
  33. package/dist/test_helpers/index.d.ts +4 -4
  34. package/dist/test_helpers/index.js +20 -20
  35. package/dist/test_helpers/socket_transport.d.ts +10 -10
  36. package/dist/test_helpers/socket_transport.js +30 -30
  37. package/package.json +11 -11
@@ -1,377 +1,377 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TCP_transport = exports.getFakeTransport = exports.setFakeTransport = void 0;
4
- /**
5
- * @module node-opcua-transport
6
- */
7
- const events_1 = require("events");
8
- const chalk = require("chalk");
9
- const node_opcua_assert_1 = require("node-opcua-assert");
10
- const node_opcua_debug_1 = require("node-opcua-debug");
11
- const node_opcua_object_registry_1 = require("node-opcua-object-registry");
12
- const node_opcua_packet_assembler_1 = require("node-opcua-packet-assembler");
13
- const status_codes_1 = require("./status_codes");
14
- const message_builder_base_1 = require("./message_builder_base");
15
- const utils_1 = require("./utils");
16
- const TCPErrorMessage_1 = require("./TCPErrorMessage");
17
- const tools_1 = require("./tools");
18
- const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
19
- const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
20
- const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
21
- const warningLog = (0, node_opcua_debug_1.make_warningLog)(__filename);
22
- let fakeSocket = {
23
- invalid: true,
24
- destroy() {
25
- errorLog("MockSocket.destroy");
26
- },
27
- end() {
28
- errorLog("MockSocket.end");
29
- }
30
- };
31
- function setFakeTransport(mockSocket) {
32
- fakeSocket = mockSocket;
33
- }
34
- exports.setFakeTransport = setFakeTransport;
35
- function getFakeTransport() {
36
- if (fakeSocket.invalid) {
37
- throw new Error("getFakeTransport: setFakeTransport must be called first - BadProtocolVersionUnsupported");
38
- }
39
- return fakeSocket;
40
- }
41
- exports.getFakeTransport = getFakeTransport;
42
- let counter = 0;
43
- // tslint:disable:class-name
44
- class TCP_transport extends events_1.EventEmitter {
45
- constructor() {
46
- super();
47
- this.name = this.constructor.name + counter;
48
- counter += 1;
49
- this._timerId = null;
50
- this._timeout = 30000; // 30 seconds timeout
51
- this._socket = null;
52
- this.headerSize = 8;
53
- this.maxMessageSize = 0;
54
- this.maxChunkCount = 0;
55
- this.receiveBufferSize = 0;
56
- this.sendBufferSize = 0;
57
- this.protocolVersion = 0;
58
- this._disconnecting = false;
59
- this.bytesWritten = 0;
60
- this.bytesRead = 0;
61
- this._theCallback = undefined;
62
- this.chunkWrittenCount = 0;
63
- this.chunkReadCount = 0;
64
- this._onSocketClosedHasBeenCalled = false;
65
- this._onSocketEndedHasBeenCalled = false;
66
- TCP_transport.registry.register(this);
67
- }
68
- setLimits({ receiveBufferSize, sendBufferSize, maxMessageSize, maxChunkCount }) {
69
- this.receiveBufferSize = receiveBufferSize;
70
- this.sendBufferSize = sendBufferSize;
71
- this.maxMessageSize = maxMessageSize;
72
- this.maxChunkCount = maxChunkCount;
73
- // reinstall packetAssembler with correct limits
74
- this._install_packetAssembler();
75
- }
76
- get timeout() {
77
- return this._timeout;
78
- }
79
- set timeout(value) {
80
- debugLog("Setting socket " + this.name + " timeout = ", value);
81
- this._timeout = value;
82
- }
83
- dispose() {
84
- this._cleanup_timers();
85
- (0, node_opcua_assert_1.assert)(!this._timerId);
86
- if (this._socket) {
87
- this._socket.destroy();
88
- this._socket.removeAllListeners();
89
- this._socket = null;
90
- }
91
- TCP_transport.registry.unregister(this);
92
- }
93
- /**
94
- * write the message_chunk on the socket.
95
- * @method write
96
- * @param messageChunk
97
- */
98
- write(messageChunk, callback) {
99
- const header = (0, message_builder_base_1.readRawMessageHeader)(messageChunk);
100
- (0, node_opcua_assert_1.assert)(header.length === messageChunk.length);
101
- const c = header.messageHeader.isFinal;
102
- (0, node_opcua_assert_1.assert)(c === "F" || c === "C" || c === "A");
103
- this._write_chunk(messageChunk, (err) => {
104
- callback && callback(err);
105
- });
106
- }
107
- get isDisconnecting() {
108
- return this._disconnecting;
109
- }
110
- /**
111
- * disconnect the TCP layer and close the underlying socket.
112
- * The ```"close"``` event will be emitted to the observers with err=null.
113
- *
114
- * @method disconnect
115
- * @async
116
- * @param callback
117
- */
118
- disconnect(callback) {
119
- (0, node_opcua_assert_1.assert)(typeof callback === "function", "expecting a callback function, but got " + callback);
120
- if (this._disconnecting) {
121
- callback();
122
- return;
123
- }
124
- (0, node_opcua_assert_1.assert)(!this._disconnecting, "TCP Transport has already been disconnected");
125
- this._disconnecting = true;
126
- // xx assert(!this._theCallback,
127
- // "disconnect shall not be called while the 'one time message receiver' is in operation");
128
- this._cleanup_timers();
129
- if (this._socket) {
130
- this._socket.end();
131
- this._socket && this._socket.destroy();
132
- // xx this._socket.removeAllListeners();
133
- this._socket = null;
134
- }
135
- this.on_socket_ended(null);
136
- setImmediate(() => {
137
- callback();
138
- });
139
- }
140
- isValid() {
141
- return this._socket !== null && !this._socket.destroyed && !this._disconnecting;
142
- }
143
- _write_chunk(messageChunk, callback) {
144
- if (this._socket !== null) {
145
- this.bytesWritten += messageChunk.length;
146
- this.chunkWrittenCount++;
147
- this._socket.write(messageChunk, callback);
148
- }
149
- else {
150
- if (callback) {
151
- callback();
152
- }
153
- }
154
- }
155
- on_socket_ended(err) {
156
- if (!this._onSocketEndedHasBeenCalled) {
157
- this._onSocketEndedHasBeenCalled = true; // we don't want to send close event twice ...
158
- this.emit("close", err || null);
159
- }
160
- else {
161
- debugLog("on_socket_ended has already been called");
162
- }
163
- }
164
- _install_packetAssembler() {
165
- if (this.packetAssembler) {
166
- this.packetAssembler.removeAllListeners();
167
- this.packetAssembler = undefined;
168
- }
169
- // install packet assembler ...
170
- this.packetAssembler = new node_opcua_packet_assembler_1.PacketAssembler({
171
- readChunkFunc: message_builder_base_1.readRawMessageHeader,
172
- minimumSizeInBytes: this.headerSize,
173
- maxChunkSize: this.receiveBufferSize //Math.max(this.receiveBufferSize, this.sendBufferSize)
174
- });
175
- this.packetAssembler.on("chunk", (chunk) => this._on_message_chunk_received(chunk));
176
- this.packetAssembler.on("error", (err, code) => {
177
- let statusCode = status_codes_1.StatusCodes2.BadTcpMessageTooLarge;
178
- switch (code) {
179
- case node_opcua_packet_assembler_1.PacketAssemblerErrorCode.ChunkSizeExceeded:
180
- statusCode = status_codes_1.StatusCodes2.BadTcpMessageTooLarge;
181
- break;
182
- default:
183
- statusCode = status_codes_1.StatusCodes2.BadTcpInternalError;
184
- }
185
- this.sendErrorMessage(statusCode, err.message);
186
- this.prematureTerminate(new Error("Packet Assembler : " + err.message), statusCode);
187
- });
188
- }
189
- /**
190
- * @method _install_socket
191
- * @param socket {Socket}
192
- * @protected
193
- */
194
- _install_socket(socket) {
195
- (0, node_opcua_assert_1.assert)(socket);
196
- this._socket = socket;
197
- if (doDebug) {
198
- debugLog(" TCP_transport#_install_socket ", this.name);
199
- }
200
- this._install_packetAssembler();
201
- this._socket
202
- .on("data", (data) => this._on_socket_data(data))
203
- .on("close", (hadError) => this._on_socket_close(hadError))
204
- .on("end", (err) => this._on_socket_end(err))
205
- .on("error", (err) => this._on_socket_error(err));
206
- // set socket timeout
207
- debugLog(" TCP_transport#install => setting " + this.name + " _socket.setTimeout to ", this.timeout);
208
- // let use a large timeout here to make sure that we not conflict with our internal timeout
209
- this._socket.setTimeout(this.timeout + 2000, () => {
210
- debugLog(` _socket ${this.name} has timed out (timeout = ${this.timeout})`);
211
- this.prematureTerminate(new Error("socket timeout : timeout=" + this.timeout), status_codes_1.StatusCodes2.BadTimeout);
212
- });
213
- }
214
- sendErrorMessage(statusCode, extraErrorDescription) {
215
- // When the Client receives an Error Message it reports the error to the application and closes the TransportConnection gracefully.
216
- // If a Client encounters a fatal error, it shall report the error to the application and send a CloseSecureChannel Message.
217
- /* istanbul ignore next*/
218
- if (doDebug) {
219
- debugLog(chalk.red(" sendErrorMessage ") + chalk.cyan(statusCode.toString()));
220
- debugLog(chalk.red(" extraErrorDescription ") + chalk.cyan(extraErrorDescription));
221
- }
222
- const reason = `${statusCode.toString()}:${extraErrorDescription || ""}`;
223
- const errorResponse = new TCPErrorMessage_1.TCPErrorMessage({
224
- statusCode,
225
- reason
226
- });
227
- const messageChunk = (0, tools_1.packTcpMessage)("ERR", errorResponse);
228
- this.write(messageChunk);
229
- }
230
- prematureTerminate(err, statusCode) {
231
- // https://reference.opcfoundation.org/v104/Core/docs/Part6/6.7.3/
232
- debugLog("prematureTerminate", err ? err.message : "", statusCode.toString());
233
- if (this._socket) {
234
- err.message = "premature socket termination " + err.message;
235
- // we consider this as an error
236
- const _s = this._socket;
237
- _s.end();
238
- _s.destroy(); // new Error("Socket has timed out"));
239
- _s.emit("error", err);
240
- this._socket = null;
241
- this.dispose();
242
- _s.removeAllListeners();
243
- }
244
- // this.gracefullShutdown(err);
245
- }
246
- /**
247
- * @method _install_one_time_message_receiver
248
- *
249
- * install a one time message receiver callback
250
- *
251
- * Rules:
252
- * * TCP_transport will not emit the ```message``` event, while the "one time message receiver" is in operation.
253
- * * the TCP_transport will wait for the next complete message chunk and call the provided callback func
254
- * ```callback(null,messageChunk);```
255
- *
256
- * if a messageChunk is not received within ```TCP_transport.timeout``` or if the underlying socket reports
257
- * an error, the callback function will be called with an Error.
258
- *
259
- */
260
- _install_one_time_message_receiver(callback) {
261
- (0, node_opcua_assert_1.assert)(!this._theCallback, "callback already set");
262
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
263
- this._theCallback = callback;
264
- this._start_one_time_message_receiver();
265
- }
266
- _fulfill_pending_promises(err, data) {
267
- this._cleanup_timers();
268
- if (this._socket && this._on_error_during_one_time_message_receiver) {
269
- this._socket.removeListener("close", this._on_error_during_one_time_message_receiver);
270
- this._on_error_during_one_time_message_receiver = null;
271
- }
272
- const callback = this._theCallback;
273
- this._theCallback = undefined;
274
- if (callback) {
275
- callback(err, data);
276
- return true;
277
- }
278
- return false;
279
- }
280
- _on_message_chunk_received(messageChunk) {
281
- if (utils_1.doTraceIncomingChunk) {
282
- console.log((0, node_opcua_debug_1.hexDump)(messageChunk));
283
- }
284
- const hadCallback = this._fulfill_pending_promises(null, messageChunk);
285
- this.chunkReadCount++;
286
- if (!hadCallback) {
287
- this.emit("chunk", messageChunk);
288
- }
289
- }
290
- _cleanup_timers() {
291
- if (this._timerId) {
292
- clearTimeout(this._timerId);
293
- this._timerId = null;
294
- }
295
- }
296
- _start_one_time_message_receiver() {
297
- (0, node_opcua_assert_1.assert)(!this._timerId, "timer already started");
298
- // Setup timeout detection timer ....
299
- this._timerId = setTimeout(() => {
300
- this._timerId = null;
301
- this._fulfill_pending_promises(new Error(`Timeout in waiting for data on socket ( timeout was = ${this.timeout} ms)`));
302
- }, this.timeout);
303
- // also monitored
304
- if (this._socket) {
305
- // to do = intercept socket error as well
306
- this._on_error_during_one_time_message_receiver = (err) => {
307
- this._fulfill_pending_promises(new Error(`ERROR in waiting for data on socket ( timeout was = ${this.timeout} ms) ` + (err === null || err === void 0 ? void 0 : err.message)));
308
- };
309
- this._socket.on("close", this._on_error_during_one_time_message_receiver);
310
- }
311
- }
312
- on_socket_closed(err) {
313
- if (this._onSocketClosedHasBeenCalled) {
314
- return;
315
- }
316
- (0, node_opcua_assert_1.assert)(!this._onSocketClosedHasBeenCalled);
317
- this._onSocketClosedHasBeenCalled = true; // we don't want to send close event twice ...
318
- this.emit("socket_closed", err || null);
319
- }
320
- _on_socket_data(data) {
321
- // istanbul ignore next
322
- if (!this.packetAssembler) {
323
- throw new Error("internal Error");
324
- }
325
- this.bytesRead += data.length;
326
- if (data.length > 0) {
327
- this.packetAssembler.feed(data);
328
- }
329
- }
330
- _on_socket_close(hadError) {
331
- // istanbul ignore next
332
- if (doDebug) {
333
- debugLog(chalk.red(" SOCKET CLOSE : "), chalk.yellow("had_error ="), chalk.cyan(hadError.toString()), this.name);
334
- }
335
- if (this._socket) {
336
- debugLog(" remote address = ", this._socket.remoteAddress, " ", this._socket.remoteFamily, " ", this._socket.remotePort);
337
- }
338
- if (hadError) {
339
- if (this._socket) {
340
- this._socket.destroy();
341
- }
342
- }
343
- const err = hadError ? new Error("ERROR IN SOCKET " + hadError.toString()) : undefined;
344
- this.on_socket_closed(err);
345
- this.dispose();
346
- }
347
- _on_socket_ended_message(err) {
348
- if (this._disconnecting) {
349
- return;
350
- }
351
- debugLog(chalk.red("Transport Connection ended") + " " + this.name);
352
- (0, node_opcua_assert_1.assert)(!this._disconnecting);
353
- err = err || new Error("_socket has been disconnected by third party");
354
- this.on_socket_ended(err);
355
- this._disconnecting = true;
356
- debugLog(" bytesRead = ", this.bytesRead);
357
- debugLog(" bytesWritten = ", this.bytesWritten);
358
- this._fulfill_pending_promises(new Error("Connection aborted - ended by server : " + (err ? err.message : "")));
359
- }
360
- _on_socket_end(err) {
361
- // istanbul ignore next
362
- if (doDebug) {
363
- debugLog(chalk.red(" SOCKET END : err="), chalk.yellow(err ? err.message : "null"), this.name);
364
- }
365
- this._on_socket_ended_message(err);
366
- }
367
- _on_socket_error(err) {
368
- // istanbul ignore next
369
- if (doDebug) {
370
- debugLog(chalk.red(" SOCKET ERROR : "), chalk.yellow(err.message), this.name);
371
- }
372
- // node The "close" event will be called directly following this event.
373
- }
374
- }
375
- exports.TCP_transport = TCP_transport;
376
- TCP_transport.registry = new node_opcua_object_registry_1.ObjectRegistry();
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TCP_transport = exports.getFakeTransport = exports.setFakeTransport = void 0;
4
+ /**
5
+ * @module node-opcua-transport
6
+ */
7
+ const events_1 = require("events");
8
+ const chalk = require("chalk");
9
+ const node_opcua_assert_1 = require("node-opcua-assert");
10
+ const node_opcua_debug_1 = require("node-opcua-debug");
11
+ const node_opcua_object_registry_1 = require("node-opcua-object-registry");
12
+ const node_opcua_packet_assembler_1 = require("node-opcua-packet-assembler");
13
+ const status_codes_1 = require("./status_codes");
14
+ const message_builder_base_1 = require("./message_builder_base");
15
+ const utils_1 = require("./utils");
16
+ const TCPErrorMessage_1 = require("./TCPErrorMessage");
17
+ const tools_1 = require("./tools");
18
+ const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
19
+ const doDebug = (0, node_opcua_debug_1.checkDebugFlag)(__filename);
20
+ const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
21
+ const warningLog = (0, node_opcua_debug_1.make_warningLog)(__filename);
22
+ let fakeSocket = {
23
+ invalid: true,
24
+ destroy() {
25
+ errorLog("MockSocket.destroy");
26
+ },
27
+ end() {
28
+ errorLog("MockSocket.end");
29
+ }
30
+ };
31
+ function setFakeTransport(mockSocket) {
32
+ fakeSocket = mockSocket;
33
+ }
34
+ exports.setFakeTransport = setFakeTransport;
35
+ function getFakeTransport() {
36
+ if (fakeSocket.invalid) {
37
+ throw new Error("getFakeTransport: setFakeTransport must be called first - BadProtocolVersionUnsupported");
38
+ }
39
+ return fakeSocket;
40
+ }
41
+ exports.getFakeTransport = getFakeTransport;
42
+ let counter = 0;
43
+ // tslint:disable:class-name
44
+ class TCP_transport extends events_1.EventEmitter {
45
+ constructor() {
46
+ super();
47
+ this.name = this.constructor.name + counter;
48
+ counter += 1;
49
+ this._timerId = null;
50
+ this._timeout = 30000; // 30 seconds timeout
51
+ this._socket = null;
52
+ this.headerSize = 8;
53
+ this.maxMessageSize = 0;
54
+ this.maxChunkCount = 0;
55
+ this.receiveBufferSize = 0;
56
+ this.sendBufferSize = 0;
57
+ this.protocolVersion = 0;
58
+ this._disconnecting = false;
59
+ this.bytesWritten = 0;
60
+ this.bytesRead = 0;
61
+ this._theCallback = undefined;
62
+ this.chunkWrittenCount = 0;
63
+ this.chunkReadCount = 0;
64
+ this._onSocketClosedHasBeenCalled = false;
65
+ this._onSocketEndedHasBeenCalled = false;
66
+ TCP_transport.registry.register(this);
67
+ }
68
+ setLimits({ receiveBufferSize, sendBufferSize, maxMessageSize, maxChunkCount }) {
69
+ this.receiveBufferSize = receiveBufferSize;
70
+ this.sendBufferSize = sendBufferSize;
71
+ this.maxMessageSize = maxMessageSize;
72
+ this.maxChunkCount = maxChunkCount;
73
+ // reinstall packetAssembler with correct limits
74
+ this._install_packetAssembler();
75
+ }
76
+ get timeout() {
77
+ return this._timeout;
78
+ }
79
+ set timeout(value) {
80
+ debugLog("Setting socket " + this.name + " timeout = ", value);
81
+ this._timeout = value;
82
+ }
83
+ dispose() {
84
+ this._cleanup_timers();
85
+ (0, node_opcua_assert_1.assert)(!this._timerId);
86
+ if (this._socket) {
87
+ this._socket.destroy();
88
+ this._socket.removeAllListeners();
89
+ this._socket = null;
90
+ }
91
+ TCP_transport.registry.unregister(this);
92
+ }
93
+ /**
94
+ * write the message_chunk on the socket.
95
+ * @method write
96
+ * @param messageChunk
97
+ */
98
+ write(messageChunk, callback) {
99
+ const header = (0, message_builder_base_1.readRawMessageHeader)(messageChunk);
100
+ (0, node_opcua_assert_1.assert)(header.length === messageChunk.length);
101
+ const c = header.messageHeader.isFinal;
102
+ (0, node_opcua_assert_1.assert)(c === "F" || c === "C" || c === "A");
103
+ this._write_chunk(messageChunk, (err) => {
104
+ callback && callback(err);
105
+ });
106
+ }
107
+ get isDisconnecting() {
108
+ return this._disconnecting;
109
+ }
110
+ /**
111
+ * disconnect the TCP layer and close the underlying socket.
112
+ * The ```"close"``` event will be emitted to the observers with err=null.
113
+ *
114
+ * @method disconnect
115
+ * @async
116
+ * @param callback
117
+ */
118
+ disconnect(callback) {
119
+ (0, node_opcua_assert_1.assert)(typeof callback === "function", "expecting a callback function, but got " + callback);
120
+ if (this._disconnecting) {
121
+ callback();
122
+ return;
123
+ }
124
+ (0, node_opcua_assert_1.assert)(!this._disconnecting, "TCP Transport has already been disconnected");
125
+ this._disconnecting = true;
126
+ // xx assert(!this._theCallback,
127
+ // "disconnect shall not be called while the 'one time message receiver' is in operation");
128
+ this._cleanup_timers();
129
+ if (this._socket) {
130
+ this._socket.end();
131
+ this._socket && this._socket.destroy();
132
+ // xx this._socket.removeAllListeners();
133
+ this._socket = null;
134
+ }
135
+ this.on_socket_ended(null);
136
+ setImmediate(() => {
137
+ callback();
138
+ });
139
+ }
140
+ isValid() {
141
+ return this._socket !== null && !this._socket.destroyed && !this._disconnecting;
142
+ }
143
+ _write_chunk(messageChunk, callback) {
144
+ if (this._socket !== null) {
145
+ this.bytesWritten += messageChunk.length;
146
+ this.chunkWrittenCount++;
147
+ this._socket.write(messageChunk, callback);
148
+ }
149
+ else {
150
+ if (callback) {
151
+ callback();
152
+ }
153
+ }
154
+ }
155
+ on_socket_ended(err) {
156
+ if (!this._onSocketEndedHasBeenCalled) {
157
+ this._onSocketEndedHasBeenCalled = true; // we don't want to send close event twice ...
158
+ this.emit("close", err || null);
159
+ }
160
+ else {
161
+ debugLog("on_socket_ended has already been called");
162
+ }
163
+ }
164
+ _install_packetAssembler() {
165
+ if (this.packetAssembler) {
166
+ this.packetAssembler.removeAllListeners();
167
+ this.packetAssembler = undefined;
168
+ }
169
+ // install packet assembler ...
170
+ this.packetAssembler = new node_opcua_packet_assembler_1.PacketAssembler({
171
+ readChunkFunc: message_builder_base_1.readRawMessageHeader,
172
+ minimumSizeInBytes: this.headerSize,
173
+ maxChunkSize: this.receiveBufferSize //Math.max(this.receiveBufferSize, this.sendBufferSize)
174
+ });
175
+ this.packetAssembler.on("chunk", (chunk) => this._on_message_chunk_received(chunk));
176
+ this.packetAssembler.on("error", (err, code) => {
177
+ let statusCode = status_codes_1.StatusCodes2.BadTcpMessageTooLarge;
178
+ switch (code) {
179
+ case node_opcua_packet_assembler_1.PacketAssemblerErrorCode.ChunkSizeExceeded:
180
+ statusCode = status_codes_1.StatusCodes2.BadTcpMessageTooLarge;
181
+ break;
182
+ default:
183
+ statusCode = status_codes_1.StatusCodes2.BadTcpInternalError;
184
+ }
185
+ this.sendErrorMessage(statusCode, err.message);
186
+ this.prematureTerminate(new Error("Packet Assembler : " + err.message), statusCode);
187
+ });
188
+ }
189
+ /**
190
+ * @method _install_socket
191
+ * @param socket {Socket}
192
+ * @protected
193
+ */
194
+ _install_socket(socket) {
195
+ (0, node_opcua_assert_1.assert)(socket);
196
+ this._socket = socket;
197
+ if (doDebug) {
198
+ debugLog(" TCP_transport#_install_socket ", this.name);
199
+ }
200
+ this._install_packetAssembler();
201
+ this._socket
202
+ .on("data", (data) => this._on_socket_data(data))
203
+ .on("close", (hadError) => this._on_socket_close(hadError))
204
+ .on("end", (err) => this._on_socket_end(err))
205
+ .on("error", (err) => this._on_socket_error(err));
206
+ // set socket timeout
207
+ debugLog(" TCP_transport#install => setting " + this.name + " _socket.setTimeout to ", this.timeout);
208
+ // let use a large timeout here to make sure that we not conflict with our internal timeout
209
+ this._socket.setTimeout(this.timeout + 2000, () => {
210
+ debugLog(` _socket ${this.name} has timed out (timeout = ${this.timeout})`);
211
+ this.prematureTerminate(new Error("socket timeout : timeout=" + this.timeout), status_codes_1.StatusCodes2.BadTimeout);
212
+ });
213
+ }
214
+ sendErrorMessage(statusCode, extraErrorDescription) {
215
+ // When the Client receives an Error Message it reports the error to the application and closes the TransportConnection gracefully.
216
+ // If a Client encounters a fatal error, it shall report the error to the application and send a CloseSecureChannel Message.
217
+ /* istanbul ignore next*/
218
+ if (doDebug) {
219
+ debugLog(chalk.red(" sendErrorMessage ") + chalk.cyan(statusCode.toString()));
220
+ debugLog(chalk.red(" extraErrorDescription ") + chalk.cyan(extraErrorDescription));
221
+ }
222
+ const reason = `${statusCode.toString()}:${extraErrorDescription || ""}`;
223
+ const errorResponse = new TCPErrorMessage_1.TCPErrorMessage({
224
+ statusCode,
225
+ reason
226
+ });
227
+ const messageChunk = (0, tools_1.packTcpMessage)("ERR", errorResponse);
228
+ this.write(messageChunk);
229
+ }
230
+ prematureTerminate(err, statusCode) {
231
+ // https://reference.opcfoundation.org/v104/Core/docs/Part6/6.7.3/
232
+ debugLog("prematureTerminate", err ? err.message : "", statusCode.toString());
233
+ if (this._socket) {
234
+ err.message = "premature socket termination " + err.message;
235
+ // we consider this as an error
236
+ const _s = this._socket;
237
+ _s.end();
238
+ _s.destroy(); // new Error("Socket has timed out"));
239
+ _s.emit("error", err);
240
+ this._socket = null;
241
+ this.dispose();
242
+ _s.removeAllListeners();
243
+ }
244
+ // this.gracefullShutdown(err);
245
+ }
246
+ /**
247
+ * @method _install_one_time_message_receiver
248
+ *
249
+ * install a one time message receiver callback
250
+ *
251
+ * Rules:
252
+ * * TCP_transport will not emit the ```message``` event, while the "one time message receiver" is in operation.
253
+ * * the TCP_transport will wait for the next complete message chunk and call the provided callback func
254
+ * ```callback(null,messageChunk);```
255
+ *
256
+ * if a messageChunk is not received within ```TCP_transport.timeout``` or if the underlying socket reports
257
+ * an error, the callback function will be called with an Error.
258
+ *
259
+ */
260
+ _install_one_time_message_receiver(callback) {
261
+ (0, node_opcua_assert_1.assert)(!this._theCallback, "callback already set");
262
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
263
+ this._theCallback = callback;
264
+ this._start_one_time_message_receiver();
265
+ }
266
+ _fulfill_pending_promises(err, data) {
267
+ this._cleanup_timers();
268
+ if (this._socket && this._on_error_during_one_time_message_receiver) {
269
+ this._socket.removeListener("close", this._on_error_during_one_time_message_receiver);
270
+ this._on_error_during_one_time_message_receiver = null;
271
+ }
272
+ const callback = this._theCallback;
273
+ this._theCallback = undefined;
274
+ if (callback) {
275
+ callback(err, data);
276
+ return true;
277
+ }
278
+ return false;
279
+ }
280
+ _on_message_chunk_received(messageChunk) {
281
+ if (utils_1.doTraceIncomingChunk) {
282
+ console.log((0, node_opcua_debug_1.hexDump)(messageChunk));
283
+ }
284
+ const hadCallback = this._fulfill_pending_promises(null, messageChunk);
285
+ this.chunkReadCount++;
286
+ if (!hadCallback) {
287
+ this.emit("chunk", messageChunk);
288
+ }
289
+ }
290
+ _cleanup_timers() {
291
+ if (this._timerId) {
292
+ clearTimeout(this._timerId);
293
+ this._timerId = null;
294
+ }
295
+ }
296
+ _start_one_time_message_receiver() {
297
+ (0, node_opcua_assert_1.assert)(!this._timerId, "timer already started");
298
+ // Setup timeout detection timer ....
299
+ this._timerId = setTimeout(() => {
300
+ this._timerId = null;
301
+ this._fulfill_pending_promises(new Error(`Timeout in waiting for data on socket ( timeout was = ${this.timeout} ms)`));
302
+ }, this.timeout);
303
+ // also monitored
304
+ if (this._socket) {
305
+ // to do = intercept socket error as well
306
+ this._on_error_during_one_time_message_receiver = (err) => {
307
+ this._fulfill_pending_promises(new Error(`ERROR in waiting for data on socket ( timeout was = ${this.timeout} ms) ` + (err === null || err === void 0 ? void 0 : err.message)));
308
+ };
309
+ this._socket.on("close", this._on_error_during_one_time_message_receiver);
310
+ }
311
+ }
312
+ on_socket_closed(err) {
313
+ if (this._onSocketClosedHasBeenCalled) {
314
+ return;
315
+ }
316
+ (0, node_opcua_assert_1.assert)(!this._onSocketClosedHasBeenCalled);
317
+ this._onSocketClosedHasBeenCalled = true; // we don't want to send close event twice ...
318
+ this.emit("socket_closed", err || null);
319
+ }
320
+ _on_socket_data(data) {
321
+ // istanbul ignore next
322
+ if (!this.packetAssembler) {
323
+ throw new Error("internal Error");
324
+ }
325
+ this.bytesRead += data.length;
326
+ if (data.length > 0) {
327
+ this.packetAssembler.feed(data);
328
+ }
329
+ }
330
+ _on_socket_close(hadError) {
331
+ // istanbul ignore next
332
+ if (doDebug) {
333
+ debugLog(chalk.red(" SOCKET CLOSE : "), chalk.yellow("had_error ="), chalk.cyan(hadError.toString()), this.name);
334
+ }
335
+ if (this._socket) {
336
+ debugLog(" remote address = ", this._socket.remoteAddress, " ", this._socket.remoteFamily, " ", this._socket.remotePort);
337
+ }
338
+ if (hadError) {
339
+ if (this._socket) {
340
+ this._socket.destroy();
341
+ }
342
+ }
343
+ const err = hadError ? new Error("ERROR IN SOCKET " + hadError.toString()) : undefined;
344
+ this.on_socket_closed(err);
345
+ this.dispose();
346
+ }
347
+ _on_socket_ended_message(err) {
348
+ if (this._disconnecting) {
349
+ return;
350
+ }
351
+ debugLog(chalk.red("Transport Connection ended") + " " + this.name);
352
+ (0, node_opcua_assert_1.assert)(!this._disconnecting);
353
+ err = err || new Error("_socket has been disconnected by third party");
354
+ this.on_socket_ended(err);
355
+ this._disconnecting = true;
356
+ debugLog(" bytesRead = ", this.bytesRead);
357
+ debugLog(" bytesWritten = ", this.bytesWritten);
358
+ this._fulfill_pending_promises(new Error("Connection aborted - ended by server : " + (err ? err.message : "")));
359
+ }
360
+ _on_socket_end(err) {
361
+ // istanbul ignore next
362
+ if (doDebug) {
363
+ debugLog(chalk.red(" SOCKET END : err="), chalk.yellow(err ? err.message : "null"), this.name);
364
+ }
365
+ this._on_socket_ended_message(err);
366
+ }
367
+ _on_socket_error(err) {
368
+ // istanbul ignore next
369
+ if (doDebug) {
370
+ debugLog(chalk.red(" SOCKET ERROR : "), chalk.yellow(err.message), this.name);
371
+ }
372
+ // node The "close" event will be called directly following this event.
373
+ }
374
+ }
375
+ exports.TCP_transport = TCP_transport;
376
+ TCP_transport.registry = new node_opcua_object_registry_1.ObjectRegistry();
377
377
  //# sourceMappingURL=tcp_transport.js.map