@astm-e1394/net 0.0.0-stage → 1.0.0-beta.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.
- package/LICENSE +21 -0
- package/README.md +89 -2
- package/index.d.ts +4 -0
- package/index.js +4 -0
- package/package.json +25 -3
- package/tcp-client-connection.d.ts +37 -0
- package/tcp-client-connection.js +108 -0
- package/tcp-connection.d.ts +33 -0
- package/tcp-connection.js +60 -0
- package/tcp-server.d.ts +49 -0
- package/tcp-server.js +78 -0
- package/tcp-socket-connection.d.ts +17 -0
- package/tcp-socket-connection.js +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Panates
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,90 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @astm-e1394/net
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Connects to laboratory instruments over TCP for ASTM E1394 messages.
|
|
4
|
+
|
|
5
|
+
[![NPM Version][npm-image]][npm-url]
|
|
6
|
+
[![NPM Downloads][downloads-image]][downloads-url]
|
|
7
|
+
[![CI Tests][ci-test-image]][ci-test-url]
|
|
8
|
+
[![Test Coverage][coveralls-image]][coveralls-url]
|
|
9
|
+
|
|
10
|
+
[npm-image]: https://img.shields.io/npm/v/@astm-e1394/net
|
|
11
|
+
[npm-url]: https://npmjs.org/package/@astm-e1394/net
|
|
12
|
+
[downloads-image]: https://img.shields.io/npm/dm/@astm-e1394/net.svg
|
|
13
|
+
[downloads-url]: https://npmjs.org/package/@astm-e1394/net
|
|
14
|
+
[ci-test-image]: https://github.com/panates/astm-e1394/actions/workflows/test.yml/badge.svg
|
|
15
|
+
[ci-test-url]: https://github.com/panates/astm-e1394/actions/workflows/test.yml
|
|
16
|
+
[coveralls-image]: https://img.shields.io/coveralls/panates/astm-e1394/dev.svg
|
|
17
|
+
[coveralls-url]: https://coveralls.io/r/panates/astm-e1394
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npm install @astm-e1394/core@beta @astm-e1394/net@beta
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
TCP connections for [`@astm-e1394/core`](https://www.npmjs.com/package/@astm-e1394/core)'s `AstmLink`, which runs the ASTM E1381 (LIS1-A) protocol and the message handlers. The core README describes the link, its handlers and its options.
|
|
26
|
+
|
|
27
|
+
## Instruments that connect to the LIS
|
|
28
|
+
|
|
29
|
+
`TcpServer` listens, makes an `AstmLink` for each connection it accepts, and serves every link with the handlers added to it:
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
import { TcpServer } from '@astm-e1394/net';
|
|
33
|
+
|
|
34
|
+
const server = new TcpServer({ link: { role: 'host', ackDelay: 50 } });
|
|
35
|
+
|
|
36
|
+
server.use('result', async req => {
|
|
37
|
+
await store(req.message);
|
|
38
|
+
});
|
|
39
|
+
server.use('query', async (req, res) => {
|
|
40
|
+
res.message = await ordersFor(req.message.get('Q-3-2'));
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
server.on('link', link => {
|
|
44
|
+
console.log('connected:', link.connection.description); // tcp://10.0.0.5:51234
|
|
45
|
+
link.on('error', err => console.error(err));
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
await server.listen(5000);
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
- `server.links` holds the links of the connections open now; a link leaves it when its connection closes.
|
|
52
|
+
- `maxConnections` refuses connections beyond a number.
|
|
53
|
+
- `server.close()` stops listening and closes every connection.
|
|
54
|
+
|
|
55
|
+
## Connecting to an instrument
|
|
56
|
+
|
|
57
|
+
`TcpClientConnection` connects to an instrument, or to a serial-to-TCP converter, and connects again when the connection drops:
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
import { AstmLink } from '@astm-e1394/core';
|
|
61
|
+
import { TcpClientConnection } from '@astm-e1394/net';
|
|
62
|
+
|
|
63
|
+
const link = new AstmLink(
|
|
64
|
+
new TcpClientConnection({ host: '10.0.0.5', port: 5000, reconnectDelay: 5000 }),
|
|
65
|
+
{ framing: 'none' }, // for an instrument that sends bare records over TCP
|
|
66
|
+
);
|
|
67
|
+
link.use('result', async req => store(req.message));
|
|
68
|
+
await link.open();
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
- `open()` rejects when the first attempt fails, and goes on trying in the background every `reconnectDelay` (5 s; 0 turns it off). The link emits `open` when the connection gets through. `close()` stops the attempts.
|
|
72
|
+
- `connectTimeout` (10 s) bounds one attempt. `keepAlive` (30 s, or `false`) sets TCP keep-alive, so that an instrument that vanished without closing is noticed.
|
|
73
|
+
|
|
74
|
+
## A socket of your own
|
|
75
|
+
|
|
76
|
+
`TcpSocketConnection` uses a socket made elsewhere as it is: one your code connected, is still connecting, or took from a server of its own.
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
import { connect } from 'node:net';
|
|
80
|
+
import { TcpSocketConnection } from '@astm-e1394/net';
|
|
81
|
+
|
|
82
|
+
const link = new AstmLink(new TcpSocketConnection(connect(5000, '10.0.0.5')));
|
|
83
|
+
await link.open(); // waits for the socket to connect
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
It does not reconnect: once the socket closes, a new socket makes a new connection.
|
|
87
|
+
|
|
88
|
+
## License
|
|
89
|
+
|
|
90
|
+
[MIT](https://github.com/panates/astm-e1394/blob/main/LICENSE)
|
package/index.d.ts
ADDED
package/index.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astm-e1394/net",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"description": "Connects to laboratory instruments over TCP for ASTM E1394 messages.",
|
|
4
|
+
"version": "1.0.0-beta.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./index.d.ts",
|
|
10
|
+
"default": "./index.js"
|
|
11
|
+
},
|
|
12
|
+
"./package.json": "./package.json"
|
|
13
|
+
},
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=22"
|
|
16
|
+
},
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/panates/astm-e1394.git",
|
|
20
|
+
"directory": "packages/core/net"
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@astm-e1394/core": "^1.0.0-beta.0"
|
|
27
|
+
}
|
|
6
28
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { TcpConnection, type TcpSocketOptions } from './tcp-connection.js';
|
|
2
|
+
export interface TcpClientConnectionOptions extends TcpSocketOptions {
|
|
3
|
+
host: string;
|
|
4
|
+
port: number;
|
|
5
|
+
/**
|
|
6
|
+
* The wait in ms before connecting again after the connection drops or an
|
|
7
|
+
* attempt fails; 0 turns reconnecting off. Default: 5 s.
|
|
8
|
+
*/
|
|
9
|
+
reconnectDelay?: number;
|
|
10
|
+
/** The time in ms one attempt to connect may take. Default: 10 s. */
|
|
11
|
+
connectTimeout?: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Connects to an instrument, or to a serial-to-TCP converter, and reconnects
|
|
15
|
+
* when the connection drops.
|
|
16
|
+
*
|
|
17
|
+
* open() resolves once connected. When the first attempt fails it rejects;
|
|
18
|
+
* with reconnecting on, the connection keeps trying in the background and
|
|
19
|
+
* emits 'open' when it gets through. Failed attempts after the first are
|
|
20
|
+
* emitted as 'error'. close() stops reconnecting.
|
|
21
|
+
*/
|
|
22
|
+
export declare class TcpClientConnection extends TcpConnection {
|
|
23
|
+
readonly options: Readonly<TcpClientConnectionOptions>;
|
|
24
|
+
readonly description: string;
|
|
25
|
+
/** Between open() and close(): the connection is to be kept up */
|
|
26
|
+
protected _wanted: boolean;
|
|
27
|
+
protected _connecting?: Promise<void>;
|
|
28
|
+
protected _reconnectTimer?: NodeJS.Timeout;
|
|
29
|
+
constructor(options: TcpClientConnectionOptions);
|
|
30
|
+
get reconnectDelay(): number;
|
|
31
|
+
open(): Promise<void>;
|
|
32
|
+
close(): Promise<void>;
|
|
33
|
+
protected _connect(): Promise<void>;
|
|
34
|
+
protected _onSocketClose(): void;
|
|
35
|
+
protected _scheduleReconnect(): void;
|
|
36
|
+
protected _clearReconnect(): void;
|
|
37
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { connect } from 'node:net';
|
|
2
|
+
import { TcpConnection } from './tcp-connection.js';
|
|
3
|
+
/**
|
|
4
|
+
* Connects to an instrument, or to a serial-to-TCP converter, and reconnects
|
|
5
|
+
* when the connection drops.
|
|
6
|
+
*
|
|
7
|
+
* open() resolves once connected. When the first attempt fails it rejects;
|
|
8
|
+
* with reconnecting on, the connection keeps trying in the background and
|
|
9
|
+
* emits 'open' when it gets through. Failed attempts after the first are
|
|
10
|
+
* emitted as 'error'. close() stops reconnecting.
|
|
11
|
+
*/
|
|
12
|
+
export class TcpClientConnection extends TcpConnection {
|
|
13
|
+
options;
|
|
14
|
+
description;
|
|
15
|
+
/** Between open() and close(): the connection is to be kept up */
|
|
16
|
+
_wanted = false;
|
|
17
|
+
_connecting;
|
|
18
|
+
_reconnectTimer;
|
|
19
|
+
constructor(options) {
|
|
20
|
+
super();
|
|
21
|
+
this.options = { ...options };
|
|
22
|
+
this.description = `tcp://${options.host}:${options.port}`;
|
|
23
|
+
}
|
|
24
|
+
get reconnectDelay() {
|
|
25
|
+
return this.options.reconnectDelay ?? 5000;
|
|
26
|
+
}
|
|
27
|
+
async open() {
|
|
28
|
+
this._wanted = true;
|
|
29
|
+
if (this.isOpen)
|
|
30
|
+
return;
|
|
31
|
+
this._clearReconnect();
|
|
32
|
+
try {
|
|
33
|
+
await this._connect();
|
|
34
|
+
}
|
|
35
|
+
catch (e) {
|
|
36
|
+
this._scheduleReconnect();
|
|
37
|
+
throw e;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
async close() {
|
|
41
|
+
this._wanted = false;
|
|
42
|
+
this._clearReconnect();
|
|
43
|
+
const connecting = this._connecting;
|
|
44
|
+
if (connecting)
|
|
45
|
+
await connecting.catch(() => undefined);
|
|
46
|
+
await this._closeSocket();
|
|
47
|
+
}
|
|
48
|
+
_connect() {
|
|
49
|
+
if (this._connecting)
|
|
50
|
+
return this._connecting;
|
|
51
|
+
const promise = new Promise((resolve, reject) => {
|
|
52
|
+
const socket = connect({
|
|
53
|
+
host: this.options.host,
|
|
54
|
+
port: this.options.port,
|
|
55
|
+
timeout: this.options.connectTimeout ?? 10_000,
|
|
56
|
+
});
|
|
57
|
+
const fail = (err) => {
|
|
58
|
+
socket.destroy();
|
|
59
|
+
reject(err);
|
|
60
|
+
};
|
|
61
|
+
socket.once('error', fail);
|
|
62
|
+
socket.once('timeout', () => fail(new Error(`Connecting to ${this.description} timed out`)));
|
|
63
|
+
socket.once('connect', () => {
|
|
64
|
+
socket.removeListener('error', fail);
|
|
65
|
+
socket.removeAllListeners('timeout');
|
|
66
|
+
socket.setTimeout(0);
|
|
67
|
+
if (!this._wanted) {
|
|
68
|
+
/* close() was called while connecting */
|
|
69
|
+
socket.destroy();
|
|
70
|
+
return resolve();
|
|
71
|
+
}
|
|
72
|
+
this._attach(socket, this.options);
|
|
73
|
+
resolve();
|
|
74
|
+
this.emit('open');
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
this._connecting = promise;
|
|
78
|
+
const done = () => {
|
|
79
|
+
if (this._connecting === promise)
|
|
80
|
+
this._connecting = undefined;
|
|
81
|
+
};
|
|
82
|
+
promise.then(done, done);
|
|
83
|
+
return promise;
|
|
84
|
+
}
|
|
85
|
+
_onSocketClose() {
|
|
86
|
+
super._onSocketClose();
|
|
87
|
+
this._scheduleReconnect();
|
|
88
|
+
}
|
|
89
|
+
_scheduleReconnect() {
|
|
90
|
+
const delay = this.reconnectDelay;
|
|
91
|
+
if (!this._wanted || delay <= 0 || this._reconnectTimer)
|
|
92
|
+
return;
|
|
93
|
+
this._reconnectTimer = setTimeout(() => {
|
|
94
|
+
this._reconnectTimer = undefined;
|
|
95
|
+
if (!this._wanted || this.isOpen)
|
|
96
|
+
return;
|
|
97
|
+
this._connect().catch(err => {
|
|
98
|
+
this._emitError(err);
|
|
99
|
+
this._scheduleReconnect();
|
|
100
|
+
});
|
|
101
|
+
}, delay);
|
|
102
|
+
}
|
|
103
|
+
_clearReconnect() {
|
|
104
|
+
if (this._reconnectTimer)
|
|
105
|
+
clearTimeout(this._reconnectTimer);
|
|
106
|
+
this._reconnectTimer = undefined;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import type { Socket } from 'node:net';
|
|
3
|
+
import type { AstmConnection, AstmConnectionEvents } from '@astm-e1394/core';
|
|
4
|
+
/** Socket settings shared by the TCP connections */
|
|
5
|
+
export interface TcpSocketOptions {
|
|
6
|
+
/**
|
|
7
|
+
* TCP keep-alive, so that a peer that vanished without closing is noticed:
|
|
8
|
+
* the delay in ms before the first probe, or false to turn it off.
|
|
9
|
+
* Default: 30 s.
|
|
10
|
+
*/
|
|
11
|
+
keepAlive?: number | false;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* What the TCP connections share: one socket at a time, its bytes passed on
|
|
15
|
+
* as 'data', and its end passed on as 'close'.
|
|
16
|
+
*/
|
|
17
|
+
export declare abstract class TcpConnection extends EventEmitter<AstmConnectionEvents> implements AstmConnection {
|
|
18
|
+
protected _socket?: Socket;
|
|
19
|
+
abstract readonly description: string;
|
|
20
|
+
abstract open(): Promise<void>;
|
|
21
|
+
abstract close(): Promise<void>;
|
|
22
|
+
get isOpen(): boolean;
|
|
23
|
+
/** The socket in use, while there is one */
|
|
24
|
+
get socket(): Socket | undefined;
|
|
25
|
+
write(data: Buffer): Promise<void>;
|
|
26
|
+
/** Takes a connected socket into use; emits 'close' once it ends */
|
|
27
|
+
protected _attach(socket: Socket, options: TcpSocketOptions): void;
|
|
28
|
+
protected _onSocketClose(): void;
|
|
29
|
+
/** Ends the socket once its data is written, and waits until it closes */
|
|
30
|
+
protected _closeSocket(): Promise<void>;
|
|
31
|
+
/** 'error' without a listener would throw in the socket's callback */
|
|
32
|
+
protected _emitError(error: Error): void;
|
|
33
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
/**
|
|
3
|
+
* What the TCP connections share: one socket at a time, its bytes passed on
|
|
4
|
+
* as 'data', and its end passed on as 'close'.
|
|
5
|
+
*/
|
|
6
|
+
export class TcpConnection extends EventEmitter {
|
|
7
|
+
_socket;
|
|
8
|
+
get isOpen() {
|
|
9
|
+
const socket = this._socket;
|
|
10
|
+
return !!socket && !socket.destroyed && socket.readyState === 'open';
|
|
11
|
+
}
|
|
12
|
+
/** The socket in use, while there is one */
|
|
13
|
+
get socket() {
|
|
14
|
+
return this._socket;
|
|
15
|
+
}
|
|
16
|
+
write(data) {
|
|
17
|
+
const socket = this._socket;
|
|
18
|
+
if (!this.isOpen || !socket) {
|
|
19
|
+
return Promise.reject(new Error(`${this.description} is not open`));
|
|
20
|
+
}
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
socket.write(data, err => (err ? reject(err) : resolve()));
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
/** Takes a connected socket into use; emits 'close' once it ends */
|
|
26
|
+
_attach(socket, options) {
|
|
27
|
+
this._socket = socket;
|
|
28
|
+
/* Control characters are single bytes: Nagle would hold ACKs back */
|
|
29
|
+
socket.setNoDelay(true);
|
|
30
|
+
const keepAlive = options.keepAlive ?? 30_000;
|
|
31
|
+
if (keepAlive !== false)
|
|
32
|
+
socket.setKeepAlive(true, keepAlive);
|
|
33
|
+
socket.on('data', (data) => this.emit('data', data));
|
|
34
|
+
socket.on('error', err => this._emitError(err));
|
|
35
|
+
socket.once('close', () => {
|
|
36
|
+
socket.removeAllListeners('data');
|
|
37
|
+
if (this._socket === socket)
|
|
38
|
+
this._socket = undefined;
|
|
39
|
+
this._onSocketClose();
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
_onSocketClose() {
|
|
43
|
+
this.emit('close');
|
|
44
|
+
}
|
|
45
|
+
/** Ends the socket once its data is written, and waits until it closes */
|
|
46
|
+
_closeSocket() {
|
|
47
|
+
const socket = this._socket;
|
|
48
|
+
if (!socket || socket.destroyed)
|
|
49
|
+
return Promise.resolve();
|
|
50
|
+
return new Promise(resolve => {
|
|
51
|
+
socket.once('close', () => resolve());
|
|
52
|
+
socket.end(() => socket.destroy());
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
/** 'error' without a listener would throw in the socket's callback */
|
|
56
|
+
_emitError(error) {
|
|
57
|
+
if (this.listenerCount('error'))
|
|
58
|
+
this.emit('error', error);
|
|
59
|
+
}
|
|
60
|
+
}
|
package/tcp-server.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { type AddressInfo, type Server, type Socket } from 'node:net';
|
|
3
|
+
import { type AstmHandler, AstmLink, type AstmLinkOptions, type AstmMessageFilter, AstmRouter } from '@astm-e1394/core';
|
|
4
|
+
import type { TcpSocketOptions } from './tcp-connection.js';
|
|
5
|
+
export interface TcpServerOptions extends TcpSocketOptions {
|
|
6
|
+
/** The options of the link made for each connection */
|
|
7
|
+
link?: AstmLinkOptions;
|
|
8
|
+
/** Connections beyond this many are refused. Default: no limit. */
|
|
9
|
+
maxConnections?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface TcpServerEvents {
|
|
12
|
+
listening: [];
|
|
13
|
+
/** A connection was accepted; its link is open */
|
|
14
|
+
link: [link: AstmLink];
|
|
15
|
+
close: [];
|
|
16
|
+
error: [error: Error];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Listens for instruments that connect to the LIS. Each socket it accepts
|
|
20
|
+
* becomes a TcpSocketConnection with an AstmLink of its own, made from the
|
|
21
|
+
* options given once, and is emitted as 'link'. The handlers added with
|
|
22
|
+
* use() serve every link. A link leaves the server's list when its
|
|
23
|
+
* connection closes.
|
|
24
|
+
*/
|
|
25
|
+
export declare class TcpServer extends EventEmitter<TcpServerEvents> {
|
|
26
|
+
readonly options: Readonly<TcpServerOptions>;
|
|
27
|
+
protected _server: Server;
|
|
28
|
+
protected _links: Set<AstmLink>;
|
|
29
|
+
/** The handlers shared by every link */
|
|
30
|
+
readonly router: AstmRouter;
|
|
31
|
+
constructor(options?: TcpServerOptions);
|
|
32
|
+
/**
|
|
33
|
+
* Adds a handler, or a router, shared by every link - or, given a filter
|
|
34
|
+
* first, for the messages it matches (see AstmRouter.use). Handlers added
|
|
35
|
+
* later serve the links already open too.
|
|
36
|
+
*/
|
|
37
|
+
use(handler: AstmHandler | AstmRouter, priority?: number): this;
|
|
38
|
+
use(filter: AstmMessageFilter, handler: AstmHandler | AstmRouter, priority?: number): this;
|
|
39
|
+
/** The links of the connections open now */
|
|
40
|
+
get links(): ReadonlySet<AstmLink>;
|
|
41
|
+
get listening(): boolean;
|
|
42
|
+
/** The address the server listens on, while it listens */
|
|
43
|
+
address(): AddressInfo | undefined;
|
|
44
|
+
/** Starts listening; port 0 takes a free port, which address() then gives */
|
|
45
|
+
listen(port: number, host?: string): Promise<void>;
|
|
46
|
+
/** Stops listening and closes every open connection */
|
|
47
|
+
close(): Promise<void>;
|
|
48
|
+
protected _accept(socket: Socket): void;
|
|
49
|
+
}
|
package/tcp-server.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { createServer, } from 'node:net';
|
|
3
|
+
import { AstmLink, AstmRouter, } from '@astm-e1394/core';
|
|
4
|
+
import { TcpSocketConnection } from './tcp-socket-connection.js';
|
|
5
|
+
/**
|
|
6
|
+
* Listens for instruments that connect to the LIS. Each socket it accepts
|
|
7
|
+
* becomes a TcpSocketConnection with an AstmLink of its own, made from the
|
|
8
|
+
* options given once, and is emitted as 'link'. The handlers added with
|
|
9
|
+
* use() serve every link. A link leaves the server's list when its
|
|
10
|
+
* connection closes.
|
|
11
|
+
*/
|
|
12
|
+
export class TcpServer extends EventEmitter {
|
|
13
|
+
options;
|
|
14
|
+
_server;
|
|
15
|
+
_links = new Set();
|
|
16
|
+
/** The handlers shared by every link */
|
|
17
|
+
router = new AstmRouter();
|
|
18
|
+
constructor(options) {
|
|
19
|
+
super();
|
|
20
|
+
this.options = { ...options };
|
|
21
|
+
this._server = createServer(socket => this._accept(socket));
|
|
22
|
+
if (this.options.maxConnections) {
|
|
23
|
+
this._server.maxConnections = this.options.maxConnections;
|
|
24
|
+
}
|
|
25
|
+
this._server.on('error', err => {
|
|
26
|
+
if (this.listenerCount('error'))
|
|
27
|
+
this.emit('error', err);
|
|
28
|
+
});
|
|
29
|
+
this._server.on('close', () => this.emit('close'));
|
|
30
|
+
}
|
|
31
|
+
use(...args) {
|
|
32
|
+
this.router.use(...args);
|
|
33
|
+
return this;
|
|
34
|
+
}
|
|
35
|
+
/** The links of the connections open now */
|
|
36
|
+
get links() {
|
|
37
|
+
return this._links;
|
|
38
|
+
}
|
|
39
|
+
get listening() {
|
|
40
|
+
return this._server.listening;
|
|
41
|
+
}
|
|
42
|
+
/** The address the server listens on, while it listens */
|
|
43
|
+
address() {
|
|
44
|
+
const address = this._server.address();
|
|
45
|
+
return address && typeof address === 'object' ? address : undefined;
|
|
46
|
+
}
|
|
47
|
+
/** Starts listening; port 0 takes a free port, which address() then gives */
|
|
48
|
+
listen(port, host) {
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
const server = this._server;
|
|
51
|
+
const fail = (err) => reject(err);
|
|
52
|
+
server.once('error', fail);
|
|
53
|
+
server.listen(port, host, () => {
|
|
54
|
+
server.removeListener('error', fail);
|
|
55
|
+
this.emit('listening');
|
|
56
|
+
resolve();
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
/** Stops listening and closes every open connection */
|
|
61
|
+
async close() {
|
|
62
|
+
const closing = new Promise(resolve => {
|
|
63
|
+
if (!this._server.listening)
|
|
64
|
+
return resolve();
|
|
65
|
+
this._server.close(() => resolve());
|
|
66
|
+
});
|
|
67
|
+
await Promise.all([...this._links].map(link => link.close()));
|
|
68
|
+
await closing;
|
|
69
|
+
}
|
|
70
|
+
_accept(socket) {
|
|
71
|
+
const connection = new TcpSocketConnection(socket, this.options);
|
|
72
|
+
const link = new AstmLink(connection, this.options.link);
|
|
73
|
+
link.use(this.router);
|
|
74
|
+
this._links.add(link);
|
|
75
|
+
link.once('close', () => this._links.delete(link));
|
|
76
|
+
this.emit('link', link);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Socket } from 'node:net';
|
|
2
|
+
import { TcpConnection, type TcpSocketOptions } from './tcp-connection.js';
|
|
3
|
+
/**
|
|
4
|
+
* A socket given to it: one that a server accepted, or one your own code
|
|
5
|
+
* connected or is connecting. The connection uses that socket as it is and
|
|
6
|
+
* does not reconnect: once it closes, a new socket makes a new connection.
|
|
7
|
+
*
|
|
8
|
+
* open() waits for a socket still connecting, and resolves at once for one
|
|
9
|
+
* already connected.
|
|
10
|
+
*/
|
|
11
|
+
export declare class TcpSocketConnection extends TcpConnection {
|
|
12
|
+
protected _description: string;
|
|
13
|
+
constructor(socket: Socket, options?: TcpSocketOptions);
|
|
14
|
+
get description(): string;
|
|
15
|
+
open(): Promise<void>;
|
|
16
|
+
close(): Promise<void>;
|
|
17
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { TcpConnection } from './tcp-connection.js';
|
|
2
|
+
/**
|
|
3
|
+
* A socket given to it: one that a server accepted, or one your own code
|
|
4
|
+
* connected or is connecting. The connection uses that socket as it is and
|
|
5
|
+
* does not reconnect: once it closes, a new socket makes a new connection.
|
|
6
|
+
*
|
|
7
|
+
* open() waits for a socket still connecting, and resolves at once for one
|
|
8
|
+
* already connected.
|
|
9
|
+
*/
|
|
10
|
+
export class TcpSocketConnection extends TcpConnection {
|
|
11
|
+
_description;
|
|
12
|
+
constructor(socket, options) {
|
|
13
|
+
super();
|
|
14
|
+
this._description = describe(socket);
|
|
15
|
+
this._attach(socket, options || {});
|
|
16
|
+
if (socket.connecting) {
|
|
17
|
+
socket.once('connect', () => {
|
|
18
|
+
this._description = describe(socket);
|
|
19
|
+
this.emit('open');
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
get description() {
|
|
24
|
+
return this._description;
|
|
25
|
+
}
|
|
26
|
+
async open() {
|
|
27
|
+
const socket = this._socket;
|
|
28
|
+
if (this.isOpen)
|
|
29
|
+
return;
|
|
30
|
+
if (!socket?.connecting)
|
|
31
|
+
throw new Error(`${this.description} is closed`);
|
|
32
|
+
await new Promise((resolve, reject) => {
|
|
33
|
+
const onError = (err) => {
|
|
34
|
+
socket.removeListener('connect', onConnect);
|
|
35
|
+
reject(err);
|
|
36
|
+
};
|
|
37
|
+
const onConnect = () => {
|
|
38
|
+
socket.removeListener('error', onError);
|
|
39
|
+
resolve();
|
|
40
|
+
};
|
|
41
|
+
socket.once('connect', onConnect);
|
|
42
|
+
socket.once('error', onError);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
async close() {
|
|
46
|
+
if (this._socket?.connecting)
|
|
47
|
+
this._socket.destroy();
|
|
48
|
+
await this._closeSocket();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function describe(socket) {
|
|
52
|
+
if (socket.remoteAddress) {
|
|
53
|
+
return `tcp://${socket.remoteAddress}:${socket.remotePort}`;
|
|
54
|
+
}
|
|
55
|
+
return 'tcp://connecting';
|
|
56
|
+
}
|