node-opcua-transport 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 (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 +72 -72
  8. package/dist/source/client_tcp_transport.js +322 -322
  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 +81 -81
  12. package/dist/source/message_builder_base.js +229 -229
  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 +119 -119
  18. package/dist/source/tcp_transport.js +386 -386
  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 +3 -3
@@ -1,387 +1,387 @@
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
- let fakeSocket = {
22
- invalid: true,
23
- destroy() {
24
- errorLog("MockSocket.destroy");
25
- },
26
- end() {
27
- errorLog("MockSocket.end");
28
- }
29
- };
30
- function setFakeTransport(mockSocket) {
31
- fakeSocket = mockSocket;
32
- }
33
- exports.setFakeTransport = setFakeTransport;
34
- function getFakeTransport() {
35
- if (fakeSocket.invalid) {
36
- throw new Error("getFakeTransport: setFakeTransport must be called first - BadProtocolVersionUnsupported");
37
- }
38
- return fakeSocket;
39
- }
40
- exports.getFakeTransport = getFakeTransport;
41
- let counter = 0;
42
- // tslint:disable:class-name
43
- class TCP_transport extends events_1.EventEmitter {
44
- constructor() {
45
- super();
46
- this.name = this.constructor.name + counter;
47
- counter += 1;
48
- this._timerId = null;
49
- this._timeout = 30000; // 30 seconds timeout
50
- this._socket = null;
51
- this.headerSize = 8;
52
- this.maxMessageSize = 0;
53
- this.maxChunkCount = 0;
54
- this.receiveBufferSize = 0;
55
- this.sendBufferSize = 0;
56
- this.protocolVersion = 0;
57
- this._disconnecting = false;
58
- this.bytesWritten = 0;
59
- this.bytesRead = 0;
60
- this._theCallback = undefined;
61
- this.chunkWrittenCount = 0;
62
- this.chunkReadCount = 0;
63
- this._onSocketClosedHasBeenCalled = false;
64
- this._onSocketEndedHasBeenCalled = false;
65
- TCP_transport.registry.register(this);
66
- }
67
- setLimits({ receiveBufferSize, sendBufferSize, maxMessageSize, maxChunkCount }) {
68
- this.receiveBufferSize = receiveBufferSize;
69
- this.sendBufferSize = sendBufferSize;
70
- this.maxMessageSize = maxMessageSize;
71
- this.maxChunkCount = maxChunkCount;
72
- // reinstall packetAssembler with correct limits
73
- this._install_packetAssembler();
74
- }
75
- get timeout() {
76
- return this._timeout;
77
- }
78
- set timeout(value) {
79
- debugLog("Setting socket " + this.name + " timeout = ", value);
80
- this._timeout = value;
81
- }
82
- dispose() {
83
- this._cleanup_timers();
84
- (0, node_opcua_assert_1.assert)(!this._timerId);
85
- if (this._socket) {
86
- this._socket.destroy();
87
- this._socket.removeAllListeners();
88
- this._socket = null;
89
- }
90
- TCP_transport.registry.unregister(this);
91
- }
92
- /**
93
- * write the message_chunk on the socket.
94
- * @method write
95
- * @param messageChunk
96
- */
97
- write(messageChunk, callback) {
98
- const header = (0, message_builder_base_1.readRawMessageHeader)(messageChunk);
99
- (0, node_opcua_assert_1.assert)(header.length === messageChunk.length);
100
- const c = header.messageHeader.isFinal;
101
- (0, node_opcua_assert_1.assert)(c === "F" || c === "C" || c === "A");
102
- this._write_chunk(messageChunk, (err) => {
103
- callback && callback(err);
104
- });
105
- }
106
- get isDisconnecting() {
107
- return this._disconnecting;
108
- }
109
- /**
110
- * disconnect the TCP layer and close the underlying socket.
111
- * The ```"close"``` event will be emitted to the observers with err=null.
112
- *
113
- * @method disconnect
114
- * @async
115
- * @param callback
116
- */
117
- disconnect(callback) {
118
- (0, node_opcua_assert_1.assert)(typeof callback === "function", "expecting a callback function, but got " + callback);
119
- if (this._disconnecting) {
120
- callback();
121
- return;
122
- }
123
- (0, node_opcua_assert_1.assert)(!this._disconnecting, "TCP Transport has already been disconnected");
124
- this._disconnecting = true;
125
- // xx assert(!this._theCallback,
126
- // "disconnect shall not be called while the 'one time message receiver' is in operation");
127
- this._cleanup_timers();
128
- if (this._socket) {
129
- this._socket.end();
130
- this._socket && this._socket.destroy();
131
- // xx this._socket.removeAllListeners();
132
- this._socket = null;
133
- }
134
- this.on_socket_ended(null);
135
- setImmediate(() => {
136
- callback();
137
- });
138
- }
139
- isValid() {
140
- return this._socket !== null && !this._socket.destroyed && !this._disconnecting;
141
- }
142
- _write_chunk(messageChunk, callback) {
143
- if (this._socket !== null) {
144
- this.bytesWritten += messageChunk.length;
145
- this.chunkWrittenCount++;
146
- this._socket.write(messageChunk, callback);
147
- }
148
- else {
149
- if (callback) {
150
- callback();
151
- }
152
- }
153
- }
154
- on_socket_ended(err) {
155
- (0, node_opcua_assert_1.assert)(!this._onSocketEndedHasBeenCalled);
156
- this._onSocketEndedHasBeenCalled = true; // we don't want to send close event twice ...
157
- /**
158
- * notify the observers that the transport layer has been disconnected.
159
- * @event close
160
- * @param err the Error object or null
161
- */
162
- this.emit("close", err || null);
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
- /**
288
- * notify the observers that a message chunk has been received
289
- * @event message
290
- * @param message_chunk the message chunk
291
- */
292
- this.emit("chunk", messageChunk);
293
- }
294
- }
295
- _cleanup_timers() {
296
- if (this._timerId) {
297
- clearTimeout(this._timerId);
298
- this._timerId = null;
299
- }
300
- }
301
- _start_one_time_message_receiver() {
302
- (0, node_opcua_assert_1.assert)(!this._timerId, "timer already started");
303
- // Setup timeout detection timer ....
304
- this._timerId = setTimeout(() => {
305
- this._timerId = null;
306
- this._fulfill_pending_promises(new Error(`Timeout in waiting for data on socket ( timeout was = ${this.timeout} ms)`));
307
- }, this.timeout);
308
- // also monitored
309
- if (this._socket) {
310
- // to do = intercept socket error as well
311
- this._on_error_during_one_time_message_receiver = (err) => {
312
- 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)));
313
- };
314
- this._socket.on("close", this._on_error_during_one_time_message_receiver);
315
- }
316
- }
317
- on_socket_closed(err) {
318
- if (this._onSocketClosedHasBeenCalled) {
319
- return;
320
- }
321
- (0, node_opcua_assert_1.assert)(!this._onSocketClosedHasBeenCalled);
322
- this._onSocketClosedHasBeenCalled = true; // we don't want to send close event twice ...
323
- /**
324
- * notify the observers that the transport layer has been disconnected.
325
- * @event socket_closed
326
- * @param err the Error object or null
327
- */
328
- this.emit("socket_closed", err || null);
329
- }
330
- _on_socket_data(data) {
331
- // istanbul ignore next
332
- if (!this.packetAssembler) {
333
- throw new Error("internal Error");
334
- }
335
- this.bytesRead += data.length;
336
- if (data.length > 0) {
337
- this.packetAssembler.feed(data);
338
- }
339
- }
340
- _on_socket_close(hadError) {
341
- // istanbul ignore next
342
- if (doDebug) {
343
- debugLog(chalk.red(" SOCKET CLOSE : "), chalk.yellow("had_error ="), chalk.cyan(hadError.toString()), this.name);
344
- }
345
- if (this._socket) {
346
- debugLog(" remote address = ", this._socket.remoteAddress, " ", this._socket.remoteFamily, " ", this._socket.remotePort);
347
- }
348
- if (hadError) {
349
- if (this._socket) {
350
- this._socket.destroy();
351
- }
352
- }
353
- const err = hadError ? new Error("ERROR IN SOCKET " + hadError.toString()) : undefined;
354
- this.on_socket_closed(err);
355
- this.dispose();
356
- }
357
- _on_socket_ended_message(err) {
358
- if (this._disconnecting) {
359
- return;
360
- }
361
- debugLog(chalk.red("Transport Connection ended") + " " + this.name);
362
- (0, node_opcua_assert_1.assert)(!this._disconnecting);
363
- err = err || new Error("_socket has been disconnected by third party");
364
- this.on_socket_ended(err);
365
- this._disconnecting = true;
366
- debugLog(" bytesRead = ", this.bytesRead);
367
- debugLog(" bytesWritten = ", this.bytesWritten);
368
- this._fulfill_pending_promises(new Error("Connection aborted - ended by server : " + (err ? err.message : "")));
369
- }
370
- _on_socket_end(err) {
371
- // istanbul ignore next
372
- if (doDebug) {
373
- debugLog(chalk.red(" SOCKET END : err="), chalk.yellow(err ? err.message : "null"), this.name);
374
- }
375
- this._on_socket_ended_message(err);
376
- }
377
- _on_socket_error(err) {
378
- // istanbul ignore next
379
- if (doDebug) {
380
- debugLog(chalk.red(" SOCKET ERROR : "), chalk.yellow(err.message), this.name);
381
- }
382
- // node The "close" event will be called directly following this event.
383
- }
384
- }
385
- exports.TCP_transport = TCP_transport;
386
- 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
+ let fakeSocket = {
22
+ invalid: true,
23
+ destroy() {
24
+ errorLog("MockSocket.destroy");
25
+ },
26
+ end() {
27
+ errorLog("MockSocket.end");
28
+ }
29
+ };
30
+ function setFakeTransport(mockSocket) {
31
+ fakeSocket = mockSocket;
32
+ }
33
+ exports.setFakeTransport = setFakeTransport;
34
+ function getFakeTransport() {
35
+ if (fakeSocket.invalid) {
36
+ throw new Error("getFakeTransport: setFakeTransport must be called first - BadProtocolVersionUnsupported");
37
+ }
38
+ return fakeSocket;
39
+ }
40
+ exports.getFakeTransport = getFakeTransport;
41
+ let counter = 0;
42
+ // tslint:disable:class-name
43
+ class TCP_transport extends events_1.EventEmitter {
44
+ constructor() {
45
+ super();
46
+ this.name = this.constructor.name + counter;
47
+ counter += 1;
48
+ this._timerId = null;
49
+ this._timeout = 30000; // 30 seconds timeout
50
+ this._socket = null;
51
+ this.headerSize = 8;
52
+ this.maxMessageSize = 0;
53
+ this.maxChunkCount = 0;
54
+ this.receiveBufferSize = 0;
55
+ this.sendBufferSize = 0;
56
+ this.protocolVersion = 0;
57
+ this._disconnecting = false;
58
+ this.bytesWritten = 0;
59
+ this.bytesRead = 0;
60
+ this._theCallback = undefined;
61
+ this.chunkWrittenCount = 0;
62
+ this.chunkReadCount = 0;
63
+ this._onSocketClosedHasBeenCalled = false;
64
+ this._onSocketEndedHasBeenCalled = false;
65
+ TCP_transport.registry.register(this);
66
+ }
67
+ setLimits({ receiveBufferSize, sendBufferSize, maxMessageSize, maxChunkCount }) {
68
+ this.receiveBufferSize = receiveBufferSize;
69
+ this.sendBufferSize = sendBufferSize;
70
+ this.maxMessageSize = maxMessageSize;
71
+ this.maxChunkCount = maxChunkCount;
72
+ // reinstall packetAssembler with correct limits
73
+ this._install_packetAssembler();
74
+ }
75
+ get timeout() {
76
+ return this._timeout;
77
+ }
78
+ set timeout(value) {
79
+ debugLog("Setting socket " + this.name + " timeout = ", value);
80
+ this._timeout = value;
81
+ }
82
+ dispose() {
83
+ this._cleanup_timers();
84
+ (0, node_opcua_assert_1.assert)(!this._timerId);
85
+ if (this._socket) {
86
+ this._socket.destroy();
87
+ this._socket.removeAllListeners();
88
+ this._socket = null;
89
+ }
90
+ TCP_transport.registry.unregister(this);
91
+ }
92
+ /**
93
+ * write the message_chunk on the socket.
94
+ * @method write
95
+ * @param messageChunk
96
+ */
97
+ write(messageChunk, callback) {
98
+ const header = (0, message_builder_base_1.readRawMessageHeader)(messageChunk);
99
+ (0, node_opcua_assert_1.assert)(header.length === messageChunk.length);
100
+ const c = header.messageHeader.isFinal;
101
+ (0, node_opcua_assert_1.assert)(c === "F" || c === "C" || c === "A");
102
+ this._write_chunk(messageChunk, (err) => {
103
+ callback && callback(err);
104
+ });
105
+ }
106
+ get isDisconnecting() {
107
+ return this._disconnecting;
108
+ }
109
+ /**
110
+ * disconnect the TCP layer and close the underlying socket.
111
+ * The ```"close"``` event will be emitted to the observers with err=null.
112
+ *
113
+ * @method disconnect
114
+ * @async
115
+ * @param callback
116
+ */
117
+ disconnect(callback) {
118
+ (0, node_opcua_assert_1.assert)(typeof callback === "function", "expecting a callback function, but got " + callback);
119
+ if (this._disconnecting) {
120
+ callback();
121
+ return;
122
+ }
123
+ (0, node_opcua_assert_1.assert)(!this._disconnecting, "TCP Transport has already been disconnected");
124
+ this._disconnecting = true;
125
+ // xx assert(!this._theCallback,
126
+ // "disconnect shall not be called while the 'one time message receiver' is in operation");
127
+ this._cleanup_timers();
128
+ if (this._socket) {
129
+ this._socket.end();
130
+ this._socket && this._socket.destroy();
131
+ // xx this._socket.removeAllListeners();
132
+ this._socket = null;
133
+ }
134
+ this.on_socket_ended(null);
135
+ setImmediate(() => {
136
+ callback();
137
+ });
138
+ }
139
+ isValid() {
140
+ return this._socket !== null && !this._socket.destroyed && !this._disconnecting;
141
+ }
142
+ _write_chunk(messageChunk, callback) {
143
+ if (this._socket !== null) {
144
+ this.bytesWritten += messageChunk.length;
145
+ this.chunkWrittenCount++;
146
+ this._socket.write(messageChunk, callback);
147
+ }
148
+ else {
149
+ if (callback) {
150
+ callback();
151
+ }
152
+ }
153
+ }
154
+ on_socket_ended(err) {
155
+ (0, node_opcua_assert_1.assert)(!this._onSocketEndedHasBeenCalled);
156
+ this._onSocketEndedHasBeenCalled = true; // we don't want to send close event twice ...
157
+ /**
158
+ * notify the observers that the transport layer has been disconnected.
159
+ * @event close
160
+ * @param err the Error object or null
161
+ */
162
+ this.emit("close", err || null);
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
+ /**
288
+ * notify the observers that a message chunk has been received
289
+ * @event message
290
+ * @param message_chunk the message chunk
291
+ */
292
+ this.emit("chunk", messageChunk);
293
+ }
294
+ }
295
+ _cleanup_timers() {
296
+ if (this._timerId) {
297
+ clearTimeout(this._timerId);
298
+ this._timerId = null;
299
+ }
300
+ }
301
+ _start_one_time_message_receiver() {
302
+ (0, node_opcua_assert_1.assert)(!this._timerId, "timer already started");
303
+ // Setup timeout detection timer ....
304
+ this._timerId = setTimeout(() => {
305
+ this._timerId = null;
306
+ this._fulfill_pending_promises(new Error(`Timeout in waiting for data on socket ( timeout was = ${this.timeout} ms)`));
307
+ }, this.timeout);
308
+ // also monitored
309
+ if (this._socket) {
310
+ // to do = intercept socket error as well
311
+ this._on_error_during_one_time_message_receiver = (err) => {
312
+ 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)));
313
+ };
314
+ this._socket.on("close", this._on_error_during_one_time_message_receiver);
315
+ }
316
+ }
317
+ on_socket_closed(err) {
318
+ if (this._onSocketClosedHasBeenCalled) {
319
+ return;
320
+ }
321
+ (0, node_opcua_assert_1.assert)(!this._onSocketClosedHasBeenCalled);
322
+ this._onSocketClosedHasBeenCalled = true; // we don't want to send close event twice ...
323
+ /**
324
+ * notify the observers that the transport layer has been disconnected.
325
+ * @event socket_closed
326
+ * @param err the Error object or null
327
+ */
328
+ this.emit("socket_closed", err || null);
329
+ }
330
+ _on_socket_data(data) {
331
+ // istanbul ignore next
332
+ if (!this.packetAssembler) {
333
+ throw new Error("internal Error");
334
+ }
335
+ this.bytesRead += data.length;
336
+ if (data.length > 0) {
337
+ this.packetAssembler.feed(data);
338
+ }
339
+ }
340
+ _on_socket_close(hadError) {
341
+ // istanbul ignore next
342
+ if (doDebug) {
343
+ debugLog(chalk.red(" SOCKET CLOSE : "), chalk.yellow("had_error ="), chalk.cyan(hadError.toString()), this.name);
344
+ }
345
+ if (this._socket) {
346
+ debugLog(" remote address = ", this._socket.remoteAddress, " ", this._socket.remoteFamily, " ", this._socket.remotePort);
347
+ }
348
+ if (hadError) {
349
+ if (this._socket) {
350
+ this._socket.destroy();
351
+ }
352
+ }
353
+ const err = hadError ? new Error("ERROR IN SOCKET " + hadError.toString()) : undefined;
354
+ this.on_socket_closed(err);
355
+ this.dispose();
356
+ }
357
+ _on_socket_ended_message(err) {
358
+ if (this._disconnecting) {
359
+ return;
360
+ }
361
+ debugLog(chalk.red("Transport Connection ended") + " " + this.name);
362
+ (0, node_opcua_assert_1.assert)(!this._disconnecting);
363
+ err = err || new Error("_socket has been disconnected by third party");
364
+ this.on_socket_ended(err);
365
+ this._disconnecting = true;
366
+ debugLog(" bytesRead = ", this.bytesRead);
367
+ debugLog(" bytesWritten = ", this.bytesWritten);
368
+ this._fulfill_pending_promises(new Error("Connection aborted - ended by server : " + (err ? err.message : "")));
369
+ }
370
+ _on_socket_end(err) {
371
+ // istanbul ignore next
372
+ if (doDebug) {
373
+ debugLog(chalk.red(" SOCKET END : err="), chalk.yellow(err ? err.message : "null"), this.name);
374
+ }
375
+ this._on_socket_ended_message(err);
376
+ }
377
+ _on_socket_error(err) {
378
+ // istanbul ignore next
379
+ if (doDebug) {
380
+ debugLog(chalk.red(" SOCKET ERROR : "), chalk.yellow(err.message), this.name);
381
+ }
382
+ // node The "close" event will be called directly following this event.
383
+ }
384
+ }
385
+ exports.TCP_transport = TCP_transport;
386
+ TCP_transport.registry = new node_opcua_object_registry_1.ObjectRegistry();
387
387
  //# sourceMappingURL=tcp_transport.js.map