-
Notifications
You must be signed in to change notification settings - Fork 13
/
transport-tcp.ts
48 lines (39 loc) · 1.18 KB
/
transport-tcp.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"use strict";
import makeChannel from 'culvert';
import bodec from 'bodec';
import pktLine from '../lib/pkt-line';
import wrapHandler from '../lib/wrap-handler';
export default function (connect) {
return function tcpTransport(path, host, port) {
port = (port|0) || 9418;
if (!path || !host) throw new Error("path and host are required");
return (serviceName, onError) => {
onData = wrapHandler(onData, onError);
onDrain = wrapHandler(onDrain, onError);
const socket = connect(host, port, onError);
const inter = makeChannel();
inter.put = pktLine.deframer(inter.put);
socket.put = pktLine.framer(socket.put);
const greeting = bodec.fromRaw(serviceName + " " + path + "\0host=" + host + "\0");
socket.put(greeting);
// Pipe socket to inter with backpressure
socket.take(onData);
function onData(chunk) {
if (inter.put(chunk)) {
socket.take(onData);
}
else {
inter.drain(onDrain);
}
}
function onDrain() {
socket.take(onData);
}
return {
put: socket.put,
drain: socket.drain,
take: inter.take
};
};
};
};