trevrpc/server

A TrevRPC server: native QUIC, and QMux over TLS on TCP for clients whose networks block UDP, and optionally the HTTP that TrevRPC does not claim, such as a web application’s pages, from the same port.

Types

Authorizes a call before the server looks up its method, so that a caller it rejects learns nothing about which methods exist: Ok(Nil) lets the call go on, Error(status) ends it with that status, usually Unauthenticated or PermissionDenied. A call the server refuses for optimistic stream compression is replayed by the client and authorized again, so put side effects, such as counting calls against a rate limit, in an interceptor. See trevrpc_server for the details.

pub type Authorizer =
  fn(CallInfo) -> Result(Nil, status.Status)

What an authorizer and the interceptors know of a call: its method’s path (/package.Service/Method), split into its service and method names, and its request metadata, the connection metadata merged in.

pub type CallInfo {
  CallInfo(
    method: String,
    service: String,
    method_name: String,
    metadata: dict.Dict(String, BitArray),
  )
}

Constructors

  • CallInfo(
      method: String,
      service: String,
      method_name: String,
      metadata: dict.Dict(String, BitArray),
    )

A certificate, with its chain, and its key, as a certificate resolver returns them.

pub type Certificate
pub type Config {
  Config(
    port: Int,
    cert_file: String,
    key_file: String,
    development_certificate: option.Option(
      dev_certificate.DevelopmentCertificate,
    ),
    certificate: option.Option(
      fn(Hello) -> Result(Certificate, Nil),
    ),
    acme_tls_alpn: Bool,
    routes: List(Route),
    tcp: Bool,
    tcp_port: option.Option(Int),
    trusted_tcp_proxies: List(String),
    http: Bool,
    webtransport: Bool,
    webtransport_origins: List(String),
    http_fallback: option.Option(fn(http_request.Request) -> Nil),
    misdirected_request_check: Bool,
    validate_all_addresses: Bool,
    max_frame_size: option.Option(Int),
    max_streams_per_connection: option.Option(Int),
    max_concurrent_requests: option.Option(Int),
    graceful_shutdown_timeout: option.Option(Int),
    stream_idle_timeout: option.Option(Int),
    validator: option.Option(
      fn(String) -> option.Option(
        fn(dynamic.Dynamic, BitArray) -> Result(
          Nil,
          status.Status,
        ),
      ),
    ),
    authorizer: option.Option(
      fn(CallInfo) -> Result(Nil, status.Status),
    ),
    interceptors: List(Interceptor),
    telemetry: Bool,
  )
}

Constructors

  • Config(
      port: Int,
      cert_file: String,
      key_file: String,
      development_certificate: option.Option(
        dev_certificate.DevelopmentCertificate,
      ),
      certificate: option.Option(
        fn(Hello) -> Result(Certificate, Nil),
      ),
      acme_tls_alpn: Bool,
      routes: List(Route),
      tcp: Bool,
      tcp_port: option.Option(Int),
      trusted_tcp_proxies: List(String),
      http: Bool,
      webtransport: Bool,
      webtransport_origins: List(String),
      http_fallback: option.Option(fn(http_request.Request) -> Nil),
      misdirected_request_check: Bool,
      validate_all_addresses: Bool,
      max_frame_size: option.Option(Int),
      max_streams_per_connection: option.Option(Int),
      max_concurrent_requests: option.Option(Int),
      graceful_shutdown_timeout: option.Option(Int),
      stream_idle_timeout: option.Option(Int),
      validator: option.Option(
        fn(String) -> option.Option(
          fn(dynamic.Dynamic, BitArray) -> Result(Nil, status.Status),
        ),
      ),
      authorizer: option.Option(
        fn(CallInfo) -> Result(Nil, status.Status),
      ),
      interceptors: List(Interceptor),
      telemetry: Bool,
    )

    Arguments

    port

    The UDP port, 0 for any free one.

    cert_file

    PEM files of the certificate, with its chain, and its key. Both are empty with a development certificate.

    development_certificate

    The rotating self-signed certificate of a local development server (see trevrpc/dev_certificate), in place of cert_file and key_file. The server presents it, and answers requests for /trevrpc/certificate-hashes with its hashes, for the JavaScript client’s fetchServerCertificateHashes option. That path is TrevRPC’s whenever the server speaks HTTP: without a development certificate it answers 404 rather than going to http_fallback.

    certificate

    Returns the certificate of each QUIC and TCP handshake, in place of cert_file and key_file, which must then be empty, so that a certificate that renews, or one per server name, is served from the next handshake on: an ACME client’s, for one. Error(Nil) fails the handshake, as when there is no certificate yet. It runs once per handshake, so it must return what it holds: one that takes longer than the TLS handshake timeout is stopped, and the handshake fails. See trevrpc_server for the details.

    acme_tls_alpn

    Whether the TCP listener also answers the TLS-ALPN-01 challenge of an ACME certificate authority (acme-tls/1, RFC 8737), which asks the certificate resolver, then required, for the challenge certificate.

    tcp

    Whether to listen on TCP for QMux over TLS, by default on the UDP port’s number.

    trusted_tcp_proxies

    The networks, in CIDR notation ("10.0.0.0/8"), of TCP load balancers that forward connections with a PROXY protocol header, version 1 or 2, in front of the TLS handshake. A connection from one of them must begin with the header, whose client becomes the call’s peer; one from anywhere else is never read for a header. None by default. See trevrpc_server for the details.

    http

    Whether to serve the HTTP mapping, over HTTP/3 and HTTP/2, which the Android client uses.

    webtransport

    Whether to serve browsers: WebTransport over HTTP/3, and QMux over WebSocket on the TCP listener.

    webtransport_origins

    The origins of the pages, besides the server’s own, that may open a browser session. Browsers always send an Origin; clients that send none are admitted too.

    http_fallback

    The handler of every HTTP request TrevRPC does not claim, over HTTP/3 on the UDP port, and HTTP/2 and HTTP/1.1 on the TCP listener, even with http and webtransport off: see trevrpc/http_request. TrevRPC claims the HTTP path while either of them is on.

    misdirected_request_check

    Whether an HTTP request whose host is another name than the TLS server name (SNI) its client sent for the connection is answered 421 Misdirected Request, as browsers that reuse a connection for another name the certificate covers need to retry on a connection of their own. Turn it off behind a proxy that terminates TLS and sends a server name of its own. See trevrpc_server for the details.

    validate_all_addresses

    Whether every QUIC connection attempt from an address QUIC has not validated must first prove it with a Retry packet, before the server keeps any state for the connection, which costs the client a round trip, against a flood of handshakes from spoofed addresses. A client that kept the address validation token of an earlier connection skips it. Off by default.

    graceful_shutdown_timeout

    Milliseconds the handlers get to finish on shutdown.

    stream_idle_timeout

    Milliseconds a streaming call’s request side may go without a message while its handler waits for one, and its handler without sending a response, not counting those waits; the call then fails with Unavailable. None by default, so that quiet streams work.

    validator

    Checks request messages before handlers see them: see trevrpc/validator.

    authorizer

    Authorizes every call before its method is looked up.

    interceptors

    Run in order before the handler of every call, the first registering the finish function that runs last.

    telemetry

    Whether every call emits the telemetry events of trevrpc_telemetry, which cost a little of every call, so they are off by default.

How a call ended: its method, as in CallInfo, the status it ended with, and the microseconds since its stream opened. An Internal status keeps the message the client does not see.

pub type Finished {
  Finished(
    method: String,
    service: String,
    method_name: String,
    status: status.Status,
    elapsed: Int,
  )
}

Constructors

  • Finished(
      method: String,
      service: String,
      method_name: String,
      status: status.Status,
      elapsed: Int,
    )

The transport of a handshake: QUIC on the UDP port, or TLS on the TCP listener.

pub type HandshakeTransport {
  Quic
  Tcp
}

Constructors

  • Quic
  • Tcp

What a TLS handshake tells of the certificate it wants: the server name (SNI) the client sent, if any, the transport, and whether it is the TLS-ALPN-01 challenge of an ACME certificate authority, which only the TCP listener sees, with acme_tls_alpn on.

pub type Hello {
  Hello(
    server_name: option.Option(String),
    transport: HandshakeTransport,
    acme_challenge: Bool,
  )
}

Constructors

Runs before the handler of every call that was authorized and whose method the server has, once per handler invocation: interceptor makes one from a function, and trevrpc/rate_limit has a ready-made one.

pub type Interceptor

A method’s handler.

pub type Route
pub type Server

Values

pub fn bidi(
  method: schema.Method(request, response),
  handler: fn(handler.Call(request, response)) -> Result(
    Nil,
    status.Status,
  ),
) -> Route
pub fn certificate_from_dynamic(
  certificate: dynamic.Dynamic,
) -> Result(Certificate, String)

A certificate from an Erlang map of the DER certificate cert, its decoded private key key and the DER certificates of its chain, cert_chain, if it has one: what an Erlang certificate source gives, such as the autocert package’s manager.

pub fn certificate_from_pem(
  cert: String,
  key: String,
) -> Result(Certificate, String)

A certificate from PEM: the certificate, with its chain after it, and its unencrypted key, which must be the certificate’s. Decode it once, not in the resolver.

pub fn client_streaming(
  method: schema.Method(request, response),
  handler: fn(handler.Call(request, response)) -> Result(
    response,
    status.Status,
  ),
) -> Route
pub fn config(
  port: Int,
  cert_file: String,
  key_file: String,
  routes: List(Route),
) -> Config

A server on port with these credentials and routes, every other option at its default.

pub fn development_config(
  port: Int,
  certificate: dev_certificate.DevelopmentCertificate,
  routes: List(Route),
) -> Config

A server on port that presents a development certificate, with these routes, every other option at its default.

pub fn interceptor(
  intercept: fn(CallInfo) -> Result(
    option.Option(fn(Finished) -> Nil),
    status.Status,
  ),
) -> Interceptor

An interceptor that runs intercept for each call: Ok(Some(finish)) registers a function the server calls once with how the call ended, however it ended, in a process of its own, Ok(None) none, and Error(status) ends the call instead, without running the handler or later interceptors, whose earlier ones still finish.

pub fn port(server: Server) -> Result(Int, Nil)

The UDP port the server listens on, unless it has stopped.

pub fn server_streaming(
  method: schema.Method(request, response),
  handler: fn(request, handler.Call(request, response)) -> Result(
    Nil,
    status.Status,
  ),
) -> Route
pub fn start(config: Config) -> Result(Server, String)

Starts a server, linked to the calling process: it stops when that process exits. An error says what failed, such as credentials that cannot be read, a port in use, or two routes for one path.

pub fn stop(server: Server) -> Nil

Shuts the server down gracefully, and returns once it is down. Stopping a server that is already down does nothing.

pub fn tcp_port(server: Server) -> Result(Int, Nil)

The TCP port, unless TCP is off or the server has stopped.

pub fn unary(
  method: schema.Method(request, response),
  handler: fn(request, handler.Call(request, response)) -> Result(
    response,
    status.Status,
  ),
) -> Route
✨ Search Document