caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
From: "Daniel Bünzli" <daniel.buenzli@erratique.ch>
To: caml-list <caml-list@inria.fr>
Subject: [Caml-list] Non-blocking IO interface design
Date: Sun, 8 Apr 2012 22:37:02 +0200	[thread overview]
Message-ID: <83F8677AD5E142A3BB0EC27C78C0658B@erratique.ch> (raw)

Hello,

This is problematic : 

  https://github.com/williamleferrand/xmlm
  http://ambassadortothecomputers.blogspot.com/2010/08/mixing-monadic-and-direct-style-code.html

To solve this problem I'm looking for a simple interface design to
make my IO modules compatible with monadic concurrency libraries (lwt,
async, [insert your own here]) and event based loops (select(2),
poll(2), etc.). The design should have the following properties:

1. Unified interface for blocking and non-blocking mode. 
2. The existence of the non-blocking mode should not significantly
   impact blocking mode users.
3. Input possible from in_channel, string, refillable fixed-size string 
   buffer (non-blocking mode). 
4. Output possible to out_channel, Buffer.t, flushable fixed-size string
   buffer (non-blocking mode).
5. No third-party IO libraries/paradigms so that the module can adapt
   to the one the user chooses.
6. Reasonably efficient.

I looked for some time into Haskell's enumerators, pipes and other
conduits but I eventually came back to a more ad-hoc approach that
abstracts as follows. I'll gladly take any feedback you may have.

Suppose we want to IO streams of value of `type t`. For example xmlm's
signals (lexemes as they should be called) if you are familiar with
that.

For input (decoding) we begin with a type for input sources, decoders
and a function to create them.

  type src = [ `Channel of in_channel | `String of string | `Manual ]
  type decoder 
  val decoder : src -> decoder

A [`Manual] source means that the client will provide the decoder with
chunks of bytes to decode at his own pace. The function for decoding
is :

  val decode : decoder -> [ `Await | `End | `Error of e | `Yield of t ]

[decode d] is : 

- [`Await] iff [d] has a [`Manual] input source and awaits for
  more input. The client must use [decode_src] (see below) to provide it.
- [`Yield v], if a value [v] of type [t] was decoded. 
- [`End], if the end of input was reached.
- [`Error e], if an error [e] occured. If you are interested in a
  best-effort decoding, you can still continue to decode after
  the error.

For [`Manual] sources the function [decode_src] is used to provide
the byte chunks to read from : 

  val decode_src : decoder -> string -> int -> int -> unit

[decode_src d s k l] provides [d] with [l] bytes to read, starting at
[k] in [s]. This byte range is read by calls to [decode] with [d]
until `Await is returned. To signal the end of input call the function
with [l = 0].

That's all what is needed for input. Just a note on the `Error
case. Decoders should report any decoding errors with [`Error] to
allow standard compliant decodings. However at that point they should
give the opportunity to the client to continue to perform a best
effort decoding. In that case [decode] should always eventually return
[`End] even if [`Error]s were reported before. I think best-effort
decoding on errors is a good thing: I was annoyed more than once with
xmlm simply failing with `Malformed_char_stream on files produced by
legacy software that gave invalid UTF-8 encodings for funky
characters. Rather than fail and block the client at that point it's
better to report an error and let it continue if it wishes so by
replacing the invalid byte sequence with U+FFFD.

For output (encoding) we begin with a type for output destinations,
encoders and a function to create them.

  type dst = [ `Channel of out_channel | `Buffer of Buffer.t | `Manual ]
  type encoder
  val encoder : dst -> encoder

A [`Manual] destination means that the client will provide to the
decoder the chunks of bytes to encode to at his own pace. The function
for encoding is :

  val encode : 
    encoder -> [ `Await | `End | `Yield of t ] -> [ `Ok | `Partial ]

[encode e v] is 

- [`Partial] iff [e] has a [`Manual] destination and needs more output
  storage. The client must use [encode_dst] (see below) to provide it
  and then call [encode e `Await] until [`Ok] is returned.
- [`Ok] when the encoder is ready to encode a new [`Yield] or [`End].

Raises [Invalid_argument] if a [`Yield] or [`End] is encoded after a 
[`Partial] encode (this is done to prevent the encoder from having 
to bufferize [`Yield]s). 

For [`Manual] destinations the function [encode_dst] is used to provide
the byte chunks to write to : 

  val encode_dst : encoder -> string -> int -> int -> unit

[encode_dst e s k l] provides [e] with [l] bytes to write, starting at
[k] in [s]. This byte range is written by calls to [encode] with [e]
until [`Partial] is returned. To know the remaining number of 
non-written free bytes in [s] the function [encode_dst_rem] can be
used:

  val encode_dst_rem : encoder -> int

[encoder_dst_rem e] is the remaining number of non-written, free bytes
in the last buffer provided with [encode_dst]. A well-behaved encoder
should always fill all the bytes it is given, except for the buffer
that encodes the `End.

One note on [`Manual] destinations, encoding [`End] always returns
[`Partial]. The client should then as usual use [encode_dst] and
continue with [`Await] until [`Ok] is returned at which point
[encode_dst_rem e] is guaranteed to be the size of the last provided
buffer (i.e. nothing was written, this is a good property for the
client's loops, see the example code).

To validate the approach and provide a blueprint for implementing the
interface I implemented both a blocking codec and a (cps) non-blocking
codec for a simplified grammar of s-expressions. It's available here :

  http://erratique.ch/repos/nbcodec
  git clone http://erratique.ch/repos/nbcodec.git

I think that the first five points are mostly met and the
cps transformation of blocking into non-blocking is relatively
straightforward and remains readable in my opinion. Regarding the 6th
point, using the included `setrip.native` program on 32 Mo of randomly
generated s-expressions seem to indicate that:

  The non-blocking decoder can be at least 1.35 slower than blocking
  The non-blocking encoder can be at least 1.1 slower than blocking

Now I don't think these "bad" numbers should be taken to dismiss the
approach since in the context of a larger reactive program a blocking
codec may actually incur performance and scability issues that cannot
be shown by this example program.

Thanks in advance for your input,

Daniel

P.S. 
Numbers above were gathered by timing these invocations :

  ./setrip.native -enc -unix -rseed 1067894368 > 1067894368.sexp
  ./setrip.native -enc -b -rseed 1067894368 > 1067894368.sexp

  ./setrip.native -dec -unix < 1067894368.sexp
  ./setrip.native -dec -b < 1067894368.sexp

This does however also compare two different IO mechanisms: pervasives
channels for blocking vs direct calls to Unix for non-blocking.
Remove the `-unix` flag to compare the timings with the same IO
mechanisms (I then get 1.45 for the decoder and still 1.1 for the
encoder).


             reply	other threads:[~2012-04-08 20:37 UTC|newest]

Thread overview: 5+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2012-04-08 20:37 Daniel Bünzli [this message]
2012-04-09 19:28 ` Anil Madhavapeddy
2012-04-10  8:21   ` Daniel Bünzli
2012-04-10 12:40     ` Yaron Minsky
2012-04-14  9:46       ` Daniel Bünzli

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=83F8677AD5E142A3BB0EC27C78C0658B@erratique.ch \
    --to=daniel.buenzli@erratique.ch \
    --cc=caml-list@inria.fr \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).