///|
// The host owns connection establishment, TLS and deadlines. This synchronous
// driver owns the protocol transaction and cannot silently pass through errors.
pub fn exchange(
  request : Message,
  read : () -> Result[Bytes, ProtocolError],
  write : (Bytes) -> Result[Unit, ProtocolError],
  preview~ : Int32? = None,
  allow_204~ : Bool = true,
  bounds~ : Limits = limits(),
  max_reads~ : Int32 = 4096,
) -> Result[Action, ProtocolError] {
  if max_reads < 1 {
    return Err(LimitExceeded("max_reads must be positive"))
  }
  let session = match new_session(request, preview~, allow_204~, bounds~) {
    Ok(s) => s
    Err(e) => return Err(e)
  }
  let first = match session.start() {
    Ok(bytes) => bytes
    Err(e) => return Err(e)
  }
  match write(first) {
    Ok(_) => ()
    Err(e) => return Err(e)
  }
  for _index = 0; _index < max_reads; _index = _index + 1 {
    let bytes = match read() {
      Ok(value) => value
      Err(e) => return Err(e)
    }
    if bytes.is_empty() {
      return Err(Incomplete)
    }
    let actions = match session.receive(bytes) {
      Ok(a) => a
      Err(e) => return Err(e)
    }
    for action in actions {
      match action {
        Send(wire) =>
          match write(wire) {
            Ok(_) => ()
            Err(e) => return Err(e)
          }
        NeedInput => ()
        Unchanged | Adapted(_) | Rejected(_, _) =>
          match session.finish() {
            Ok(_) => return Ok(action)
            Err(e) => return Err(e)
          }
      }
    }
  }
  Err(LimitExceeded("transaction receive budget exceeded"))
}