Este artículo solo está disponible en inglés.

I was overthinking the next post of the WebRTC from scratch series, the one that sets the design rules of the project. One of the things I wanted to try was an approach called "sans I/O", and while working out how to apply it in C I ended up with a very simple way to implement it. I liked the result enough to write this post about it.

What sans I/O is

Sans I/O denotes an implementation of a network protocol that performs no I/O of its own. The protocol is written as a deterministic state machine: it is informed of what happened (a packet arrived, time passed), updates its state and describes what it wants done (send this packet). An I/O layer produces those inputs and translates the outputs into system calls.

The term originates in the Python community; sans-io.readthedocs.io documents the approach and lists libraries written this way.

The following properties follow from this separation:

  • Testability. No real I/O is involved. A component is a deterministic machine with defined input and output event streams.
  • Composability. Two protocols are combined by mapping the output events of one to the input events of the other.
  • Portability. The protocol never touches sockets, timers or threads, which is where platform-specific code tends to live.

Implementing it in C

There is no standard way of implementing sans I/O. What follows is the structure I arrived at after applying it to a protocol like WebRTC, packet-oriented and composed of several protocols (one of which, ICE, needs close control of the network layer), with C and a simple implementation in mind.

An implementation consists of:

  • Events, serialized bytes tagged with their kind.
  • Components, structs holding the state of one protocol.
  • Three functions per component: how its state changes and which events it emits when it receives an event, the same when time passes, and when it next needs to be told the time.

Everything that enters or leaves a component is an event, with one exception: time. Reading the clock is itself a form of I/O, and a component that calls time() is no longer deterministic.

The event buffer

Events are serialized one after another into a flat buffer, each as a small header (kind and size) followed by its payload. A component receives the buffer in every call in which it may emit events.

typedef struct {
    uint32_t read_offset;
    uint32_t write_offset;
    uint32_t capacity;
    char* data;
} event_buffer_t;


// An event as a component sees it: its kind and its payload.
typedef struct {
    uint16_t kind;
    uint16_t size;
    const char* data;
} event_t;


#define SERIALIZE(ptr, field)                 \
    do {                                      \
        memcpy(ptr, &(field), sizeof(field)); \
        (ptr) += sizeof(field);               \
    } while (0)

#define DESERIALIZE(ptr, size, field)         \
    do {                                      \
        assert((size) >= sizeof(field));      \
        memcpy(&(field), ptr, sizeof(field)); \
        (ptr) += sizeof(field);               \
        (size) -= sizeof(field);              \
    } while (0)


// Appends an event and returns a pointer to its payload. The caller must fill
// the payload before doing anything else with the buffer.
char* event_buffer_push(event_buffer_t* buffer, uint16_t kind, uint16_t size) {
    assert(
        buffer->write_offset + sizeof(kind) + sizeof(size) + size
        <= buffer->capacity
    );

    char* dst = buffer->data + buffer->write_offset;
    SERIALIZE(dst, kind);
    SERIALIZE(dst, size);

    buffer->write_offset = dst - buffer->data + size;
    return dst;
}


// Takes the next event out of the buffer. Returns 0 if there is none.
int event_buffer_pop(event_buffer_t* buffer, event_t* event) {
    const char* src = buffer->data + buffer->read_offset;
    uint32_t unread = buffer->write_offset - buffer->read_offset;
    if (unread == 0) {
        return 0;
    }

    DESERIALIZE(src, unread, event->kind);
    DESERIALIZE(src, unread, event->size);

    event->data = src;
    buffer->read_offset = src - buffer->data + event->size;
    return 1;
}


void event_buffer_clear(event_buffer_t* buffer) {
    buffer->read_offset = buffer->write_offset = 0;
}

A ring buffer is the usual choice for a queue, but it is not needed here. The buffer is drained completely after every external stimulus (a datagram, a tick, a call from the application) and then cleared, so it never holds many events. The one constraint is that it must not grow while events are being propagated, since the pointer returned by event_buffer_pop remains in use while the components handle the event.

Defining events

An event is defined by a kind (an integer) and a payload layout. The two UDP events may be defined as follows:

typedef struct {
    uint8_t ip[16];  // IPv6, or IPv4-mapped
    uint16_t port;
} endpoint_t;


// Provisional; the final kinds are defined in Events and composition.
#define SEND_UDP    1
#define RECEIVE_UDP 2


// Payload of SEND_UDP and RECEIVE_UDP: the socket, the destination or source
// endpoint, then the datagram. Writes it at dst and returns the event.
event_t build_udp_event(
    char* dst, uint16_t kind, int socket, endpoint_t remote, const void* data,
    uint16_t size
) {
    event_t event = {kind, 0, dst};

    SERIALIZE(dst, socket);
    SERIALIZE(dst, remote);
    memcpy(dst, data, size);

    event.size = dst - event.data + size;
    return event;
}


void push_udp(
    event_buffer_t* buffer, uint16_t kind, int socket, endpoint_t remote,
    const void* data, uint16_t size
) {
    char* dst = event_buffer_push(
        buffer, kind, sizeof(socket) + sizeof(remote) + size
    );

    build_udp_event(dst, kind, socket, remote, data, size);
}

Defining components

A component consists of a struct and three functions: *_process_event, *_process_time and *_next_deadline. The I/O layer calls the second before delivering any event, so a component may rely on its copy of now while handling events. The third returns the earliest time at which the component needs *_process_time to be called again, or UINT64_MAX if it has nothing pending. It is a hint for the caller, not a contract: *_process_time may be called at any time, and a loop that ignores the deadlines and ticks at a fixed rate remains correct. A component reads only its own state and writes only to the buffer, which is what allows it to be tested in isolation.

The running example is a UDP ping. The server echoes back whatever it receives:

// The server has no state.
typedef struct {
    char unused;
} ping_server_t;


void ping_server_process_event(
    ping_server_t* server, event_buffer_t* buffer, event_t event
) {
    if (event.kind != RECEIVE_UDP) {
        return;
    }

    int socket;
    endpoint_t remote;
    DESERIALIZE(event.data, event.size, socket);
    DESERIALIZE(event.data, event.size, remote);

    push_udp(buffer, SEND_UDP, socket, remote, event.data, event.size);
}

The client has state and tracks time, all of it derived from its inputs:

#define PING_SEND   3  // app -> client; payload: the endpoint_t to ping
#define PING_RESULT 4  // client -> app; payload: a ping_result_t


typedef struct {
    bool ok;  // false: timed out or cancelled by a new PING_SEND
    uint64_t latency_ms;
} ping_result_t;


#define PING_TIMEOUT_MS 1000


typedef struct {
    int socket;
    uint64_t now;
    uint32_t sequence;  // payload of the last ping sent
    bool waiting;       // a ping is in flight; the fields below are valid
    endpoint_t server;
    uint64_t sent_at;
} ping_client_t;


static void ping_client_finish(
    ping_client_t* client, event_buffer_t* buffer, bool ok
) {
    ping_result_t result = {ok, client->now - client->sent_at};
    memcpy(
        event_buffer_push(buffer, PING_RESULT, sizeof(result)), &result,
        sizeof(result)
    );

    client->waiting = false;
}


void ping_client_process_event(
    ping_client_t* client, event_buffer_t* buffer, event_t event
) {
    switch (event.kind) {
    case PING_SEND:
        if (client->waiting) {
            ping_client_finish(client, buffer, false);
        }

        DESERIALIZE(event.data, event.size, client->server);
        client->sequence++;
        client->sent_at = client->now;
        client->waiting = true;

        push_udp(
            buffer, SEND_UDP, client->socket, client->server,
            &client->sequence, sizeof(client->sequence)
        );
        break;

    case RECEIVE_UDP: {
        int socket;
        endpoint_t remote;
        DESERIALIZE(event.data, event.size, socket);
        DESERIALIZE(event.data, event.size, remote);

        if (client->waiting
            && memcmp(&remote, &client->server, sizeof(remote)) == 0
            && event.size == sizeof(client->sequence)
            && memcmp(event.data, &client->sequence, event.size) == 0) {
            ping_client_finish(client, buffer, true);
        }
        break;
    }
    }
}


void ping_client_process_time(
    ping_client_t* client, event_buffer_t* buffer, uint64_t now
) {
    client->now = now;

    if (client->waiting && now - client->sent_at >= PING_TIMEOUT_MS) {
        ping_client_finish(client, buffer, false);
    }
}


uint64_t ping_client_next_deadline(const ping_client_t* client) {
    if (!client->waiting) {
        return UINT64_MAX;
    }
    return client->sent_at + PING_TIMEOUT_MS;
}

Events and composition

Composing components means delivering the events emitted by one of them to another. Some sans I/O implementations give each component separate input and output streams for this purpose. This post advocates a different arrangement:

  • every event is broadcast to every component;
  • a component ignores the events that do not concern it;
  • the kind of an event determines which components consume it.

The cost is composability at run time, since events become tied to one pipeline, a fixed arrangement of components. Consider the ping client, which emits SEND_UDP and consumes RECEIVE_UDP, wired to an I/O layer that consumes SEND_UDP and emits RECEIVE_UDP. Inserting a component that encrypts and decrypts the datagrams requires new kinds, and at least one component has to change the events it emits or handles:

eventemitted byhandled by
SEND_UDPping clientcrypto
SEND_UDP_ENCRYPTEDcryptoI/O layer
RECEIVE_UDP_ENCRYPTEDI/O layercrypto
RECEIVE_UDPcryptoping client

In exchange, as long as components need not be composed dynamically (in the manner of GStreamer, where pipelines are assembled at run time), the glue code becomes trivial. A component that talks to several others needs nothing extra, and a component can be made to receive whichever events are of interest to it, for instance one that tracks metrics.

Since the kind determines the handlers, they can be encoded in the kind itself, which avoids the cost of broadcasting. For the ping client, crypto and network pipeline, the events may be defined as follows:

// High byte of a kind: one bit per handler of the event. Low byte: which event
// it is.
#define TO_IO     0x0100
#define TO_APP    0x0200
#define TO_PING   0x0400
#define TO_CRYPTO 0x0800

#define SEND_UDP              (1 | TO_CRYPTO)  // plaintext out: encrypt it
#define SEND_UDP_ENCRYPTED    (2 | TO_IO)      // ciphertext out: send it
#define RECEIVE_UDP_ENCRYPTED (3 | TO_CRYPTO)  // ciphertext in: decrypt it
#define RECEIVE_UDP           (4 | TO_PING)    // plaintext in
#define PING_SEND             (5 | TO_PING)
#define PING_RESULT           (6 | TO_APP)

The pipeline

A pipeline wires several components into a single component-like shape: a struct holding the components and the buffer, and the same three functions. *_process_event pushes the event and propagates, *_process_time passes the time to every component and propagates, and *_next_deadline is the minimum of the components' deadlines. Propagation pops events until the buffer is drained and hands each one to the components its kind names. Events addressed to the I/O layer or to the application leave the pipeline through two functions that the I/O layer provides:

typedef struct {
    ping_client_t client;
    // Turns SEND_UDP into SEND_UDP_ENCRYPTED and back (not shown).
    crypto_t crypto;
    event_buffer_t buffer;
} crypto_ping_t;


// Provided by the I/O layer: SEND_UDP_ENCRYPTED is sent, PING_RESULT is
// reported.
void io_process_event(crypto_ping_t* ping, event_t event);
void app_process_event(crypto_ping_t* ping, event_t event);


void crypto_ping_propagate_events(crypto_ping_t* ping) {
    event_t event;
    while (event_buffer_pop(&ping->buffer, &event)) {
        if (event.kind & TO_PING) {
            ping_client_process_event(&ping->client, &ping->buffer, event);
        }
        if (event.kind & TO_CRYPTO) {
            crypto_process_event(&ping->crypto, &ping->buffer, event);
        }
        if (event.kind & TO_IO) {
            io_process_event(ping, event);
        }
        if (event.kind & TO_APP) {
            app_process_event(ping, event);
        }
    }

    event_buffer_clear(&ping->buffer);
}


void crypto_ping_process_event(crypto_ping_t* ping, event_t event) {
    memcpy(
        event_buffer_push(&ping->buffer, event.kind, event.size), event.data,
        event.size
    );

    crypto_ping_propagate_events(ping);
}


void crypto_ping_process_time(crypto_ping_t* ping, uint64_t now) {
    ping_client_process_time(&ping->client, &ping->buffer, now);
    crypto_process_time(&ping->crypto, &ping->buffer, now);

    crypto_ping_propagate_events(ping);
}


uint64_t crypto_ping_next_deadline(const crypto_ping_t* ping) {
    uint64_t a = ping_client_next_deadline(&ping->client);
    uint64_t b = crypto_next_deadline(&ping->crypto);

    return a < b ? a : b;
}

In a well-formed protocol the loop terminates: the components eventually have nothing further to emit and wait for the network, the application or time.

The two functions provided by the I/O layer run while the buffer is being drained, so they must not call back into the pipeline. A request that arises from an event, such as sending the next ping after a result, is recorded and submitted once the call that produced it returns.

The interface of the pipeline differs from a component's in one respect: its functions take no buffer, since the events that leave the pipeline are delivered by calls to io_process_event and app_process_event. The exact interface can be had by giving *_process_event and *_process_time an external event_buffer_t* and copying into it the events addressed to the I/O layer or the application, in place of the two calls. This makes the pipeline usable as a component of a larger pipeline, at the price of a second buffer and a copy per outgoing event. When no such nesting is needed, the direct calls are simpler, and this post uses them.

The I/O layer

The I/O layer is the code that drives a component. It feeds the component with events and timestamps and acts on the I/O and application events the component emits. It implements:

  • The handling of I/O and application events: each is mapped to a socket call or to application logic. In the pipeline of the previous section this is io_process_event and app_process_event, which the I/O layer must provide.
  • A loop over external occurrences (datagrams, the passage of time, requests from the application) that submits each one to the component and waits between them no longer than the next deadline.

The program below uses a blocking socket and waits until the next deadline. A non-blocking socket, an epoll loop (whose timeout argument is exactly this deadline), a thread per socket or the replay of a recorded session would make the same calls, and no protocol code would change. Adapting the protocol to an I/O model amounts to writing this loop.

int main(void) {
    static char memory[4096];
    crypto_ping_t ping = {.buffer = {0, 0, sizeof(memory), memory}};
    endpoint_t server = {/* ... */}, from;
    char datagram[1500];
    // Open the socket, initialize client and crypto...

    crypto_ping_process_time(&ping, now_ms());
    crypto_ping_process_event(
        &ping, (event_t){PING_SEND, sizeof(server), (const char*)&server}
    );

    for (;;) {
        // Wait for a datagram until the next deadline, or forever if there is
        // none.
        uint64_t now = now_ms();
        uint64_t deadline = crypto_ping_next_deadline(&ping);
        int wait_ms = 0;
        if (deadline == UINT64_MAX) {
            wait_ms = -1;
        } else if (deadline > now) {
            wait_ms = (int)(deadline - now);
        }

        int received = poll_udp(
            ping.client.socket, wait_ms, &from, datagram, sizeof(datagram)
        );

        crypto_ping_process_time(&ping, now_ms());
        if (received > 0) {
            char payload[sizeof(int) + sizeof(from) + sizeof(datagram)];
            crypto_ping_process_event(
                &ping,
                build_udp_event(
                    payload, RECEIVE_UDP_ENCRYPTED, ping.client.socket, from,
                    datagram, received
                )
            );
        }
    }
}

Testing

A unit test is a sequence of calls to *_process_event and *_process_time followed by assertions on the events emitted and on the state of the component. No mocks are involved.

A unit test turns into a fuzzing test by deriving that sequence of calls from the fuzzer's input instead.

A kind of test that I have found useful with network protocols in the past is to simulate the network and let a client and a server component talk to each other. It requires no more than a separate event_buffer_t per endpoint and a mapping of the I/O events of one onto the buffer of the other. The test is then the I/O layer of the previous section reduced to a loop that drains the buffers. The following one simulates a ping round trip:

static void deliver(event_t event, event_buffer_t* to, endpoint_t from) {
    int socket;
    endpoint_t remote;
    DESERIALIZE(event.data, event.size, socket);
    DESERIALIZE(event.data, event.size, remote);

    push_udp(to, RECEIVE_UDP, socket, from, event.data, event.size);
}


void test_ping_round_trip(void) {
    char client_memory[1024], server_memory[1024];
    event_buffer_t client_buffer = {
        0, 0, sizeof(client_memory), client_memory
    };
    event_buffer_t server_buffer = {
        0, 0, sizeof(server_memory), server_memory
    };
    ping_client_t client = {.socket = 1};
    ping_server_t server;
    endpoint_t client_endpoint = {.port = 1};
    endpoint_t server_endpoint = {.port = 2};
    ping_result_t result = {0};
    event_t event;

    ping_client_process_time(&client, &client_buffer, 1000);
    memcpy(
        event_buffer_push(&client_buffer, PING_SEND, sizeof(server_endpoint)),
        &server_endpoint, sizeof(server_endpoint)
    );

    for (;;) {
        if (event_buffer_pop(&client_buffer, &event)) {
            ping_client_process_event(&client, &client_buffer, event);
            if (event.kind == SEND_UDP) {
                deliver(event, &server_buffer, client_endpoint);
            }
            if (event.kind == PING_RESULT) {
                DESERIALIZE(event.data, event.size, result);
            }
        } else if (event_buffer_pop(&server_buffer, &event)) {
            ping_server_process_event(&server, &server_buffer, event);
            if (event.kind == SEND_UDP) {
                deliver(event, &client_buffer, server_endpoint);
            }
        } else {
            break;
        }
    }

    assert(result.ok && result.latency_ms == 0);
}

Conclusions

The implementation needed to apply sans I/O is tiny: a flat buffer with a push and a pop, a handful of event kinds and three functions per component. There is no framework to learn, nothing allocated after start-up, and the I/O layer is whatever loop the program already has. In return, tests need no mocks and the protocol code runs unchanged wherever the loop does.

I haven't used this on anything bigger than a ping yet. The plan is to put it to work soon, with ICE, DTLS, SCTP and RTP as the components of the WebRTC from scratch series.