@spilne/perfect-net
v0.6.0
Published
Networking for @spilne/perfect-core: TCP, Unix socket and TLS connections as effects, typed messages, and a network simulator for tests.
Readme
@spilne/perfect-net
Networking for @spilne/perfect-core: typed messages
over TCP, Unix domain sockets, TLS and WebSockets, as effects, plus a network simulator
for tests. Runs on Node and Bun.
Install
bun add @spilne/perfect-netQuickstart
import { eff, scoped } from "@spilne/perfect-core";
import { BinaryCodec, Tcp } from "@spilne/perfect-net";
const codec = BinaryCodec.json<{ n: number }>();
const program = scoped(
eff(function* () {
const listener = yield* Tcp.listen(
{ host: "127.0.0.1", port: 0 },
{
codec,
handle: (connection) => connection.messages.forEach((m) => connection.send({ n: m.n * 2 })),
},
);
const connection = yield* Tcp.connect(listener.address, { codec });
yield* connection.send({ n: 21 });
return yield* connection.messages.take(1).toArray(); // [{ n: 42 }]
}),
);- Connections:
Tcp.connect/Tcp.listenwith{ host, port }or{ path }(Unix socket), optionaltls. EachConnectionhas a typedsend, amessagesstream andclose, and closes with its scope. - Codecs:
BinaryCodec.bytes,.utf8,.json<T>(); MessagePack from@spilne/perfect-net/msgpack(withmsgpackr) and Protobuf from@spilne/perfect-net/protobuf(with@bufbuild/protobuf). - Channels and reconnecting:
Multiplexerruns many channels over one connection, each with its own flow control;Resilient.connectreopens a broken connection with retries and an optional circuit breaker. - Clusters:
Gossip.joinkeeps a SWIM membership list,HashRingassigns keys to members, andDiscovery(DNS, SRV, or mDNS from@spilne/perfect-net/mdnswithmulticast-dns) finds the first members. - Recording:
Recorder.wrapwrites down a conversation andReplay.ofplays it back for tests, with no server. - Testing: depend on the
Transportservice and provideSimulatedNetworknodes in tests, with latency, message loss and partitions under the test's control (deterministic withTestClockandTestRandom).
See the networking guide.
