node-opcua-transport 2.55.0 → 2.59.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 (43) hide show
  1. package/.mocharc.yml +10 -10
  2. package/LICENSE +20 -20
  3. package/dist/source/AcknowledgeMessage.js +5 -5
  4. package/dist/source/AcknowledgeMessage.js.map +1 -1
  5. package/dist/source/TCPErrorMessage.js.map +1 -1
  6. package/dist/source/client_tcp_transport.d.ts +3 -3
  7. package/dist/source/client_tcp_transport.js +2 -2
  8. package/dist/source/client_tcp_transport.js.map +1 -1
  9. package/dist/source/server_tcp_transport.d.ts +3 -0
  10. package/dist/source/server_tcp_transport.js +2 -7
  11. package/dist/source/server_tcp_transport.js.map +1 -1
  12. package/dist/source/tcp_transport.js +2 -2
  13. package/dist/source/tools.d.ts +1 -1
  14. package/dist/source/tools.js +4 -4
  15. package/dist/source/tools.js.map +1 -1
  16. package/dist/source/utils.js +1 -1
  17. package/dist/source/utils.js.map +1 -1
  18. package/dist/test-fixtures/fixture_full_tcp_packets.js +8 -8
  19. package/dist/test-fixtures/fixture_full_tcp_packets.js.map +1 -1
  20. package/dist/test_helpers/direct_transport.d.ts +1 -1
  21. package/dist/test_helpers/direct_transport.js.map +1 -1
  22. package/dist/test_helpers/fake_server.d.ts +2 -2
  23. package/dist/test_helpers/fake_server.js +1 -1
  24. package/dist/test_helpers/fake_server.js.map +1 -1
  25. package/dist/test_helpers/half_com_channel.js +2 -4
  26. package/dist/test_helpers/half_com_channel.js.map +1 -1
  27. package/dist/test_helpers/socket_transport.js +1 -0
  28. package/dist/test_helpers/socket_transport.js.map +1 -1
  29. package/package.json +11 -9
  30. package/source/AcknowledgeMessage.ts +7 -9
  31. package/source/TCPErrorMessage.ts +58 -57
  32. package/source/client_tcp_transport.ts +366 -366
  33. package/source/index.ts +11 -11
  34. package/source/message_builder_base.ts +2 -2
  35. package/source/server_tcp_transport.ts +11 -12
  36. package/source/tcp_transport.ts +455 -455
  37. package/source/tools.ts +4 -4
  38. package/source/utils.ts +1 -1
  39. package/test_helpers/direct_transport.ts +2 -2
  40. package/test_helpers/fake_server.ts +69 -71
  41. package/test_helpers/half_com_channel.ts +2 -5
  42. package/test_helpers/index.ts +4 -4
  43. package/test_helpers/socket_transport.ts +33 -34
@@ -1,455 +1,455 @@
1
- /**
2
- * @module node-opcua-transport
3
- */
4
- import { EventEmitter } from "events";
5
- import { Socket } from "net";
6
-
7
- import * as chalk from "chalk";
8
-
9
- import { assert } from "node-opcua-assert";
10
- import { createFastUninitializedBuffer } from "node-opcua-buffer-utils";
11
- import * as debug from "node-opcua-debug";
12
- import { ObjectRegistry } from "node-opcua-object-registry";
13
- import { PacketAssembler } from "node-opcua-packet-assembler";
14
- import { ErrorCallback, CallbackWithData } from "node-opcua-status-code";
15
-
16
- import { readRawMessageHeader } from "./message_builder_base";
17
- import { writeTCPMessageHeader } from "./tools";
18
-
19
- const debugLog = debug.make_debugLog(__filename);
20
- const doDebug = debug.checkDebugFlag(__filename);
21
- const errorLog = debug.make_errorLog(__filename);
22
-
23
- export interface MockSocket {
24
- invalid?: boolean;
25
- [key:string]: any;
26
- }
27
- let fakeSocket: MockSocket = { invalid: true };
28
-
29
- export function setFakeTransport(mockSocket: MockSocket): void {
30
- fakeSocket = mockSocket;
31
- }
32
-
33
- export function getFakeTransport(): any {
34
- if (fakeSocket.invalid) {
35
- throw new Error("getFakeTransport: setFakeTransport must be called first - BadProtocolVersionUnsupported");
36
- }
37
- return fakeSocket;
38
- }
39
-
40
- let counter = 0;
41
-
42
- export interface TCP_transport {
43
- on(eventName: "message", eventHandler: (message: Buffer) => void): this;
44
- on(eventName: "socket_closed", eventHandler: (err: Error | null) => void): this;
45
- on(eventName: "close", eventHandler: (err: Error | null) => void): this;
46
-
47
- once(eventName: "message", eventHandler: (message: Buffer) => void): this;
48
- once(eventName: "socket_closed", eventHandler: (err: Error | null) => void): this;
49
- once(eventName: "close", eventHandler: (err: Error | null) => void): this;
50
- }
51
- // tslint:disable:class-name
52
- export class TCP_transport extends EventEmitter {
53
- private static registry = new ObjectRegistry();
54
-
55
- /**
56
- * indicates the version number of the OPCUA protocol used
57
- * @default 0
58
- */
59
- public protocolVersion: number;
60
-
61
- public bytesWritten: number;
62
- public bytesRead: number;
63
- public chunkWrittenCount: number;
64
- public chunkReadCount: number;
65
- public name: string;
66
-
67
- public _socket: Socket | null;
68
-
69
- /**
70
- * the size of the header in bytes
71
- * @default 8
72
- */
73
- private readonly headerSize: 8;
74
- private _disconnecting: boolean;
75
- private _timerId: NodeJS.Timer | null;
76
- private _onSocketClosedHasBeenCalled: boolean;
77
- private _onSocketEndedHasBeenCalled: boolean;
78
- private _theCallback?: CallbackWithData;
79
- private _on_error_during_one_time_message_receiver: any;
80
- private _pendingBuffer?: any;
81
- private packetAssembler?: PacketAssembler;
82
- private _timeout: number;
83
-
84
- constructor() {
85
- super();
86
-
87
- this.name = this.constructor.name + counter;
88
- counter += 1;
89
-
90
- this._timerId = null;
91
- this._timeout = 30000; // 30 seconds timeout
92
- this._socket = null;
93
- this.headerSize = 8;
94
- this.protocolVersion = 0;
95
-
96
- this._disconnecting = false;
97
- this._pendingBuffer = undefined;
98
-
99
- this.bytesWritten = 0;
100
- this.bytesRead = 0;
101
-
102
- this._theCallback = undefined;
103
- this.chunkWrittenCount = 0;
104
- this.chunkReadCount = 0;
105
-
106
- this._onSocketClosedHasBeenCalled = false;
107
- this._onSocketEndedHasBeenCalled = false;
108
- TCP_transport.registry.register(this);
109
- }
110
-
111
- public get timeout(): number {
112
- return this._timeout;
113
- }
114
- public set timeout(value: number) {
115
- debugLog("Setting socket " + this.name + " timeout = ", value);
116
- this._timeout = value;
117
- }
118
- public dispose(): void {
119
- this._cleanup_timers();
120
- assert(!this._timerId);
121
- if (this._socket) {
122
- this._socket.destroy();
123
- this._socket.removeAllListeners();
124
- this._socket = null;
125
- }
126
- TCP_transport.registry.unregister(this);
127
- }
128
-
129
- /**
130
- * ```createChunk``` is used to construct a pre-allocated chunk to store up to ```length``` bytes of data.
131
- * The created chunk includes a prepended header for ```chunk_type``` of size ```self.headerSize```.
132
- *
133
- * @method createChunk
134
- * @param msgType
135
- * @param chunkType {String} chunk type. should be 'F' 'C' or 'A'
136
- * @param length
137
- * @return a buffer object with the required length representing the chunk.
138
- *
139
- * Note:
140
- * - only one chunk can be created at a time.
141
- * - a created chunk should be committed using the ```write``` method before an other one is created.
142
- */
143
- public createChunk(msgType: string, chunkType: string, length: number): Buffer {
144
- assert(msgType === "MSG");
145
- assert(this._pendingBuffer === undefined, "createChunk has already been called ( use write first)");
146
-
147
- const totalLength = length + this.headerSize;
148
- const buffer = createFastUninitializedBuffer(totalLength);
149
- writeTCPMessageHeader("MSG", chunkType, totalLength, buffer);
150
- this._pendingBuffer = buffer;
151
-
152
- return buffer;
153
- }
154
-
155
- /**
156
- * write the message_chunk on the socket.
157
- * @method write
158
- * @param messageChunk
159
- *
160
- * Notes:
161
- * - the message chunk must have been created by ```createChunk```.
162
- * - once a message chunk has been written, it is possible to call ```createChunk``` again.
163
- *
164
- */
165
- public write(messageChunk: Buffer): void {
166
- assert(
167
- this._pendingBuffer === undefined || this._pendingBuffer === messageChunk,
168
- " write should be used with buffer created by createChunk"
169
- );
170
- const header = readRawMessageHeader(messageChunk);
171
- assert(header.length === messageChunk.length);
172
- assert(["F", "C", "A"].indexOf(header.messageHeader.isFinal) !== -1);
173
- this._write_chunk(messageChunk);
174
- this._pendingBuffer = undefined;
175
- }
176
-
177
- public get isDisconnecting(): boolean {
178
- return this._disconnecting;
179
- }
180
- /**
181
- * disconnect the TCP layer and close the underlying socket.
182
- * The ```"close"``` event will be emitted to the observers with err=null.
183
- *
184
- * @method disconnect
185
- * @async
186
- * @param callback
187
- */
188
- public disconnect(callback: ErrorCallback): void {
189
- assert(typeof callback === "function", "expecting a callback function, but got " + callback);
190
-
191
- if (this._disconnecting) {
192
- callback();
193
- return;
194
- }
195
-
196
- assert(!this._disconnecting, "TCP Transport has already been disconnected");
197
- this._disconnecting = true;
198
-
199
- // xx assert(!this._theCallback,
200
- // "disconnect shall not be called while the 'one time message receiver' is in operation");
201
- this._cleanup_timers();
202
-
203
- if (this._socket) {
204
- this._socket.end();
205
- this._socket.destroy();
206
- // xx this._socket.removeAllListeners();
207
- this._socket = null;
208
- }
209
- this.on_socket_ended(null);
210
- setImmediate(() => {
211
- callback();
212
- });
213
- }
214
-
215
- public isValid(): boolean {
216
- return this._socket !== null && !this._socket.destroyed && !this._disconnecting;
217
- }
218
-
219
- protected _write_chunk(messageChunk: Buffer): void {
220
- if (this._socket !== null) {
221
- this.bytesWritten += messageChunk.length;
222
- this.chunkWrittenCount++;
223
- this._socket.write(messageChunk);
224
- }
225
- }
226
-
227
- protected on_socket_ended(err: Error | null): void {
228
- assert(!this._onSocketEndedHasBeenCalled);
229
- this._onSocketEndedHasBeenCalled = true; // we don't want to send close event twice ...
230
- /**
231
- * notify the observers that the transport layer has been disconnected.
232
- * @event close
233
- * @param err the Error object or null
234
- */
235
- this.emit("close", err || null);
236
- }
237
-
238
- /**
239
- * @method _install_socket
240
- * @param socket {Socket}
241
- * @protected
242
- */
243
- protected _install_socket(socket: Socket): void {
244
- assert(socket);
245
- this._socket = socket;
246
- if (doDebug) {
247
- debugLog(" TCP_transport#_install_socket ", this.name);
248
- }
249
-
250
- // install packet assembler ...
251
- this.packetAssembler = new PacketAssembler({
252
- readMessageFunc: readRawMessageHeader,
253
-
254
- minimumSizeInBytes: this.headerSize
255
- });
256
-
257
- /* istanbul ignore next */
258
- if (!this.packetAssembler) {
259
- throw new Error("Internal Error");
260
- }
261
- this.packetAssembler.on("message", (messageChunk: Buffer) => this._on_message_received(messageChunk));
262
-
263
- this._socket
264
- .on("data", (data: Buffer) => this._on_socket_data(data))
265
- .on("close", (hadError) => this._on_socket_close(hadError))
266
- .on("end", (err: Error) => this._on_socket_end(err))
267
- .on("error", (err: Error) => this._on_socket_error(err));
268
-
269
- // set socket timeout
270
- debugLog(" TCP_transport#install => setting " + this.name + " _socket.setTimeout to ", this.timeout);
271
-
272
- // let use a large timeout here to make sure that we not conflict with our internal timeout
273
- this._socket!.setTimeout(this.timeout + 2000, () => {
274
- debugLog(` _socket ${this.name} has timed out (timeout = ${this.timeout})`);
275
- this.prematureTerminate(new Error("INTERNAL_EPIPE timeout=" + this.timeout));
276
- });
277
- }
278
-
279
- public prematureTerminate(err: Error): void {
280
- debugLog("prematureTerminate", err ? err.message : "");
281
- if (this._socket) {
282
- err.message = "EPIPE_" + err.message;
283
- // we consider this as an error
284
- const _s = this._socket;
285
- _s.end();
286
- _s.destroy(); // new Error("Socket has timed out"));
287
- _s.emit("error", err);
288
- this._socket = null;
289
- this.dispose();
290
- _s.removeAllListeners();
291
- }
292
- }
293
- /**
294
- * @method _install_one_time_message_receiver
295
- *
296
- * install a one time message receiver callback
297
- *
298
- * Rules:
299
- * * TCP_transport will not emit the ```message``` event, while the "one time message receiver" is in operation.
300
- * * the TCP_transport will wait for the next complete message chunk and call the provided callback func
301
- * ```callback(null,messageChunk);```
302
- *
303
- * if a messageChunk is not received within ```TCP_transport.timeout``` or if the underlying socket reports
304
- * an error, the callback function will be called with an Error.
305
- *
306
- */
307
- protected _install_one_time_message_receiver(callback: CallbackWithData): void {
308
- assert(!this._theCallback, "callback already set");
309
- assert(typeof callback === "function");
310
- this._theCallback = callback;
311
- this._start_one_time_message_receiver();
312
- }
313
-
314
- private _fulfill_pending_promises(err: Error | null, data?: Buffer): boolean {
315
- this._cleanup_timers();
316
-
317
- if (this._socket && this._on_error_during_one_time_message_receiver) {
318
- this._socket.removeListener("close", this._on_error_during_one_time_message_receiver);
319
- this._on_error_during_one_time_message_receiver = null;
320
- }
321
-
322
- const callback = this._theCallback;
323
- this._theCallback = undefined;
324
-
325
- if (callback) {
326
- callback(err, data);
327
- return true;
328
- }
329
- return false;
330
- }
331
-
332
- private _on_message_received(messageChunk: Buffer) {
333
- const hasCallback = this._fulfill_pending_promises(null, messageChunk);
334
- this.chunkReadCount++;
335
- if (!hasCallback) {
336
- /**
337
- * notify the observers that a message chunk has been received
338
- * @event message
339
- * @param message_chunk the message chunk
340
- */
341
- this.emit("message", messageChunk);
342
- }
343
- }
344
-
345
- private _cleanup_timers() {
346
- if (this._timerId) {
347
- clearTimeout(this._timerId);
348
- this._timerId = null;
349
- }
350
- }
351
-
352
- private _start_one_time_message_receiver() {
353
- assert(!this._timerId, "timer already started");
354
-
355
- // Setup timeout detection timer ....
356
- this._timerId = setTimeout(() => {
357
- this._timerId = null;
358
- this._fulfill_pending_promises(new Error(`Timeout in waiting for data on socket ( timeout was = ${this.timeout} ms)`));
359
- }, this.timeout);
360
-
361
- // also monitored
362
- if (this._socket) {
363
- // to do = intercept socket error as well
364
- this._on_error_during_one_time_message_receiver = (err?: Error) => {
365
- this._fulfill_pending_promises(
366
- new Error(`ERROR in waiting for data on socket ( timeout was = ${this.timeout} ms) ` + err?.message)
367
- );
368
- };
369
- this._socket.on("close", this._on_error_during_one_time_message_receiver);
370
- }
371
- }
372
-
373
- private on_socket_closed(err?: Error) {
374
- if (this._onSocketClosedHasBeenCalled) {
375
- return;
376
- }
377
- assert(!this._onSocketClosedHasBeenCalled);
378
- this._onSocketClosedHasBeenCalled = true; // we don't want to send close event twice ...
379
- /**
380
- * notify the observers that the transport layer has been disconnected.
381
- * @event socket_closed
382
- * @param err the Error object or null
383
- */
384
- this.emit("socket_closed", err || null);
385
- }
386
-
387
- private _on_socket_data(data: Buffer): void {
388
- if (!this.packetAssembler) {
389
- throw new Error("internal Error");
390
- }
391
- this.bytesRead += data.length;
392
- if (data.length > 0) {
393
- this.packetAssembler.feed(data);
394
- }
395
- }
396
-
397
- private _on_socket_close(hadError: boolean) {
398
- // istanbul ignore next
399
- if (doDebug) {
400
- debugLog(chalk.red(" SOCKET CLOSE : "), chalk.yellow("had_error ="), chalk.cyan(hadError.toString()), this.name);
401
- }
402
- if (this._socket) {
403
- debugLog(
404
- " remote address = ",
405
- this._socket.remoteAddress,
406
- " ",
407
- this._socket.remoteFamily,
408
- " ",
409
- this._socket.remotePort
410
- );
411
- }
412
- if (hadError) {
413
- if (this._socket) {
414
- this._socket.destroy();
415
- }
416
- }
417
- const err = hadError ? new Error("ERROR IN SOCKET " + hadError.toString()) : undefined;
418
- this.on_socket_closed(err);
419
- this.dispose();
420
- }
421
-
422
- private _on_socket_ended_message(err?: Error) {
423
- if (this._disconnecting) {
424
- return;
425
- }
426
-
427
- debugLog(chalk.red("Transport Connection ended") + " " + this.name);
428
- assert(!this._disconnecting);
429
- err = err || new Error("_socket has been disconnected by third party");
430
-
431
- this.on_socket_ended(err);
432
-
433
- this._disconnecting = true;
434
-
435
- debugLog(" bytesRead = ", this.bytesRead);
436
- debugLog(" bytesWritten = ", this.bytesWritten);
437
- this._fulfill_pending_promises(new Error("Connection aborted - ended by server : " + (err ? err.message : "")));
438
- }
439
-
440
- private _on_socket_end(err: Error) {
441
- // istanbul ignore next
442
- if (doDebug) {
443
- debugLog(chalk.red(" SOCKET END : err="), chalk.yellow(err ? err.message : "null"), this.name);
444
- }
445
- this._on_socket_ended_message(err);
446
- }
447
-
448
- private _on_socket_error(err: Error) {
449
- // istanbul ignore next
450
- if (doDebug) {
451
- debugLog(chalk.red(" SOCKET ERROR : "), chalk.yellow(err.message), this.name);
452
- }
453
- // node The "close" event will be called directly following this event.
454
- }
455
- }
1
+ /**
2
+ * @module node-opcua-transport
3
+ */
4
+ import { EventEmitter } from "events";
5
+ import { Socket } from "net";
6
+
7
+ import * as chalk from "chalk";
8
+
9
+ import { assert } from "node-opcua-assert";
10
+ import { createFastUninitializedBuffer } from "node-opcua-buffer-utils";
11
+ import * as debug from "node-opcua-debug";
12
+ import { ObjectRegistry } from "node-opcua-object-registry";
13
+ import { PacketAssembler } from "node-opcua-packet-assembler";
14
+ import { ErrorCallback, CallbackWithData } from "node-opcua-status-code";
15
+
16
+ import { readRawMessageHeader } from "./message_builder_base";
17
+ import { writeTCPMessageHeader } from "./tools";
18
+
19
+ const debugLog = debug.make_debugLog(__filename);
20
+ const doDebug = debug.checkDebugFlag(__filename);
21
+ const errorLog = debug.make_errorLog(__filename);
22
+
23
+ export interface MockSocket {
24
+ invalid?: boolean;
25
+ [key: string]: any;
26
+ }
27
+ let fakeSocket: MockSocket = { invalid: true };
28
+
29
+ export function setFakeTransport(mockSocket: MockSocket): void {
30
+ fakeSocket = mockSocket;
31
+ }
32
+
33
+ export function getFakeTransport(): any {
34
+ if (fakeSocket.invalid) {
35
+ throw new Error("getFakeTransport: setFakeTransport must be called first - BadProtocolVersionUnsupported");
36
+ }
37
+ return fakeSocket;
38
+ }
39
+
40
+ let counter = 0;
41
+
42
+ export interface TCP_transport {
43
+ on(eventName: "message", eventHandler: (message: Buffer) => void): this;
44
+ on(eventName: "socket_closed", eventHandler: (err: Error | null) => void): this;
45
+ on(eventName: "close", eventHandler: (err: Error | null) => void): this;
46
+
47
+ once(eventName: "message", eventHandler: (message: Buffer) => void): this;
48
+ once(eventName: "socket_closed", eventHandler: (err: Error | null) => void): this;
49
+ once(eventName: "close", eventHandler: (err: Error | null) => void): this;
50
+ }
51
+ // tslint:disable:class-name
52
+ export class TCP_transport extends EventEmitter {
53
+ private static registry = new ObjectRegistry();
54
+
55
+ /**
56
+ * indicates the version number of the OPCUA protocol used
57
+ * @default 0
58
+ */
59
+ public protocolVersion: number;
60
+
61
+ public bytesWritten: number;
62
+ public bytesRead: number;
63
+ public chunkWrittenCount: number;
64
+ public chunkReadCount: number;
65
+ public name: string;
66
+
67
+ public _socket: Socket | null;
68
+
69
+ /**
70
+ * the size of the header in bytes
71
+ * @default 8
72
+ */
73
+ private readonly headerSize: 8;
74
+ private _disconnecting: boolean;
75
+ private _timerId: NodeJS.Timer | null;
76
+ private _onSocketClosedHasBeenCalled: boolean;
77
+ private _onSocketEndedHasBeenCalled: boolean;
78
+ private _theCallback?: CallbackWithData;
79
+ private _on_error_during_one_time_message_receiver: any;
80
+ private _pendingBuffer?: any;
81
+ private packetAssembler?: PacketAssembler;
82
+ private _timeout: number;
83
+
84
+ constructor() {
85
+ super();
86
+
87
+ this.name = this.constructor.name + counter;
88
+ counter += 1;
89
+
90
+ this._timerId = null;
91
+ this._timeout = 30000; // 30 seconds timeout
92
+ this._socket = null;
93
+ this.headerSize = 8;
94
+ this.protocolVersion = 0;
95
+
96
+ this._disconnecting = false;
97
+ this._pendingBuffer = undefined;
98
+
99
+ this.bytesWritten = 0;
100
+ this.bytesRead = 0;
101
+
102
+ this._theCallback = undefined;
103
+ this.chunkWrittenCount = 0;
104
+ this.chunkReadCount = 0;
105
+
106
+ this._onSocketClosedHasBeenCalled = false;
107
+ this._onSocketEndedHasBeenCalled = false;
108
+ TCP_transport.registry.register(this);
109
+ }
110
+
111
+ public get timeout(): number {
112
+ return this._timeout;
113
+ }
114
+ public set timeout(value: number) {
115
+ debugLog("Setting socket " + this.name + " timeout = ", value);
116
+ this._timeout = value;
117
+ }
118
+ public dispose(): void {
119
+ this._cleanup_timers();
120
+ assert(!this._timerId);
121
+ if (this._socket) {
122
+ this._socket.destroy();
123
+ this._socket.removeAllListeners();
124
+ this._socket = null;
125
+ }
126
+ TCP_transport.registry.unregister(this);
127
+ }
128
+
129
+ /**
130
+ * ```createChunk``` is used to construct a pre-allocated chunk to store up to ```length``` bytes of data.
131
+ * The created chunk includes a prepended header for ```chunk_type``` of size ```self.headerSize```.
132
+ *
133
+ * @method createChunk
134
+ * @param msgType
135
+ * @param chunkType {String} chunk type. should be 'F' 'C' or 'A'
136
+ * @param length
137
+ * @return a buffer object with the required length representing the chunk.
138
+ *
139
+ * Note:
140
+ * - only one chunk can be created at a time.
141
+ * - a created chunk should be committed using the ```write``` method before an other one is created.
142
+ */
143
+ public createChunk(msgType: string, chunkType: string, length: number): Buffer {
144
+ assert(msgType === "MSG");
145
+ assert(this._pendingBuffer === undefined, "createChunk has already been called ( use write first)");
146
+
147
+ const totalLength = length + this.headerSize;
148
+ const buffer = createFastUninitializedBuffer(totalLength);
149
+ writeTCPMessageHeader("MSG", chunkType, totalLength, buffer);
150
+ this._pendingBuffer = buffer;
151
+
152
+ return buffer;
153
+ }
154
+
155
+ /**
156
+ * write the message_chunk on the socket.
157
+ * @method write
158
+ * @param messageChunk
159
+ *
160
+ * Notes:
161
+ * - the message chunk must have been created by ```createChunk```.
162
+ * - once a message chunk has been written, it is possible to call ```createChunk``` again.
163
+ *
164
+ */
165
+ public write(messageChunk: Buffer): void {
166
+ assert(
167
+ this._pendingBuffer === undefined || this._pendingBuffer === messageChunk,
168
+ " write should be used with buffer created by createChunk"
169
+ );
170
+ const header = readRawMessageHeader(messageChunk);
171
+ assert(header.length === messageChunk.length);
172
+ assert(["F", "C", "A"].indexOf(header.messageHeader.isFinal) !== -1);
173
+ this._write_chunk(messageChunk);
174
+ this._pendingBuffer = undefined;
175
+ }
176
+
177
+ public get isDisconnecting(): boolean {
178
+ return this._disconnecting;
179
+ }
180
+ /**
181
+ * disconnect the TCP layer and close the underlying socket.
182
+ * The ```"close"``` event will be emitted to the observers with err=null.
183
+ *
184
+ * @method disconnect
185
+ * @async
186
+ * @param callback
187
+ */
188
+ public disconnect(callback: ErrorCallback): void {
189
+ assert(typeof callback === "function", "expecting a callback function, but got " + callback);
190
+
191
+ if (this._disconnecting) {
192
+ callback();
193
+ return;
194
+ }
195
+
196
+ assert(!this._disconnecting, "TCP Transport has already been disconnected");
197
+ this._disconnecting = true;
198
+
199
+ // xx assert(!this._theCallback,
200
+ // "disconnect shall not be called while the 'one time message receiver' is in operation");
201
+ this._cleanup_timers();
202
+
203
+ if (this._socket) {
204
+ this._socket.end();
205
+ this._socket.destroy();
206
+ // xx this._socket.removeAllListeners();
207
+ this._socket = null;
208
+ }
209
+ this.on_socket_ended(null);
210
+ setImmediate(() => {
211
+ callback();
212
+ });
213
+ }
214
+
215
+ public isValid(): boolean {
216
+ return this._socket !== null && !this._socket.destroyed && !this._disconnecting;
217
+ }
218
+
219
+ protected _write_chunk(messageChunk: Buffer): void {
220
+ if (this._socket !== null) {
221
+ this.bytesWritten += messageChunk.length;
222
+ this.chunkWrittenCount++;
223
+ this._socket.write(messageChunk);
224
+ }
225
+ }
226
+
227
+ protected on_socket_ended(err: Error | null): void {
228
+ assert(!this._onSocketEndedHasBeenCalled);
229
+ this._onSocketEndedHasBeenCalled = true; // we don't want to send close event twice ...
230
+ /**
231
+ * notify the observers that the transport layer has been disconnected.
232
+ * @event close
233
+ * @param err the Error object or null
234
+ */
235
+ this.emit("close", err || null);
236
+ }
237
+
238
+ /**
239
+ * @method _install_socket
240
+ * @param socket {Socket}
241
+ * @protected
242
+ */
243
+ protected _install_socket(socket: Socket): void {
244
+ assert(socket);
245
+ this._socket = socket;
246
+ if (doDebug) {
247
+ debugLog(" TCP_transport#_install_socket ", this.name);
248
+ }
249
+
250
+ // install packet assembler ...
251
+ this.packetAssembler = new PacketAssembler({
252
+ readMessageFunc: readRawMessageHeader,
253
+
254
+ minimumSizeInBytes: this.headerSize
255
+ });
256
+
257
+ /* istanbul ignore next */
258
+ if (!this.packetAssembler) {
259
+ throw new Error("Internal Error");
260
+ }
261
+ this.packetAssembler.on("message", (messageChunk: Buffer) => this._on_message_received(messageChunk));
262
+
263
+ this._socket
264
+ .on("data", (data: Buffer) => this._on_socket_data(data))
265
+ .on("close", (hadError) => this._on_socket_close(hadError))
266
+ .on("end", (err: Error) => this._on_socket_end(err))
267
+ .on("error", (err: Error) => this._on_socket_error(err));
268
+
269
+ // set socket timeout
270
+ debugLog(" TCP_transport#install => setting " + this.name + " _socket.setTimeout to ", this.timeout);
271
+
272
+ // let use a large timeout here to make sure that we not conflict with our internal timeout
273
+ this._socket!.setTimeout(this.timeout + 2000, () => {
274
+ debugLog(` _socket ${this.name} has timed out (timeout = ${this.timeout})`);
275
+ this.prematureTerminate(new Error("INTERNAL_EPIPE timeout=" + this.timeout));
276
+ });
277
+ }
278
+
279
+ public prematureTerminate(err: Error): void {
280
+ debugLog("prematureTerminate", err ? err.message : "");
281
+ if (this._socket) {
282
+ err.message = "EPIPE_" + err.message;
283
+ // we consider this as an error
284
+ const _s = this._socket;
285
+ _s.end();
286
+ _s.destroy(); // new Error("Socket has timed out"));
287
+ _s.emit("error", err);
288
+ this._socket = null;
289
+ this.dispose();
290
+ _s.removeAllListeners();
291
+ }
292
+ }
293
+ /**
294
+ * @method _install_one_time_message_receiver
295
+ *
296
+ * install a one time message receiver callback
297
+ *
298
+ * Rules:
299
+ * * TCP_transport will not emit the ```message``` event, while the "one time message receiver" is in operation.
300
+ * * the TCP_transport will wait for the next complete message chunk and call the provided callback func
301
+ * ```callback(null,messageChunk);```
302
+ *
303
+ * if a messageChunk is not received within ```TCP_transport.timeout``` or if the underlying socket reports
304
+ * an error, the callback function will be called with an Error.
305
+ *
306
+ */
307
+ protected _install_one_time_message_receiver(callback: CallbackWithData): void {
308
+ assert(!this._theCallback, "callback already set");
309
+ assert(typeof callback === "function");
310
+ this._theCallback = callback;
311
+ this._start_one_time_message_receiver();
312
+ }
313
+
314
+ private _fulfill_pending_promises(err: Error | null, data?: Buffer): boolean {
315
+ this._cleanup_timers();
316
+
317
+ if (this._socket && this._on_error_during_one_time_message_receiver) {
318
+ this._socket.removeListener("close", this._on_error_during_one_time_message_receiver);
319
+ this._on_error_during_one_time_message_receiver = null;
320
+ }
321
+
322
+ const callback = this._theCallback;
323
+ this._theCallback = undefined;
324
+
325
+ if (callback) {
326
+ callback(err, data);
327
+ return true;
328
+ }
329
+ return false;
330
+ }
331
+
332
+ private _on_message_received(messageChunk: Buffer) {
333
+ const hadCallback = this._fulfill_pending_promises(null, messageChunk);
334
+ this.chunkReadCount++;
335
+ if (!hadCallback) {
336
+ /**
337
+ * notify the observers that a message chunk has been received
338
+ * @event message
339
+ * @param message_chunk the message chunk
340
+ */
341
+ this.emit("message", messageChunk);
342
+ }
343
+ }
344
+
345
+ private _cleanup_timers() {
346
+ if (this._timerId) {
347
+ clearTimeout(this._timerId);
348
+ this._timerId = null;
349
+ }
350
+ }
351
+
352
+ private _start_one_time_message_receiver() {
353
+ assert(!this._timerId, "timer already started");
354
+
355
+ // Setup timeout detection timer ....
356
+ this._timerId = setTimeout(() => {
357
+ this._timerId = null;
358
+ this._fulfill_pending_promises(new Error(`Timeout in waiting for data on socket ( timeout was = ${this.timeout} ms)`));
359
+ }, this.timeout);
360
+
361
+ // also monitored
362
+ if (this._socket) {
363
+ // to do = intercept socket error as well
364
+ this._on_error_during_one_time_message_receiver = (err?: Error) => {
365
+ this._fulfill_pending_promises(
366
+ new Error(`ERROR in waiting for data on socket ( timeout was = ${this.timeout} ms) ` + err?.message)
367
+ );
368
+ };
369
+ this._socket.on("close", this._on_error_during_one_time_message_receiver);
370
+ }
371
+ }
372
+
373
+ private on_socket_closed(err?: Error) {
374
+ if (this._onSocketClosedHasBeenCalled) {
375
+ return;
376
+ }
377
+ assert(!this._onSocketClosedHasBeenCalled);
378
+ this._onSocketClosedHasBeenCalled = true; // we don't want to send close event twice ...
379
+ /**
380
+ * notify the observers that the transport layer has been disconnected.
381
+ * @event socket_closed
382
+ * @param err the Error object or null
383
+ */
384
+ this.emit("socket_closed", err || null);
385
+ }
386
+
387
+ private _on_socket_data(data: Buffer): void {
388
+ if (!this.packetAssembler) {
389
+ throw new Error("internal Error");
390
+ }
391
+ this.bytesRead += data.length;
392
+ if (data.length > 0) {
393
+ this.packetAssembler.feed(data);
394
+ }
395
+ }
396
+
397
+ private _on_socket_close(hadError: boolean) {
398
+ // istanbul ignore next
399
+ if (doDebug) {
400
+ debugLog(chalk.red(" SOCKET CLOSE : "), chalk.yellow("had_error ="), chalk.cyan(hadError.toString()), this.name);
401
+ }
402
+ if (this._socket) {
403
+ debugLog(
404
+ " remote address = ",
405
+ this._socket.remoteAddress,
406
+ " ",
407
+ this._socket.remoteFamily,
408
+ " ",
409
+ this._socket.remotePort
410
+ );
411
+ }
412
+ if (hadError) {
413
+ if (this._socket) {
414
+ this._socket.destroy();
415
+ }
416
+ }
417
+ const err = hadError ? new Error("ERROR IN SOCKET " + hadError.toString()) : undefined;
418
+ this.on_socket_closed(err);
419
+ this.dispose();
420
+ }
421
+
422
+ private _on_socket_ended_message(err?: Error) {
423
+ if (this._disconnecting) {
424
+ return;
425
+ }
426
+
427
+ debugLog(chalk.red("Transport Connection ended") + " " + this.name);
428
+ assert(!this._disconnecting);
429
+ err = err || new Error("_socket has been disconnected by third party");
430
+
431
+ this.on_socket_ended(err);
432
+
433
+ this._disconnecting = true;
434
+
435
+ debugLog(" bytesRead = ", this.bytesRead);
436
+ debugLog(" bytesWritten = ", this.bytesWritten);
437
+ this._fulfill_pending_promises(new Error("Connection aborted - ended by server : " + (err ? err.message : "")));
438
+ }
439
+
440
+ private _on_socket_end(err: Error) {
441
+ // istanbul ignore next
442
+ if (doDebug) {
443
+ debugLog(chalk.red(" SOCKET END : err="), chalk.yellow(err ? err.message : "null"), this.name);
444
+ }
445
+ this._on_socket_ended_message(err);
446
+ }
447
+
448
+ private _on_socket_error(err: Error) {
449
+ // istanbul ignore next
450
+ if (doDebug) {
451
+ debugLog(chalk.red(" SOCKET ERROR : "), chalk.yellow(err.message), this.name);
452
+ }
453
+ // node The "close" event will be called directly following this event.
454
+ }
455
+ }