.nib std
nib 0.3.0

module use "std/net.nib"

Net

TCP sockets: listen, accept, connect, send and receive bytes, through one interface, Net.Socket, answered by Net.Native.

Net is the layer everything network-shaped is built on. Net.Socket has seven operations — bind and listen, accept, dial, receive, send, close, and poll several connections at once — and Net.Native answers them with real TCP sockets. Http and Server are ordinary nib written on top of it; most programs that serve a website want Server.run rather than these operations directly.

A connection is a Symbol: the value accept and connect answer and the only thing that names the socket. It cannot be made from a number or a string, and it cannot be printed, so a program can only use connections it was actually given.

use "std/net.nib"

module Client where
  func ask :: host: String, port: Int, line: String -> String ! Net.Socket raises Err.BindFailed, Err.Closed, Err.ConnectFailed, HandleRefused =
    let conn = @Net.Socket.connect(host, port);
    let _ = @Net.Socket.send(conn, Bytes.from_string(line ++ "\n"));
    let reply = Bytes.to_string(@Net.Socket.recv(conn));
    let _ = @Net.Socket.close(conn);
    reply

  func main :: -> String ! Net.Socket raises Err.BindFailed, Err.Closed, Err.ConnectFailed, HandleRefused =
    try Client.ask("127.0.0.1", 7000, "ping")
    rescue Err.ConnectFailed(msg) => "no answer: {msg}" end

wire W runs Client.main where Net.Socket = Net.Native

Errors

  • Err.BindFailed — the program's own side: the port is in use, the address is malformed, or a port number is out of range. accept also raises it when its wait runs out with nobody arriving, so one rescue Err.BindFailed(_) in a server loop covers both.
  • Err.ConnectFailed — the peer's side of a dial: nothing listening, the network refusing, or no answer within 10 seconds.
  • Err.Closed — the peer went away while the program was sending, so the bytes were not delivered.
  • HandleRefused — the connection value is not one this program may use right now: another wire opened it, the runtime already closed it, or another fibre is in the middle of an operation on it. A refusal leaves the connection as it was.

Writing a server loop

accept always waits a bounded time, so a loop comes back round even when nobody calls. Put one round inside the try and call the loop again after it: a try whose body calls the loop again never returns, and every round would keep a handler alive. The instance below answers like an idle listener, so the example runs without opening a port:

use "std/net.nib"

effector Nobody is Net.Socket where
  listen(host, port) = ()
  connect(host, port) = raise Err.ConnectFailed("no peer")
  accept(ms) = raise Err.BindFailed("nobody arrived within {ms} ms")
  recv(conn) = Bytes.from_string("")
  send(conn, bytes) = ()
  close(conn) = ()
  poll(conns, ms) = #[]

module Loop where
  func round :: -> String ! Net.Socket raises HandleRefused =
    try
      let conn = @Net.Socket.accept(400);
      let _ = @Net.Socket.close(conn);
      "served one"
    rescue Err.BindFailed(msg) => "quiet: {msg}" end

  func main :: -> String ! Net.Socket raises Err.BindFailed, HandleRefused =
    let _ = @Net.Socket.listen("127.0.0.1", 18081);
    Loop.round()

wire Test runs Loop.main where Net.Socket = Nobody
quiet: nobody arrived within 400 ms

Interfaces

interfaceSocket
interface Socket where
  listen(host: String, port: Int) -> () raises BindFailed;
  connect(host: String, port: Int) -> Handle raises ConnectFailed, BindFailed;
  accept(timeout_ms: Int) -> Handle raises BindFailed;
  recv(conn: Handle) -> Bytes raises Closed, HandleRefused;
  send(conn: Handle, bytes: Bytes) -> () raises Closed, HandleRefused;
  close(conn: Handle) -> () raises HandleRefused;
  poll(conns: Vec<Handle>, timeout_ms: Int) -> Vec<Int> raises HandleRefused

The seven socket operations.

  • listen(host, port) binds and listens. host is an IP address such as "127.0.0.1" or "0.0.0.0", never a hostname. Calling it again for the address already bound does nothing; calling it for a different address raises Err.BindFailed.
  • connect(host, port) dials a peer and answers the connection. The address rule is the same as listen's. Raises Err.ConnectFailed when the peer cannot be reached within 10 seconds, and Err.BindFailed for a port that is not a port (0, 65536).
  • accept(timeout_ms) waits up to timeout_ms for a connection on the listener and answers it, or raises Err.BindFailed if none arrived. Zero or less checks once without waiting.
  • recv(conn) answers the bytes available now, up to 64 KiB. An empty Bytes means stop reading: the peer closed, or nothing arrived for 10 seconds.
  • send(conn, bytes) writes all of bytes, or raises Err.Closed if the peer has gone.
  • close(conn) closes the connection. Closing one twice is harmless.
  • poll(conns, timeout_ms) waits up to timeout_ms for any of conns to have bytes to read (or to have closed), without reading them. Answers the positions in conns that are ready, in ascending order, or #[] on timeout.

recv, send, close and poll raise HandleRefused for a connection this program may not use. Data crosses as Bytes; Bytes.to_string and Bytes.from_string convert, and never fail.

Effectors

effectorNet.Native builtin instance
effector Net.Native is Net.Socket  -- installed by nibc
  listen :: String, Int -> () raises Err.BindFailed
  connect :: String, Int -> Handle raises Err.ConnectFailed, Err.BindFailed
  accept :: Int -> Handle raises Err.BindFailed
  recv :: Handle -> Bytes raises Err.Closed, HandleRefused
  send :: Handle, Bytes -> () raises Err.Closed, HandleRefused
  close :: Handle -> () raises HandleRefused
  poll :: Vec<Handle>, Int -> Vec<Int> raises HandleRefused

Real TCP sockets, installed by nibc. A program has at most one listener, chosen by its listen call; the address is an argument rather than a setting, so a program's port is written in its source. Connections belong to the wire that opened them, and every one still open is closed when the run ends.

use "std/net.nib"

module Echo where
  func main :: -> () ! Net.Socket raises Err.BindFailed, Err.Closed, HandleRefused =
    let _ = @Net.Socket.listen("127.0.0.1", 7000);
    let conn = @Net.Socket.accept(5000);
    let _ = @Net.Socket.send(conn, @Net.Socket.recv(conn));
    @Net.Socket.close(conn)

wire W runs Echo.main where Net.Socket = Net.Native
effectorNet.Sim builtin instance
effector Net.Sim is Net.Socket  -- installed by nibc
  listen :: String, Int -> () raises Err.BindFailed
  connect :: String, Int -> Handle raises Err.ConnectFailed, Err.BindFailed
  accept :: Int -> Handle raises Err.BindFailed
  recv :: Handle -> Bytes raises Err.Closed, HandleRefused
  send :: Handle, Bytes -> () raises Err.Closed, HandleRefused
  close :: Handle -> () raises HandleRefused
  poll :: Vec<Handle>, Int -> Vec<Int> raises HandleRefused

A simulated network the runtime plays, for testing a cluster in one process. Every node is a fibre, named by the address it listens on; each send's delay, loss or duplication is the world's choice, drawn from --world FILE's seed and recorded in the journal, and partitions are part of that file. One recv answers one send. Bind it in a test's wire and keep Net.Native in production: the program does not change.

use "std/net.nib"

module Pair where
  func main :: -> String ! Net.Socket raises Err.BindFailed, Err.ConnectFailed, Err.Closed, HandleRefused =
    let _ = @Net.Socket.listen("10.0.0.1", 7000);
    let out = @Net.Socket.connect("10.0.0.1", 7000);
    let peer = @Net.Socket.accept(1000);
    let _ = @Net.Socket.send(out, Bytes.from_string("ping"));
    Bytes.to_string(@Net.Socket.recv(peer))

wire W runs Pair.main where Net.Socket = Net.Sim