@kylewillett/troupe 0.1.1 → 0.3.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/CHANGELOG.md +26 -1
- package/README.md +134 -4
- package/dist/ask.d.ts +5 -1
- package/dist/ask.js +16 -0
- package/dist/backstage/index.d.ts +2 -1
- package/dist/backstage/index.js +1 -0
- package/dist/backstage/source.d.ts +1 -1
- package/dist/backstage/source.js +65 -2
- package/dist/backstage/types.d.ts +65 -4
- package/dist/backstage/types.js +2 -1
- package/dist/backstage-ui/assets/index-CG896RLZ.css +1 -0
- package/dist/backstage-ui/assets/index-DF_Xnc1u.js +9 -0
- package/dist/backstage-ui/index.html +2 -2
- package/dist/cell.d.ts +19 -16
- package/dist/cell.js +46 -20
- package/dist/checks.d.ts +10 -0
- package/dist/checks.js +34 -2
- package/dist/cluster/index.d.ts +6 -0
- package/dist/cluster/index.js +4 -0
- package/dist/cluster/leases.d.ts +37 -0
- package/dist/cluster/leases.js +132 -0
- package/dist/cluster/membership.d.ts +100 -0
- package/dist/cluster/membership.js +559 -0
- package/dist/cluster/memory.d.ts +31 -0
- package/dist/cluster/memory.js +187 -0
- package/dist/cluster/placement.d.ts +10 -0
- package/dist/cluster/placement.js +30 -0
- package/dist/cluster/postgres/index.d.ts +1 -0
- package/dist/cluster/postgres/index.js +3 -0
- package/dist/cluster/postgres/schema.d.ts +7 -0
- package/dist/cluster/postgres/schema.js +33 -0
- package/dist/cluster/postgres/schema.sql +18 -0
- package/dist/cluster/postgres/store.d.ts +28 -0
- package/dist/cluster/postgres/store.js +124 -0
- package/dist/cluster/region.d.ts +103 -0
- package/dist/cluster/region.js +843 -0
- package/dist/cluster/remoting.d.ts +79 -0
- package/dist/cluster/remoting.js +755 -0
- package/dist/cluster/shard-memory.d.ts +14 -0
- package/dist/cluster/shard-memory.js +92 -0
- package/dist/cluster/shard-store.d.ts +62 -0
- package/dist/cluster/shard-store.js +36 -0
- package/dist/cluster/shard.d.ts +54 -0
- package/dist/cluster/shard.js +278 -0
- package/dist/cluster/sharding.d.ts +116 -0
- package/dist/cluster/sharding.js +286 -0
- package/dist/cluster/table.d.ts +29 -0
- package/dist/cluster/table.js +74 -0
- package/dist/cluster/timed-store.d.ts +4 -0
- package/dist/cluster/timed-store.js +19 -0
- package/dist/cluster/transport.d.ts +29 -0
- package/dist/cluster/transport.js +4 -0
- package/dist/cluster/wire.d.ts +90 -0
- package/dist/cluster/wire.js +177 -0
- package/dist/hash.d.ts +7 -0
- package/dist/hash.js +25 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/internal.d.ts +139 -2
- package/dist/internal.js +12 -1
- package/dist/json.d.ts +44 -0
- package/dist/json.js +143 -0
- package/dist/node/cluster/frames.d.ts +31 -0
- package/dist/node/cluster/frames.js +73 -0
- package/dist/node/cluster/index.d.ts +1 -0
- package/dist/node/cluster/index.js +3 -0
- package/dist/node/cluster/tcp.d.ts +101 -0
- package/dist/node/cluster/tcp.js +416 -0
- package/dist/persistence/actor.d.ts +9 -0
- package/dist/persistence/actor.js +21 -10
- package/dist/persistence/backend.d.ts +1 -10
- package/dist/persistence/backend.js +4 -34
- package/dist/persistence/errors.d.ts +19 -0
- package/dist/persistence/errors.js +22 -0
- package/dist/persistence/index.d.ts +1 -1
- package/dist/persistence/index.js +1 -1
- package/dist/persistence/postgres/index.d.ts +2 -1
- package/dist/persistence/postgres/index.js +1 -1
- package/dist/persistence/postgres/pool.d.ts +44 -0
- package/dist/persistence/postgres/pool.js +65 -0
- package/dist/persistence/postgres/postgres.d.ts +1 -33
- package/dist/persistence/postgres/postgres.js +4 -63
- package/dist/persistence/projection.d.ts +6 -0
- package/dist/persistence/projection.js +21 -5
- package/dist/rehearsal/clock.d.ts +54 -0
- package/dist/rehearsal/clock.js +203 -0
- package/dist/rehearsal/database.d.ts +116 -0
- package/dist/rehearsal/database.js +349 -0
- package/dist/rehearsal/loop.d.ts +57 -0
- package/dist/rehearsal/loop.js +153 -0
- package/dist/rehearsal/network.d.ts +120 -0
- package/dist/rehearsal/network.js +524 -0
- package/dist/rehearsal/ranges.d.ts +8 -0
- package/dist/rehearsal/ranges.js +27 -0
- package/dist/rehearsal/yield.d.ts +9 -0
- package/dist/rehearsal/yield.js +24 -0
- package/dist/system.d.ts +13 -1
- package/dist/system.js +204 -25
- package/dist/timeout.d.ts +8 -0
- package/dist/timeout.js +26 -0
- package/dist/types.d.ts +86 -3
- package/package.json +21 -2
- package/dist/backstage-ui/assets/index-Bg0MCiqs.css +0 -1
- package/dist/backstage-ui/assets/index-CeefBsDh.js +0 -9
- package/dist/persistence/json.d.ts +0 -7
- package/dist/persistence/json.js +0 -75
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Length-prefixed frames on a byte stream (decision 0027): a 4-byte big-endian length, then that
|
|
2
|
+
// many bytes of UTF-8 text. TCP delivers bytes in chunks that have nothing to do with frames, so
|
|
3
|
+
// the decoder keeps what it has until a frame is whole.
|
|
4
|
+
/** The length prefix, in bytes. */
|
|
5
|
+
const HEADER = 4;
|
|
6
|
+
/** Encodes one frame: its UTF-8 bytes, after their length. */
|
|
7
|
+
export function encodeFrame(text) {
|
|
8
|
+
const length = Buffer.byteLength(text, 'utf8');
|
|
9
|
+
const frame = Buffer.allocUnsafe(HEADER + length);
|
|
10
|
+
frame.writeUInt32BE(length, 0);
|
|
11
|
+
frame.write(text, HEADER, 'utf8');
|
|
12
|
+
return frame;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Turns chunks of a stream into frames, one at a time, so the limit can change between frames.
|
|
16
|
+
* That's how the transport keeps a peer to small frames until it has proven the secret, even when
|
|
17
|
+
* its proof and its first big frame arrive in one chunk.
|
|
18
|
+
*/
|
|
19
|
+
export class FrameDecoder {
|
|
20
|
+
/** The largest frame accepted, in bytes. */
|
|
21
|
+
limit;
|
|
22
|
+
#chunks = [];
|
|
23
|
+
#buffered = 0;
|
|
24
|
+
constructor(limit) {
|
|
25
|
+
this.limit = limit;
|
|
26
|
+
}
|
|
27
|
+
/** Adds a chunk of the stream. */
|
|
28
|
+
push(chunk) {
|
|
29
|
+
if (chunk.length === 0)
|
|
30
|
+
return;
|
|
31
|
+
this.#chunks.push(chunk);
|
|
32
|
+
this.#buffered += chunk.length;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The next whole frame, or undefined until there is one. A frame whose length is over the
|
|
36
|
+
* limit is reported as soon as its header arrives, before its body is buffered, and decoding
|
|
37
|
+
* should stop there.
|
|
38
|
+
*/
|
|
39
|
+
next() {
|
|
40
|
+
if (this.#buffered < HEADER)
|
|
41
|
+
return undefined;
|
|
42
|
+
const length = this.#peek(HEADER).readUInt32BE(0);
|
|
43
|
+
if (length > this.limit)
|
|
44
|
+
return { tooLong: length };
|
|
45
|
+
if (this.#buffered < HEADER + length)
|
|
46
|
+
return undefined;
|
|
47
|
+
return { frame: this.#take(HEADER + length).toString('utf8', HEADER) };
|
|
48
|
+
}
|
|
49
|
+
/** Whether part of a frame is waiting for the rest. */
|
|
50
|
+
get partial() {
|
|
51
|
+
return this.#buffered > 0;
|
|
52
|
+
}
|
|
53
|
+
/** The first `n` bytes, joined into the first chunk so the next peek is free. */
|
|
54
|
+
#peek(n) {
|
|
55
|
+
const first = this.#chunks[0];
|
|
56
|
+
if (first.length >= n)
|
|
57
|
+
return first;
|
|
58
|
+
const joined = Buffer.concat(this.#chunks);
|
|
59
|
+
this.#chunks = [joined];
|
|
60
|
+
return joined;
|
|
61
|
+
}
|
|
62
|
+
#take(n) {
|
|
63
|
+
const head = this.#peek(n);
|
|
64
|
+
const taken = head.subarray(0, n);
|
|
65
|
+
const rest = head.subarray(n);
|
|
66
|
+
if (rest.length > 0)
|
|
67
|
+
this.#chunks[0] = rest;
|
|
68
|
+
else
|
|
69
|
+
this.#chunks.shift();
|
|
70
|
+
this.#buffered -= n;
|
|
71
|
+
return taken;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { tcpTransport, type TcpTransportOptions } from './tcp.js';
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { type AddressInfo, type Socket } from 'node:net';
|
|
2
|
+
import type { Connection, Transport } from '../../cluster/transport.js';
|
|
3
|
+
/** Options for {@link tcpTransport}. */
|
|
4
|
+
export interface TcpTransportOptions {
|
|
5
|
+
/** The port to listen on. */
|
|
6
|
+
port: number;
|
|
7
|
+
/** The interface to listen on. Default `127.0.0.1`: only this machine can connect. */
|
|
8
|
+
host?: string;
|
|
9
|
+
/**
|
|
10
|
+
* The address other nodes dial, as `host:port`, when it isn't `host` and `port`: in Docker,
|
|
11
|
+
* say, where a node listens on `0.0.0.0` and is reached by its service name.
|
|
12
|
+
*/
|
|
13
|
+
advertise?: string;
|
|
14
|
+
/**
|
|
15
|
+
* Shared by every node in the cluster. It never crosses the wire: each side proves it knows it
|
|
16
|
+
* by answering the other's random challenge.
|
|
17
|
+
*/
|
|
18
|
+
secret: string;
|
|
19
|
+
/**
|
|
20
|
+
* The largest frame accepted from a peer, in UTF-8 bytes. A larger one closes the connection.
|
|
21
|
+
* Default 1 MiB, the same as remoting's own limit on what it sends.
|
|
22
|
+
*/
|
|
23
|
+
maxFrameBytes?: number;
|
|
24
|
+
}
|
|
25
|
+
/** A transport with what tests need to see inside it. Never exported from the entry point. */
|
|
26
|
+
export interface TcpNode {
|
|
27
|
+
readonly transport: Transport;
|
|
28
|
+
/** Every connection that hasn't closed yet, both ways. */
|
|
29
|
+
readonly connections: ReadonlySet<TcpConnection>;
|
|
30
|
+
/** Where the server is bound, once it's listening. */
|
|
31
|
+
bound(): AddressInfo | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* Ends everything at once, as `kill -9` would: every socket is reset, so frames still on their
|
|
34
|
+
* way are lost and the other ends see an error, and nothing here is told.
|
|
35
|
+
*/
|
|
36
|
+
kill(): void;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* A transport on TCP, for nodes in separate processes. Each frame is a 4-byte big-endian length
|
|
40
|
+
* and UTF-8 JSON text. Peers prove the shared secret before any other frame, and one that can't
|
|
41
|
+
* is disconnected. Connections aren't encrypted: keep cluster traffic on a private network.
|
|
42
|
+
* @throws TypeError for options that can't be used.
|
|
43
|
+
*/
|
|
44
|
+
export declare function tcpTransport(opts: TcpTransportOptions): Transport;
|
|
45
|
+
/**
|
|
46
|
+
* {@link tcpTransport}, with its insides showing. `authTimeoutMs` is for tests, which can't wait
|
|
47
|
+
* the real 5 s.
|
|
48
|
+
* @throws TypeError for options that can't be used.
|
|
49
|
+
*/
|
|
50
|
+
export declare function openTcpTransport(opts: TcpTransportOptions, { authTimeoutMs }?: {
|
|
51
|
+
readonly authTimeoutMs?: number;
|
|
52
|
+
}): TcpNode;
|
|
53
|
+
interface Settings {
|
|
54
|
+
readonly address: string;
|
|
55
|
+
readonly host: string;
|
|
56
|
+
readonly port: number;
|
|
57
|
+
readonly secret: string;
|
|
58
|
+
readonly maxFrameBytes: number;
|
|
59
|
+
readonly authTimeoutMs: number;
|
|
60
|
+
}
|
|
61
|
+
/** One node's transport: a server, and the connections both ways. */
|
|
62
|
+
declare class Node {
|
|
63
|
+
#private;
|
|
64
|
+
readonly transport: Transport;
|
|
65
|
+
readonly connections: Set<TcpConnection>;
|
|
66
|
+
readonly settings: Settings;
|
|
67
|
+
onRefused: ((reason: string) => void) | undefined;
|
|
68
|
+
constructor(settings: Settings);
|
|
69
|
+
bound(): AddressInfo | undefined;
|
|
70
|
+
kill(): void;
|
|
71
|
+
}
|
|
72
|
+
type Role = 'dialer' | 'acceptor';
|
|
73
|
+
/** One connection: the socket, the proof both ways, then frames. */
|
|
74
|
+
export declare class TcpConnection implements Connection {
|
|
75
|
+
#private;
|
|
76
|
+
readonly socket: Socket | undefined;
|
|
77
|
+
readonly role: Role;
|
|
78
|
+
/** `proving` until the peer has proven the secret, then `open`. */
|
|
79
|
+
state: 'connecting' | 'proving' | 'open' | 'closed';
|
|
80
|
+
/** Frames written to the socket, the challenge and proof included. */
|
|
81
|
+
sent: number;
|
|
82
|
+
/** Frames read from the socket, the challenge and proof included. */
|
|
83
|
+
received: number;
|
|
84
|
+
/** Resolves once the connection has closed and its listeners have been told. */
|
|
85
|
+
readonly closed: Promise<void>;
|
|
86
|
+
/** A connection that closes at once with `error`, for a dial that can't be made. */
|
|
87
|
+
static failed(node: Node, error: Error): TcpConnection;
|
|
88
|
+
constructor(node: Node, socket: Socket | undefined, role: Role, peer: string | undefined, onOpen: ((connection: Connection) => void) | undefined);
|
|
89
|
+
send(frame: string): void;
|
|
90
|
+
onFrame(listener: (frame: string) => void): void;
|
|
91
|
+
onClose(listener: (error?: unknown) => void): void;
|
|
92
|
+
close(): void;
|
|
93
|
+
/** Its node was killed: the socket is reset, and nobody here hears of it. */
|
|
94
|
+
vanish(): void;
|
|
95
|
+
}
|
|
96
|
+
/** The host and port in `host:port` or `[ipv6]:port`, or undefined. */
|
|
97
|
+
export declare function parseAddress(address: string): {
|
|
98
|
+
host: string;
|
|
99
|
+
port: number;
|
|
100
|
+
} | undefined;
|
|
101
|
+
export {};
|
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
// The TCP transport (decision 0027): length-prefixed frames on node:net, and a challenge-response
|
|
2
|
+
// on a shared secret before any other frame. Remoting does the rest: the hello, reconnecting with
|
|
3
|
+
// backoff on the system's scheduler, and buffering while a peer is away (decision 0026). So this
|
|
4
|
+
// file has no timers of its own, only the socket's idle timeout while a peer proves the secret.
|
|
5
|
+
//
|
|
6
|
+
// The proof: each side sends a random nonce, and answers the other's with an HMAC-SHA256 under the
|
|
7
|
+
// secret of both nonces and its role. The role is in the MAC so a proof can't be reflected back
|
|
8
|
+
// to the side that made it, and a challenge that comes back unchanged is refused outright.
|
|
9
|
+
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
10
|
+
import { connect as dial, createServer, } from 'node:net';
|
|
11
|
+
import { checkInt, checkKeys, describe } from '../../checks.js';
|
|
12
|
+
import { encodeFrame, FrameDecoder } from './frames.js';
|
|
13
|
+
const OPTIONS = new Set(['port', 'host', 'advertise', 'secret', 'maxFrameBytes']);
|
|
14
|
+
const PROTOCOL = 'troupe-tcp/1';
|
|
15
|
+
const NONCE_BYTES = 32;
|
|
16
|
+
const MAC_BYTES = 32;
|
|
17
|
+
const HEX = /^[0-9a-f]+$/;
|
|
18
|
+
// A challenge or a proof is under 200 bytes: nothing bigger is buffered from an unproven peer.
|
|
19
|
+
const AUTH_LIMIT_BYTES = 256;
|
|
20
|
+
const AUTH_TIMEOUT_MS = 5_000;
|
|
21
|
+
/**
|
|
22
|
+
* A transport on TCP, for nodes in separate processes. Each frame is a 4-byte big-endian length
|
|
23
|
+
* and UTF-8 JSON text. Peers prove the shared secret before any other frame, and one that can't
|
|
24
|
+
* is disconnected. Connections aren't encrypted: keep cluster traffic on a private network.
|
|
25
|
+
* @throws TypeError for options that can't be used.
|
|
26
|
+
*/
|
|
27
|
+
export function tcpTransport(opts) {
|
|
28
|
+
return openTcpTransport(opts).transport;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* {@link tcpTransport}, with its insides showing. `authTimeoutMs` is for tests, which can't wait
|
|
32
|
+
* the real 5 s.
|
|
33
|
+
* @throws TypeError for options that can't be used.
|
|
34
|
+
*/
|
|
35
|
+
export function openTcpTransport(opts, { authTimeoutMs = AUTH_TIMEOUT_MS } = {}) {
|
|
36
|
+
checkKeys(opts, OPTIONS, 'tcpTransport');
|
|
37
|
+
const { port, host = '127.0.0.1', advertise, secret, maxFrameBytes = 1_048_576 } = opts;
|
|
38
|
+
checkInt(port, 'tcpTransport: port');
|
|
39
|
+
if (port > 65_535)
|
|
40
|
+
throw new TypeError(`tcpTransport: port must be at most 65535, got ${String(port)}`);
|
|
41
|
+
if (typeof host !== 'string' || host === '' || /\s/.test(host)) {
|
|
42
|
+
throw new TypeError(`tcpTransport: host must be a host name or IP, got ${describe(host)}`);
|
|
43
|
+
}
|
|
44
|
+
if (advertise !== undefined && (typeof advertise !== 'string' || !parseAddress(advertise))) {
|
|
45
|
+
throw new TypeError(`tcpTransport: advertise must be "host:port", got ${describe(advertise)}`);
|
|
46
|
+
}
|
|
47
|
+
if (typeof secret !== 'string' || secret === '') {
|
|
48
|
+
throw new TypeError('tcpTransport: secret must be a non-empty string');
|
|
49
|
+
}
|
|
50
|
+
checkInt(maxFrameBytes, 'tcpTransport: maxFrameBytes');
|
|
51
|
+
const address = advertise ?? formatAddress(host, port);
|
|
52
|
+
const node = new Node({ address, host, port, secret, maxFrameBytes, authTimeoutMs });
|
|
53
|
+
return {
|
|
54
|
+
transport: node.transport,
|
|
55
|
+
connections: node.connections,
|
|
56
|
+
bound: () => node.bound(),
|
|
57
|
+
kill: () => {
|
|
58
|
+
node.kill();
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** One node's transport: a server, and the connections both ways. */
|
|
63
|
+
class Node {
|
|
64
|
+
transport;
|
|
65
|
+
connections = new Set();
|
|
66
|
+
settings;
|
|
67
|
+
onRefused;
|
|
68
|
+
#server;
|
|
69
|
+
#gone = false;
|
|
70
|
+
#closing;
|
|
71
|
+
constructor(settings) {
|
|
72
|
+
this.settings = settings;
|
|
73
|
+
this.transport = Object.freeze({
|
|
74
|
+
address: settings.address,
|
|
75
|
+
listen: (onConnection, onRefused) => this.#listen(onConnection, onRefused),
|
|
76
|
+
connect: (to) => this.#connect(to),
|
|
77
|
+
close: () => this.#close(),
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
bound() {
|
|
81
|
+
const bound = this.#server?.address();
|
|
82
|
+
return typeof bound === 'object' && bound !== null ? bound : undefined;
|
|
83
|
+
}
|
|
84
|
+
#listen(onConnection, onRefused) {
|
|
85
|
+
if (this.#gone)
|
|
86
|
+
return Promise.reject(new Error(`${this.settings.address} has closed`));
|
|
87
|
+
if (this.#server !== undefined) {
|
|
88
|
+
return Promise.reject(new Error(`${this.settings.address} is already listening`));
|
|
89
|
+
}
|
|
90
|
+
this.onRefused = onRefused;
|
|
91
|
+
const server = createServer((socket) => {
|
|
92
|
+
if (this.#gone) {
|
|
93
|
+
socket.destroy();
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
new TcpConnection(this, socket, 'acceptor', undefined, onConnection);
|
|
97
|
+
});
|
|
98
|
+
this.#server = server;
|
|
99
|
+
return new Promise((resolve, reject) => {
|
|
100
|
+
server.once('error', (error) => {
|
|
101
|
+
this.#server = undefined;
|
|
102
|
+
reject(error);
|
|
103
|
+
});
|
|
104
|
+
server.listen(this.settings.port, this.settings.host, () => {
|
|
105
|
+
server.removeAllListeners('error');
|
|
106
|
+
// Errors after this are the accepted sockets', and each connection handles its own.
|
|
107
|
+
server.on('error', () => { });
|
|
108
|
+
resolve();
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
#connect(to) {
|
|
113
|
+
const target = parseAddress(to);
|
|
114
|
+
if (this.#gone || target === undefined) {
|
|
115
|
+
const why = this.#gone ? `${this.settings.address} has closed` : `"${to}" isn't host:port`;
|
|
116
|
+
return TcpConnection.failed(this, new Error(why));
|
|
117
|
+
}
|
|
118
|
+
const socket = dial({ host: target.host, port: target.port });
|
|
119
|
+
return new TcpConnection(this, socket, 'dialer', to, undefined);
|
|
120
|
+
}
|
|
121
|
+
#close() {
|
|
122
|
+
if (this.#closing !== undefined)
|
|
123
|
+
return this.#closing;
|
|
124
|
+
const wasGone = this.#gone;
|
|
125
|
+
this.#gone = true;
|
|
126
|
+
const server = this.#server;
|
|
127
|
+
const closes = [...this.connections].map((c) => c.closed);
|
|
128
|
+
for (const connection of [...this.connections])
|
|
129
|
+
connection.close();
|
|
130
|
+
const stopped = wasGone || server === undefined || !server.listening
|
|
131
|
+
? Promise.resolve()
|
|
132
|
+
: new Promise((resolve) => {
|
|
133
|
+
server.close(() => {
|
|
134
|
+
resolve();
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
this.#closing = Promise.all([stopped, ...closes]).then(() => undefined);
|
|
138
|
+
return this.#closing;
|
|
139
|
+
}
|
|
140
|
+
kill() {
|
|
141
|
+
if (this.#gone)
|
|
142
|
+
return;
|
|
143
|
+
this.#gone = true;
|
|
144
|
+
this.#closing = Promise.resolve();
|
|
145
|
+
for (const connection of [...this.connections])
|
|
146
|
+
connection.vanish();
|
|
147
|
+
this.#server?.close();
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** One connection: the socket, the proof both ways, then frames. */
|
|
151
|
+
export class TcpConnection {
|
|
152
|
+
socket;
|
|
153
|
+
role;
|
|
154
|
+
/** `proving` until the peer has proven the secret, then `open`. */
|
|
155
|
+
state;
|
|
156
|
+
/** Frames written to the socket, the challenge and proof included. */
|
|
157
|
+
sent = 0;
|
|
158
|
+
/** Frames read from the socket, the challenge and proof included. */
|
|
159
|
+
received = 0;
|
|
160
|
+
/** Resolves once the connection has closed and its listeners have been told. */
|
|
161
|
+
closed;
|
|
162
|
+
#node;
|
|
163
|
+
#peer;
|
|
164
|
+
#onOpen;
|
|
165
|
+
#decoder = new FrameDecoder(AUTH_LIMIT_BYTES);
|
|
166
|
+
#nonce = randomBytes(NONCE_BYTES).toString('hex');
|
|
167
|
+
#pending = [];
|
|
168
|
+
#frameListeners = [];
|
|
169
|
+
#closeListeners = [];
|
|
170
|
+
#peerNonce;
|
|
171
|
+
#error;
|
|
172
|
+
#done = false;
|
|
173
|
+
#ended = () => { };
|
|
174
|
+
/** A connection that closes at once with `error`, for a dial that can't be made. */
|
|
175
|
+
static failed(node, error) {
|
|
176
|
+
const connection = new TcpConnection(node, undefined, 'dialer', undefined, undefined);
|
|
177
|
+
connection.#error = { error };
|
|
178
|
+
queueMicrotask(() => {
|
|
179
|
+
connection.#finish();
|
|
180
|
+
});
|
|
181
|
+
return connection;
|
|
182
|
+
}
|
|
183
|
+
constructor(node, socket, role, peer, onOpen) {
|
|
184
|
+
this.#node = node;
|
|
185
|
+
this.socket = socket;
|
|
186
|
+
this.role = role;
|
|
187
|
+
this.#peer = peer;
|
|
188
|
+
this.#onOpen = onOpen;
|
|
189
|
+
this.closed = new Promise((resolve) => {
|
|
190
|
+
this.#ended = resolve;
|
|
191
|
+
});
|
|
192
|
+
this.state = role === 'dialer' ? 'connecting' : 'proving';
|
|
193
|
+
if (socket === undefined)
|
|
194
|
+
return;
|
|
195
|
+
node.connections.add(this);
|
|
196
|
+
socket.setNoDelay(true);
|
|
197
|
+
// The socket's own idle timer, the one clock here: a peer gets this long to prove the secret.
|
|
198
|
+
const timeoutMs = node.settings.authTimeoutMs;
|
|
199
|
+
socket.setTimeout(timeoutMs);
|
|
200
|
+
socket.on('timeout', () => {
|
|
201
|
+
this.#refuse(`it didn't prove the secret within ${String(timeoutMs)} ms`);
|
|
202
|
+
});
|
|
203
|
+
socket.on('data', (chunk) => {
|
|
204
|
+
this.#onData(chunk);
|
|
205
|
+
});
|
|
206
|
+
socket.on('error', (error) => {
|
|
207
|
+
this.#error ??= { error };
|
|
208
|
+
});
|
|
209
|
+
socket.on('close', () => {
|
|
210
|
+
this.#finish();
|
|
211
|
+
});
|
|
212
|
+
if (role === 'dialer') {
|
|
213
|
+
socket.once('connect', () => {
|
|
214
|
+
if (this.state !== 'connecting')
|
|
215
|
+
return;
|
|
216
|
+
this.state = 'proving';
|
|
217
|
+
this.#challenge();
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
this.#challenge();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
send(frame) {
|
|
225
|
+
if (this.state === 'closed')
|
|
226
|
+
return;
|
|
227
|
+
if (this.state !== 'open') {
|
|
228
|
+
this.#pending.push(frame);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
this.#write(frame);
|
|
232
|
+
}
|
|
233
|
+
onFrame(listener) {
|
|
234
|
+
this.#frameListeners.push(listener);
|
|
235
|
+
}
|
|
236
|
+
onClose(listener) {
|
|
237
|
+
if (!this.#done) {
|
|
238
|
+
this.#closeListeners.push(listener);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
const error = this.#error;
|
|
242
|
+
queueMicrotask(() => {
|
|
243
|
+
if (error === undefined)
|
|
244
|
+
listener();
|
|
245
|
+
else
|
|
246
|
+
listener(error.error);
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
close() {
|
|
250
|
+
if (this.state === 'closed')
|
|
251
|
+
return;
|
|
252
|
+
const wasOpen = this.state === 'open';
|
|
253
|
+
this.state = 'closed';
|
|
254
|
+
this.#pending.length = 0;
|
|
255
|
+
// What was already written still goes. Before the proof, nothing of ours has been written.
|
|
256
|
+
if (wasOpen)
|
|
257
|
+
this.socket?.destroySoon();
|
|
258
|
+
else
|
|
259
|
+
this.socket?.destroy();
|
|
260
|
+
}
|
|
261
|
+
/** Its node was killed: the socket is reset, and nobody here hears of it. */
|
|
262
|
+
vanish() {
|
|
263
|
+
this.state = 'closed';
|
|
264
|
+
this.#done = true;
|
|
265
|
+
this.#closeListeners = [];
|
|
266
|
+
this.#frameListeners.length = 0;
|
|
267
|
+
this.#node.connections.delete(this);
|
|
268
|
+
this.socket?.resetAndDestroy();
|
|
269
|
+
this.#ended();
|
|
270
|
+
}
|
|
271
|
+
#onData(chunk) {
|
|
272
|
+
if (this.state === 'closed')
|
|
273
|
+
return;
|
|
274
|
+
this.#decoder.push(chunk);
|
|
275
|
+
// One frame at a time: the proof raises the limit, and the frames after it in the same chunk
|
|
276
|
+
// are held to the new one.
|
|
277
|
+
for (let next = this.#decoder.next(); next !== undefined; next = this.#decoder.next()) {
|
|
278
|
+
if (next.tooLong !== undefined) {
|
|
279
|
+
this.#refuse(`it sent a frame of ${String(next.tooLong)} bytes, over the limit (${String(this.#decoder.limit)})`);
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
this.received++;
|
|
283
|
+
if (this.state === 'open')
|
|
284
|
+
this.#emit(next.frame);
|
|
285
|
+
else
|
|
286
|
+
this.#onProof(next.frame);
|
|
287
|
+
// A listener may have closed it, or the proof refused it: a call TypeScript can't see into.
|
|
288
|
+
if (this.#isClosed())
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
#isClosed() {
|
|
293
|
+
return this.state === 'closed';
|
|
294
|
+
}
|
|
295
|
+
#emit(frame) {
|
|
296
|
+
for (const listener of this.#frameListeners)
|
|
297
|
+
listener(frame);
|
|
298
|
+
}
|
|
299
|
+
#challenge() {
|
|
300
|
+
this.#write(JSON.stringify({ t: 'challenge', protocol: PROTOCOL, nonce: this.#nonce }));
|
|
301
|
+
}
|
|
302
|
+
/** A frame from a peer that hasn't proven the secret yet: its challenge, then its proof. */
|
|
303
|
+
#onProof(text) {
|
|
304
|
+
const frame = parse(text);
|
|
305
|
+
if (this.#peerNonce === undefined) {
|
|
306
|
+
if (frame?.t !== 'challenge') {
|
|
307
|
+
this.#refuse('it sent something other than a challenge first');
|
|
308
|
+
}
|
|
309
|
+
else if (frame.protocol !== PROTOCOL) {
|
|
310
|
+
this.#refuse(`its protocol is ${describe(frame.protocol)}, not "${PROTOCOL}"`);
|
|
311
|
+
}
|
|
312
|
+
else if (!isHex(frame.nonce, NONCE_BYTES)) {
|
|
313
|
+
this.#refuse('its challenge is malformed');
|
|
314
|
+
}
|
|
315
|
+
else if (frame.nonce === this.#nonce) {
|
|
316
|
+
this.#refuse('it sent back our own challenge');
|
|
317
|
+
}
|
|
318
|
+
else {
|
|
319
|
+
this.#peerNonce = frame.nonce;
|
|
320
|
+
this.#write(JSON.stringify({ t: 'proof', mac: this.#mac(this.role) }));
|
|
321
|
+
}
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (frame?.t !== 'proof' || !isHex(frame.mac, MAC_BYTES)) {
|
|
325
|
+
this.#refuse('it sent something other than a proof after its challenge');
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
const expected = Buffer.from(this.#mac(this.role === 'dialer' ? 'acceptor' : 'dialer'), 'hex');
|
|
329
|
+
if (!timingSafeEqual(expected, Buffer.from(frame.mac, 'hex'))) {
|
|
330
|
+
this.#refuse('it failed to prove the secret');
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
this.#open();
|
|
334
|
+
}
|
|
335
|
+
#mac(role) {
|
|
336
|
+
const [dialer, acceptor] = this.role === 'dialer'
|
|
337
|
+
? [this.#nonce, this.#peerNonce]
|
|
338
|
+
: [this.#peerNonce, this.#nonce];
|
|
339
|
+
return createHmac('sha256', this.#node.settings.secret)
|
|
340
|
+
.update(`${PROTOCOL} ${role} ${dialer} ${acceptor}`)
|
|
341
|
+
.digest('hex');
|
|
342
|
+
}
|
|
343
|
+
#open() {
|
|
344
|
+
this.state = 'open';
|
|
345
|
+
this.socket?.setTimeout(0);
|
|
346
|
+
this.#decoder.limit = this.#node.settings.maxFrameBytes;
|
|
347
|
+
for (const frame of this.#pending.splice(0))
|
|
348
|
+
this.#write(frame);
|
|
349
|
+
this.#onOpen?.(this);
|
|
350
|
+
}
|
|
351
|
+
/** Drops a peer that broke the rules: it's sent nothing more, and the node is told why. */
|
|
352
|
+
#refuse(why) {
|
|
353
|
+
if (this.state === 'closed')
|
|
354
|
+
return;
|
|
355
|
+
const reason = `refused the TCP connection with ${this.#who()}: ${why}`;
|
|
356
|
+
this.#error = { error: new Error(reason) };
|
|
357
|
+
this.state = 'closed';
|
|
358
|
+
this.#pending.length = 0;
|
|
359
|
+
this.socket?.destroy();
|
|
360
|
+
this.#node.onRefused?.(reason);
|
|
361
|
+
}
|
|
362
|
+
#who() {
|
|
363
|
+
if (this.#peer !== undefined)
|
|
364
|
+
return this.#peer;
|
|
365
|
+
const socket = this.socket;
|
|
366
|
+
const host = socket?.remoteAddress ?? 'an unknown peer';
|
|
367
|
+
return socket?.remotePort === undefined ? host : formatAddress(host, socket.remotePort);
|
|
368
|
+
}
|
|
369
|
+
#write(frame) {
|
|
370
|
+
this.sent++;
|
|
371
|
+
this.socket?.write(encodeFrame(frame));
|
|
372
|
+
}
|
|
373
|
+
#finish() {
|
|
374
|
+
if (this.#done)
|
|
375
|
+
return;
|
|
376
|
+
this.#done = true;
|
|
377
|
+
this.state = 'closed';
|
|
378
|
+
this.#node.connections.delete(this);
|
|
379
|
+
const error = this.#error;
|
|
380
|
+
for (const listener of this.#closeListeners.splice(0)) {
|
|
381
|
+
if (error === undefined)
|
|
382
|
+
listener();
|
|
383
|
+
else
|
|
384
|
+
listener(error.error);
|
|
385
|
+
}
|
|
386
|
+
this.#ended();
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
/** `host:port`, with brackets around an IPv6 host. */
|
|
390
|
+
function formatAddress(host, port) {
|
|
391
|
+
return host.includes(':') ? `[${host}]:${String(port)}` : `${host}:${String(port)}`;
|
|
392
|
+
}
|
|
393
|
+
/** The host and port in `host:port` or `[ipv6]:port`, or undefined. */
|
|
394
|
+
export function parseAddress(address) {
|
|
395
|
+
const match = /^(?:\[([^\]\s]+)\]|([^:[\]\s/@#]+)):(\d{1,5})$/.exec(address);
|
|
396
|
+
if (match === null)
|
|
397
|
+
return undefined;
|
|
398
|
+
const port = Number(match[3]);
|
|
399
|
+
if (port < 1 || port > 65_535)
|
|
400
|
+
return undefined;
|
|
401
|
+
return { host: match[1] ?? match[2], port };
|
|
402
|
+
}
|
|
403
|
+
function parse(text) {
|
|
404
|
+
try {
|
|
405
|
+
const value = JSON.parse(text);
|
|
406
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
407
|
+
? value
|
|
408
|
+
: undefined;
|
|
409
|
+
}
|
|
410
|
+
catch {
|
|
411
|
+
return undefined;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
function isHex(value, bytes) {
|
|
415
|
+
return typeof value === 'string' && value.length === bytes * 2 && HEX.test(value);
|
|
416
|
+
}
|
|
@@ -130,6 +130,15 @@ export interface PersistentActorDef<C, E, S> {
|
|
|
130
130
|
*/
|
|
131
131
|
version?: number;
|
|
132
132
|
};
|
|
133
|
+
/**
|
|
134
|
+
* How long each journal and snapshot call may take, in ms: a positive integer. Default 10,000.
|
|
135
|
+
* An append or a recovery read that takes longer fails the actor with
|
|
136
|
+
* `PersistenceTimeoutError`, for its supervision to handle, and no reply is sent. The append
|
|
137
|
+
* may still have been written, so a restart recovers from the journal to find out (decision
|
|
138
|
+
* 0036). A snapshot load that takes longer is skipped, and recovery replays every event. A
|
|
139
|
+
* snapshot save that takes longer is logged.
|
|
140
|
+
*/
|
|
141
|
+
timeoutMs?: number;
|
|
133
142
|
}
|
|
134
143
|
/**
|
|
135
144
|
* Defines an event-sourced actor. Commands go to `onCommand`, which returns an effect. Its events
|