Documentation
Blocking I/O
How a process reads from a socket, a pipe or another blocking source and still takes messages.
A process may block on a socket like any goroutine, but while it is blocked it does not read its mailbox. The code is from examples/blockingio, a line server whose listener and connections are processes.
Blocking in a process that takes no messages
The listener accepts connections, and nothing is sent to it, so it blocks in Accept as any Go code would. It does not call Receive meanwhile, so a request to inspect it waits, and when its deadline ends it says how long the listener has been busy.
It must still end when asked. An Exit cancels the process's context, but nothing can interrupt a goroutine, so context.AfterFunc closes the listener when the context ends. Accept returns, and the process returns the context's cause, the *ExitError with the reason it was asked to exit with.
// listener accepts connections and serves each in a process of its own,
// linked to it, so that they end when it does. Nothing is sent to it, so it
// may block in Accept: its exit closes the listener, which ends the wait.
func listener(ln net.Listener) func(*grpcproc.Process[proto.Message]) error {
return func(p *grpcproc.Process[proto.Message]) error {
context.AfterFunc(p.Context(), func() { _ = ln.Close() })
for {
c, err := ln.Accept()
if err != nil {
if cause := context.Cause(p.Context()); cause != nil {
return cause // asked to exit: the reason is the process's
}
return err
}
conn, err := p.Spawn(serve(c), grpcproc.LinkParent(), grpcproc.WithLabel("conn"))
if err != nil {
_ = c.Close()
continue
}
// Writes reach a connection as messages, from any process.
_ = conn.Send(p.Context(), p, write("welcome to "+p.Node().Name()))
}
}
}Each connection is a process of its own, spawned with LinkParent: linked to the listener, one way, so that it ends when the listener does.
Reading in a goroutine that only sends
A connection's process has two things to do at once: read what the peer sends, and write what other processes ask it to. Blocked in Read, it could not do the second. So the process keeps its mailbox and its state, and the blocking reads go to a goroutine of its own, which touches none of that state: it only sends each line it reads to the process's mailbox, where the line waits in order with the writes.
// serve runs one connection, and answers each line with it in upper case.
// Its goroutine owns the connection and takes messages; the blocking reads
// are another goroutine's, which touches nothing of the process's and only
// sends what it reads to the process's mailbox, as the node.
func serve(c net.Conn) func(*grpcproc.Process[*connpb.Event]) error {
return func(p *grpcproc.Process[*connpb.Event]) error {
defer func() { _ = c.Close() }()
context.AfterFunc(p.Context(), func() { _ = c.Close() }) // an exit ends the read
node, self := p.Node(), p.Addr()
go func() {
lines := bufio.NewScanner(c)
for lines.Scan() {
_ = self.Send(context.Background(), node, received(lines.Text()))
}
if p.Context().Err() == nil { // not the process's own exit closing c
_ = self.Send(context.Background(), node, closed(lines.Err()))
}
}()
for {
m, err := p.Receive()
if err != nil {
return err
}
switch e := m.Body.Kind.(type) {
case *connpb.Event_Received:
if _, err := fmt.Fprintln(c, strings.ToUpper(e.Received)); err != nil {
return err
}
case *connpb.Event_Write:
if _, err := fmt.Fprintln(c, e.Write); err != nil {
return err
}
case *connpb.Event_Closed:
return nil // the peer hung up
}
}
}
}Receive returns a line, a write, or the end of the connection. Because the process waits there and not in Read, it still answers inspection, makes calls and holds monitors.
A mailbox holds one message type, and it is a protobuf message, so a line from a socket becomes one even though it never leaves the node. The example's Event is a oneof of the three things a connection takes. Local delivery passes the pointer and encodes nothing.
// Messages of the blocking I/O example: what a connection's process takes.
syntax = "proto3";
package conn.v1;
option go_package = "github.com/floatdrop/grpcproc/examples/connpb;connpb";
// Event is everything a connection's process accepts. A mailbox holds one
// message type, so a line read from the connection is a message too, though
// it never leaves the node.
message Event {
oneof kind {
// A line the connection's reader read.
string received = 1;
// A line to write to the connection.
string write = 2;
// Why the reader stopped: the peer is gone.
string closed = 3;
}
}What other goroutines may call
Receive and ReceiveTimeout belong to the process's own goroutine. Other goroutines may send and call as the process, ask another process to exit, and use its PID, Addr, Node, Context and Log; a message's Reply works from anywhere.
Sending as the process from another goroutine has two side effects. The send inherits the metadata of whatever message the process is handling at that moment, so a trace would tie a line from the socket to an unrelated request; and a Call made there shows the process as waiting on a reply while its own goroutine may be idle. The reader in the example sends as the node instead, self.Send(ctx, node, …): the message comes from the node's own PID and carries nobody's metadata.
Ending
Every way out closes the connection, and the blocked goroutine learns of it from the connection. The process's exit, whether it was asked to exit, the listener's link ended it, or the node is stopping, cancels its context, and AfterFunc closes the connection: the reader's Read fails, and the reader stops. When the peer hangs up first, the reader's Read fails on its own; the reader sends why, and the loop returns nil, a normal exit. The reader checks the context before it sends that, so an exit the process started leaves no dead letter behind.
The program talks to its server as a client would, then asks the listener to exit. The listener's link ends the connection's process, whose exit closes the connection under the client:
// A client, as the outside world sees the server.
c, err := net.Dial("tcp", ln.Addr().String())
check(err)
defer func() { _ = c.Close() }()
lines := bufio.NewScanner(c)
lines.Scan()
fmt.Println("<", lines.Text())
for _, s := range []string{"hello", "blocking reads"} {
_, err := fmt.Fprintln(c, s)
check(err)
fmt.Println(">", s)
lines.Scan()
fmt.Println("<", lines.Text())
}
// The listener's exit closes its listener and ends the connection's
// process, linked to it, whose exit closes the connection.
check(node.Exit(ctx, server, "closing"))
fmt.Println("connection open:", lines.Scan())< welcome to edge
> hello
< HELLO
> blocking reads
< BLOCKING READS
connection open: falseHTTP and gRPC handlers
Code outside any process reaches processes with the node as the sender: an address's Send and Call, or the node's SendTo and CallTo, work from any goroutine. An HTTP or gRPC handler is such code: it calls the process that does the work and writes the answer, with the request's context bounding the wait, as the tutorial's web front does. A process per connection is for what a server library does not already handle: a raw socket, a pipe, a device.