Connect RPC protocol in pure OCaml
README.md

connect #

The Connect RPC protocol for OCaml, without I/O.

Connect is an RPC protocol from Buf that runs Protocol Buffers services over plain HTTP: a unary call is an ordinary POST whose body is the message, so curl and browsers can call it, and the same server also answers gRPC and gRPC-Web clients. connect implements the parts of the protocol that do not depend on a transport, so that an HTTP/1.1, HTTP/2 or HTTP/3 adapter can be written on top of it. It has the same shape as the nox-grpc library and shares its status codes.

The library covers the status codes and their Connect names, message codecs (Protocol Buffers, raw bytes and JSON text), method descriptors and their HTTP paths, content types, the protocol headers, custom metadata with base64 -bin values, the JSON error and end-stream bodies, and the envelope framing of streaming calls. Compression is named but not implemented, and there is no HTTP adapter yet.

Install #

$ opam install connect

If opam cannot find the package, add the overlay repository first:

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install connect

Usage #

A method descriptor gives the HTTP path of a call, and Connect.Metadata gives the headers a unary Connect request carries:

let say =
  Connect.Method.v ~service:"connectrpc.eliza.v1.ElizaService" ~name:"Say"
    Connect.Method.Unary ~request:Connect.Codec.json_string
    ~response:Connect.Codec.json_string

let path = Connect.Method.path say

let headers =
  [
    ("content-type", Connect.Metadata.content_type ~codec:"json" ());
    Connect.Metadata.protocol_version_header;
  ]

A server that fails a call answers with a JSON error body:

let not_found =
  Connect.Error.v ~code:Connect.Status.Not_found ~message:"no such user" ()
  |> Connect.Error.to_string

A streaming body is a sequence of envelopes. Each envelope is a one-byte flags field, a four-byte big-endian length and that many bytes of message; flag 0x01 marks a compressed message and flag 0x02 the final envelope of a response, whose body is the JSON end-stream object carrying the error, if any, and the trailers. Connect.Envelope.Reader decodes them from the chunks a transport delivers, and refuses an envelope longer than 4 MiB unless told otherwise.

API #

The top-level module Connect exposes Status, Codec, Method, Metadata, Compression, Error, End_stream and Envelope; their interfaces are in lib/.

License #

ISC. See LICENSE.md.