///|
// Keep the public String-keyed API while upstream compares HTTP names ignoring case.
fn to_upstream_headers(
  headers : Map[String, String],
) -> Map[@async_http.CaseInsensitiveString, String] {
  let result : Map[@async_http.CaseInsensitiveString, String] = Map([])
  for name, value in headers {
    result[@async_http.CaseInsensitiveString(name)] = value
  }
  result
}

///|
fn extract_host_url(url : String) -> String {
  let start = if url.has_prefix("https://") {
    8
  } else if url.has_prefix("http://") {
    7
  } else {
    0
  }
  let mut path_start = -1
  for i = start; i < url.length(); i = i + 1 {
    if url[i].to_int() == '/'.to_int() {
      path_start = i
      break
    }
  }
  if path_start == -1 {
    url
  } else {
    url[:path_start].to_owned()
  }
}

///|
fn extract_path_from_url(url : String) -> String {
  let start = if url.has_prefix("https://") {
    8
  } else if url.has_prefix("http://") {
    7
  } else {
    0
  }
  let mut path_start = -1
  for i = start; i < url.length(); i = i + 1 {
    if url[i].to_int() == '/'.to_int() {
      path_start = i
      break
    }
  }
  if path_start == -1 {
    "/"
  } else {
    url[path_start:].to_owned()
  }
}

///|
fn to_response(resp : @async_http.ResponseHeader) -> Response {
  let headers : Map[String, String] = Map([])
  for k, v in resp.headers {
    headers[k.to_string().to_lower()] = v
  }
  let cookies = resp.cookies.map(to_cookie)
  Response::{ code: resp.code, reason: resp.reason, headers, cookies, }
}

///|
fn to_cookie(cookie : @async_http.Cookie) -> Cookie {
  Cookie(
    cookie.name,
    cookie.value,
    path?=cookie.path,
    expires_raw?=cookie.expires_raw,
    max_age?=cookie.max_age,
    domain?=cookie.domain,
    secure=cookie.secure,
    http_only=cookie.http_only,
    extensions=cookie.extensions,
  )
}

///|
fn from_cookie(cookie : Cookie) -> @async_http.Cookie {
  @async_http.Cookie(
    cookie.name,
    cookie.value,
    path?=cookie.path,
    expires_raw?=cookie.expires_raw,
    max_age?=cookie.max_age,
    domain?=cookie.domain,
    secure=cookie.secure,
    http_only=cookie.http_only,
    extensions=cookie.extensions,
  )
}

///|
fn from_request_method(meth : RequestMethod) -> @async_http.RequestMethod {
  match meth {
    Get => @async_http.RequestMethod::Get
    Head => @async_http.RequestMethod::Head
    Post => @async_http.RequestMethod::Post
    Put => @async_http.RequestMethod::Put
    Delete => @async_http.RequestMethod::Delete
    Connect => @async_http.RequestMethod::Connect
    Options => @async_http.RequestMethod::Options
    Trace => @async_http.RequestMethod::Trace
    Patch => @async_http.RequestMethod::Patch
  }
}

///|
pub struct Client {
  priv write_controller : @io.BinaryWriterController
  priv mut read_controller : @io.BinaryReaderController
  inner : @async_http.ClientConnection
  priv mut request_method : RequestMethod?
  priv mut response_has_no_body : Bool
}

///|
fn to_upstream_proxy(client : Client) -> @async_http.Proxy {
  @async_http.Proxy::custom_tunnel((host, port) => {
    let conn = client.inner
    conn.request(@async_http.RequestMethod::Connect, "\{host}:\{port}")
    let response = conn.end_request()
    guard response.code >= 200 && response.code < 300 else {
      raise HttpError::NetworkError(
        "Proxy CONNECT failed: HTTP \{response.code}",
      )
    }
    conn.skip_response_body()
    conn.enter_passthrough_mode()
    conn
  })
}

///|
pub async fn Client::new(
  url : String,
  headers? : Map[String, String],
  proxy? : Client,
  verify~ : Bool = true,
  trust? : @tls.TrustedRoot,
) -> Client raise HttpError {
  let proxy = proxy.map(to_upstream_proxy)
  let trust = match trust {
    Some(trust) => trust
    None => if verify { @tls.SystemRoot } else { @tls.NoVerification }
  }
  let client = @async_http.ClientConnection(
    url,
    headers=to_upstream_headers(headers.unwrap_or({})),
    proxy?,
    trust~,
  ) catch {
    _ => raise HttpError::InvalidUrl(url)
  }
  Client::{
    write_controller: @io.BinaryWriterController(),
    read_controller: @io.BinaryReaderController(),
    inner: client,
    request_method: None,
    response_has_no_body: false,
  }
}

///|
pub fn Client::close(self : Client) -> Unit {
  self.inner.close()
}

///|
pub async fn Client::request(
  self : Client,
  meth : RequestMethod,
  path : StringView,
  extra_headers? : Map[String, String],
) -> Unit raise HttpError {
  self.read_controller = @io.BinaryReaderController()
  self.request_method = Some(meth)
  self.response_has_no_body = false
  self.inner.request(
    from_request_method(meth),
    path,
    extra_headers=to_upstream_headers(extra_headers.unwrap_or({})),
  ) catch {
    err => raise classify_http_error(err.to_string())
  }
}

///|
pub async fn Client::end_request(self : Client) -> Response raise HttpError {
  let meth = self.request_method
  let response = self.inner.end_request() catch {
    err => raise classify_http_error(err.to_string())
  }
  let resp = to_response(response)
  self.response_has_no_body = response_has_no_body(resp.code, meth)
  self.request_method = None
  resp
}

///|
pub async fn Client::flush(self : Client) -> Unit raise HttpError {
  self.inner.flush_partial_data() catch {
    err => raise classify_http_error(err.to_string())
  }
}

///|
pub async fn Client::skip_response_body(self : Client) -> Unit raise HttpError {
  self.read_controller = @io.BinaryReaderController()
  self.inner.skip_response_body() catch {
    err => raise classify_http_error(err.to_string())
  }
  self.response_has_no_body = false
}

///|
pub async fn Client::enter_passthrough_mode(
  self : Client,
) -> Unit raise HttpError {
  self.read_controller = @io.BinaryReaderController()
  self.response_has_no_body = false
  self.inner.enter_passthrough_mode() catch {
    err => raise classify_http_error(err.to_string())
  }
}

///|
pub async fn Client::get(
  self : Client,
  path : String,
  extra_headers? : Map[String, String],
  body? : &@data.Data,
) -> Response raise HttpError {
  self.request(Get, path, extra_headers=extra_headers.unwrap_or({}))
  ignore(
    self.write(body.unwrap_or("").binary()[:]) catch {
      err => raise classify_http_error(err.to_string())
    },
  )
  self.end_request()
}

///|
pub async fn Client::post(
  self : Client,
  path : String,
  body : &@data.Data,
  extra_headers? : Map[String, String],
) -> Response raise HttpError {
  self.request(Post, path, extra_headers?)
  self.write(body.binary()[:]) catch {
    err => raise classify_http_error(err.to_string())
  }
  self.end_request()
}

///|
pub async fn Client::put(
  self : Client,
  path : String,
  body : &@data.Data,
  extra_headers? : Map[String, String],
) -> Response raise HttpError {
  self.request(Put, path, extra_headers?)
  self.write(body.binary()[:]) catch {
    err => raise classify_http_error(err.to_string())
  }
  self.end_request()
}

///|
impl @io.BinaryReaderImpl for Client with fn get_controller(self) {
  self.read_controller
}

///|
impl @io.BinaryReaderImpl for Client with fn raw_read_impl(
  self,
  buf,
  offset~,
  max_len~,
) {
  if self.response_has_no_body {
    0
  } else {
    self.inner.read_into(buf.mut_view(start=offset, end=offset + max_len))
  }
}

///|
impl @io.BinaryWriterImpl for Client with fn raw_write_impl(
  self,
  buf,
  offset~,
  len~,
) {
  self.inner.write(buf[offset:offset + len])
  len
}

///|
async fn request_internal(
  url : String,
  meth : String,
  headers : Map[String, String],
  body : &@data.Data,
  proxy? : Client,
) -> (Response, &@data.Data) raise HttpError {
  let upstream_proxy = proxy.map(to_upstream_proxy)
  let (resp, body_data) = try {
    match meth {
      "POST" => {
        let (resp, body_data) = @async_http.post_binary(
          url,
          body.binary()[:],
          headers=to_upstream_headers(headers),
          proxy?=upstream_proxy,
        )
        (to_response(resp), body_data.binary())
      }
      "PUT" => {
        let (resp, body_data) = @async_http.put_binary(
          url,
          body.binary()[:],
          headers=to_upstream_headers(headers),
          proxy?=upstream_proxy,
        )
        (to_response(resp), body_data.binary())
      }
      _ => {
        let client = Client::new(extract_host_url(url), proxy?)
        defer client.close()
        let resp = client.get(
          extract_path_from_url(url),
          extra_headers=headers,
          body~,
        )
        (resp, client.read_all().binary())
      }
    }
  } catch {
    err => raise classify_http_error(err.to_string())
  }
  (resp, body_data)
}

///|
async fn create_stream_client(
  url : String,
  meth : RequestMethod,
  headers : Map[String, String],
  body : &@data.Data,
  proxy? : Client,
) -> (Response, Client) raise HttpError {
  let host_url = extract_host_url(url)
  let path = extract_path_from_url(url)
  let client = Client::new(host_url, proxy?)
  let resp = try {
    match meth {
      Get => {
        client.request(Get, path, extra_headers=headers)
        ignore(
          client.write(body.binary()[:]) catch {
            err => raise classify_http_error(err.to_string())
          },
        )
        client.end_request()
      }
      _ => {
        client.request(meth, path, extra_headers=headers)
        ignore(
          client.write(body.binary()[:]) catch {
            err => raise classify_http_error(err.to_string())
          },
        )
        client.end_request()
      }
    }
  } catch {
    err => {
      client.close()
      raise classify_http_error(err.to_string())
    }
  }
  (resp, client)
}

// Streaming API

///|
pub struct Stream {
  inner : @async_http.ClientConnection
}

///|
async fn stream_request_internal(
  url : String,
  meth : String,
  headers : Map[String, String],
  body : &@data.Data,
) -> (Response, Stream) raise HttpError {
  let (resp, client) = create_stream_client(
    url,
    if meth == "POST" {
      Post
    } else if meth == "PUT" {
      Put
    } else {
      Get
    },
    headers,
    body,
  )
  (resp, Stream::{ inner: client.inner, })
}

///|
pub async fn get_stream(
  url : String,
  headers? : Map[String, String],
  body~ : &@data.Data = "",
  proxy? : Client,
) -> (Response, Client) raise HttpError {
  create_stream_client(url, Get, headers.unwrap_or({}), body, proxy?)
}

///|
pub async fn post_stream(
  url : String,
  headers? : Map[String, String],
  proxy? : Client,
) -> Client raise HttpError {
  let host_url = extract_host_url(url)
  let path = extract_path_from_url(url)
  let client = Client::new(host_url, proxy?)
  try client.request(Post, path, extra_headers=headers.unwrap_or({})) catch {
    err => {
      client.close()
      raise classify_http_error(err.to_string())
    }
  } noraise {
    _ => client
  }
}

///|
pub async fn put_stream(
  url : String,
  headers? : Map[String, String],
  proxy? : Client,
) -> Client raise HttpError {
  let host_url = extract_host_url(url)
  let path = extract_path_from_url(url)
  let client = Client::new(host_url, proxy?)
  try client.request(Put, path, extra_headers=headers.unwrap_or({})) catch {
    err => {
      client.close()
      raise classify_http_error(err.to_string())
    }
  } noraise {
    _ => client
  }
}

///|
pub async fn Stream::read_some(self : Stream) -> Bytes? raise HttpError {
  self.inner.read() catch {
    err => raise classify_http_error(error_message(err))
  }
}

///|
pub async fn Stream::read_all(self : Stream) -> Bytes raise HttpError {
  let data : &@data.Data = @io.BinaryReader::read_all(self.inner) catch {
    err => raise classify_http_error(error_message(err))
  }
  data.binary()
}

///|
pub fn Stream::close(self : Stream) -> Unit {
  self.inner.close()
}

// Non-streaming API

///|
pub async fn get(
  url : String,
  headers? : Map[String, String],
  body~ : &@data.Data = "",
  proxy? : Client,
) -> (Response, &@data.Data) raise HttpError {
  request_internal(url, "GET", headers.unwrap_or({}), body, proxy?)
}

///|
pub async fn post(
  url : String,
  body : &@data.Data,
  headers? : Map[String, String],
  proxy? : Client,
) -> (Response, &@data.Data) raise HttpError {
  request_internal(url, "POST", headers.unwrap_or({}), body, proxy?)
}

///|
pub async fn put(
  url : String,
  body : &@data.Data,
  headers? : Map[String, String],
  proxy? : Client,
) -> (Response, &@data.Data) raise HttpError {
  request_internal(url, "PUT", headers.unwrap_or({}), body, proxy?)
}

// Server API

///|
priv struct NativeHttpLimits {
  max_body_bytes : Int32
  request_timeout_ms : Int32
  keep_alive_timeout_ms : Int32
  headers_timeout_ms : Int32
}

///|
fn NativeHttpLimits::enabled(self : NativeHttpLimits) -> Bool {
  self.max_body_bytes > 0 ||
  self.request_timeout_ms > 0 ||
  self.keep_alive_timeout_ms > 0 ||
  self.headers_timeout_ms > 0
}

///|
fn NativeHttpLimits::header_timeout(
  self : NativeHttpLimits,
  first_request : Bool,
) -> Int32 {
  if first_request || self.keep_alive_timeout_ms <= 0 {
    self.headers_timeout_ms
  } else if self.headers_timeout_ms <= 0 {
    self.keep_alive_timeout_ms
  } else {
    @cmp.minimum(self.headers_timeout_ms, self.keep_alive_timeout_ms)
  }
}

///|
async fn[T] with_native_http_timeout(
  timeout_ms : Int32,
  operation : async () -> T,
) -> T {
  if timeout_ms > 0 {
    @async.with_timeout(timeout_ms, operation, error=HttpError::TimeoutError)
  } else {
    operation()
  }
}

///|
priv enum NativeResponseState {
  AwaitingResponse
  SendingResponse
  ResponseFinished
  Passthrough
  ConnectionClosed
}

///|
pub struct Server {
  inner : @async_http.Server
  priv limits : NativeHttpLimits
}

///|
/// A native HTTP listener that can bound the request head before parsing.
pub struct NativeServer {
  priv listener : @socket.TcpServer
  priv headers : @async_http.Headers
  priv limits : NativeHttpLimits
  priv max_request_head_bytes : Int32
}

///|
priv struct NativeRequestHeadLimit {
  socket : @socket.Tcp
  max_bytes : Int32
}

///|
pub struct ServerConnection {
  priv write_controller : @io.BinaryWriterController
  priv mut read_controller : @io.BinaryReaderController
  priv mut upstream_request : @async_http.RequestHeader?
  priv limits : NativeHttpLimits
  priv request_head_limit : NativeRequestHeadLimit?
  priv mut body_remaining : Int32?
  priv mut body_deadline_ms : Int64?
  priv mut body_finished : Bool
  priv mut response_state : NativeResponseState
  inner : @async_http.ServerConnection
}

///|
fn ServerConnection::wrap_native(
  inner : @async_http.ServerConnection,
  limits : NativeHttpLimits,
  request : @async_http.RequestHeader?,
  request_head_limit? : NativeRequestHeadLimit,
) -> ServerConnection {
  {
    inner,
    limits,
    request_head_limit,
    read_controller: @io.BinaryReaderController(),
    write_controller: @io.BinaryWriterController(),
    upstream_request: request,
    body_remaining: None,
    body_deadline_ms: None,
    body_finished: false,
    response_state: AwaitingResponse,
  }
}

///|
fn to_request_method(
  meth : @async_http.RequestMethod,
) -> RequestMethod raise HttpError {
  match meth {
    Get => RequestMethod::Get
    Head => RequestMethod::Head
    Post => RequestMethod::Post
    Put => RequestMethod::Put
    Delete => RequestMethod::Delete
    Connect => RequestMethod::Connect
    Options => RequestMethod::Options
    Trace => RequestMethod::Trace
    Patch => RequestMethod::Patch
    _ => raise HttpError::NotSupported
  }
}

///|
fn to_request(req : @async_http.RequestHeader) -> Request raise HttpError {
  let headers : Map[String, String] = Map([])
  for k, v in req.headers {
    headers[k.to_string().to_lower()] = v
  }
  Request::{ meth: to_request_method(req.meth), path: req.path, headers, }
}

///|
fn to_addr(addr : @socket.Addr) -> Addr {
  Addr::{ text: addr.to_string(), port: addr.port.to_int(), }
}

///|
/// Positive Native limits bound decoded request body bytes, body reading time,
/// and header reading time. On a reused connection the shorter configured
/// header or keep-alive deadline applies while waiting for the next headers.
pub async fn Server::new(
  host? : String,
  port? : Int32,
  headers? : Map[String, String],
  dual_stack? : Bool,
  reuse_addr? : Bool,
  max_request_body_bytes? : Int32,
  request_timeout_ms? : Int32,
  keep_alive_timeout_ms? : Int32,
  headers_timeout_ms? : Int32,
  accept_queue_limit? : Int32,
  trust_proxy? : Bool,
) -> Server raise HttpError {
  let limits = native_http_limits(
    max_request_body_bytes, request_timeout_ms, keep_alive_timeout_ms, headers_timeout_ms,
  )
  ignore(accept_queue_limit)
  ignore(trust_proxy)
  let addr = native_server_addr(host, port)
  let server = @async_http.Server(
    addr,
    dual_stack?,
    reuse_addr?,
    headers=to_upstream_headers(headers.unwrap_or({})),
  ) catch {
    err => raise classify_http_error(err.to_string())
  }
  Server::{ inner: server, limits, }
}

///|
pub fn Server::port(self : Server) -> Int32 {
  self.inner.local_addr().port.to_int()
}

///|
pub fn Server::addr(self : Server) -> Addr {
  to_addr(self.inner.local_addr())
}

///|
pub fn Server::close(self : Server) -> Unit {
  self.inner.close()
}

///|
pub async fn Server::close_graceful(
  self : Server,
  timeout_ms? : Int32,
) -> Unit raise HttpError {
  let timeout = timeout_ms.unwrap_or(30000)
  if timeout < 0 {
    raise HttpError::NetworkError("timeout_ms must be >= 0")
  }
  @async.sleep(0)
  self.close()
}

///|
pub async fn Server::accept(
  self : Server,
) -> (ServerConnection, Addr) raise HttpError {
  let conn = self.inner.accept() catch {
    err => raise classify_http_error(err.to_string())
  }
  (
    ServerConnection::wrap_native(conn, self.limits, None),
    to_addr(conn.remote_addr()),
  )
}

///|
pub async fn Server::run_forever(
  self : Server,
  f : async (Request, &@io.BinaryReader, ServerConnection) -> Unit,
  allow_failure? : Bool,
  max_connections? : Int32,
) -> Unit raise HttpError {
  if !self.limits.enabled() {
    self.inner.run_forever(
      (req, conn) => {
        let wrapped = ServerConnection::wrap_native(
          conn,
          self.limits,
          Some(req),
        )
        f(to_request(req), wrapped, wrapped)
      },
      allow_failure?,
      max_connections?,
    ) catch {
      err => raise classify_http_error(err.to_string())
    }
    return
  }
  defer self.close()
  let slots = max_connections.map(n => @async.Semaphore(n))
  @async.with_task_group(group => {
    for ;; {
      if slots is Some(limit) {
        limit.acquire()
      }
      let (conn, _) = self.accept()
      group.spawn_bg(allow_failure=allow_failure.unwrap_or(true), () => {
        defer conn.close()
        defer (if slots is Some(limit) { limit.release() })
        conn.serve_requests(f)
      })
    }
  }) catch {
    HttpError::_ as err => raise err
    err => raise classify_http_error(err.to_string())
  }
}

///|
async fn ServerConnection::serve_requests(
  self : ServerConnection,
  handle : async (Request, &@io.BinaryReader, ServerConnection) -> Unit,
) -> Unit {
  try {
    for ;; {
      let request = self.read_request()
      handle(request, self, self)
      if self.response_state is SendingResponse {
        self.end_response()
      }
      if !(self.response_state is ResponseFinished) {
        break
      }
    }
  } catch {
    _ if self.response_state is ConnectionClosed => ()
    err => raise err
  }
}

///|
fn native_http_limits(
  max_request_body_bytes : Int32?,
  request_timeout_ms : Int32?,
  keep_alive_timeout_ms : Int32?,
  headers_timeout_ms : Int32?,
) -> NativeHttpLimits {
  {
    max_body_bytes: max_request_body_bytes.unwrap_or(0),
    request_timeout_ms: request_timeout_ms.unwrap_or(0),
    keep_alive_timeout_ms: keep_alive_timeout_ms.unwrap_or(0),
    headers_timeout_ms: headers_timeout_ms.unwrap_or(0),
  }
}

///|
fn native_server_addr(
  host : String?,
  port : Int32?,
) -> @socket.Addr raise HttpError {
  let address = "\{host.unwrap_or("127.0.0.1")}:\{port.unwrap_or(3000)}"
  @socket.Addr::parse(address) catch {
    _ => raise HttpError::InvalidUrl(address)
  }
}

///|
/// Start a native HTTP listener with an on-wire request-head limit. The limit
/// includes the request line and terminating empty line. A non-positive
/// value disables it.
pub async fn NativeServer::new(
  host? : String,
  port? : Int32,
  headers? : Map[String, String],
  dual_stack? : Bool,
  reuse_addr? : Bool,
  max_request_head_bytes~ : Int32 = 16384,
  max_request_body_bytes? : Int32,
  request_timeout_ms? : Int32,
  keep_alive_timeout_ms? : Int32,
  headers_timeout_ms? : Int32,
) -> NativeServer raise HttpError {
  let addr = native_server_addr(host, port)
  let listener = @socket.TcpServer(addr, dual_stack?, reuse_addr?) catch {
    err => raise classify_http_error(err.to_string())
  }
  {
    listener,
    headers: to_upstream_headers(headers.unwrap_or({})),
    limits: native_http_limits(
      max_request_body_bytes, request_timeout_ms, keep_alive_timeout_ms, headers_timeout_ms,
    ),
    max_request_head_bytes,
  }
}

///|
pub fn NativeServer::port(self : NativeServer) -> Int32 {
  self.listener.local_addr().port.to_int()
}

///|
pub fn NativeServer::close(self : NativeServer) -> Unit {
  self.listener.close()
}

///|
pub async fn NativeServer::run_forever(
  self : NativeServer,
  handle : async (Request, &@io.BinaryReader, ServerConnection) -> Unit,
  allow_failure? : Bool,
  max_connections? : Int32,
) -> Unit raise HttpError {
  self.listener.run_forever(
    socket => {
      let inner = @async_http.ServerConnection(socket, headers=self.headers)
      let head_limit = if self.max_request_head_bytes > 0 {
        Some({ socket, max_bytes: self.max_request_head_bytes, })
      } else {
        None
      }
      let conn = ServerConnection::wrap_native(
        inner,
        self.limits,
        None,
        request_head_limit?=head_limit,
      )
      defer conn.close()
      conn.serve_requests(handle)
    },
    allow_failure?,
    max_connections?,
  ) catch {
    err => raise classify_http_error(err.to_string())
  }
}

///|
pub fn ServerConnection::close(self : ServerConnection) -> Unit {
  self.response_state = ConnectionClosed
  self.inner.close()
}

///|
fn ServerConnection::check_open(
  self : ServerConnection,
) -> Unit raise HttpError {
  if self.response_state is ConnectionClosed {
    raise HttpError::NetworkError("HTTP connection is closed")
  }
}

///|
async fn ServerConnection::reject_request(
  self : ServerConnection,
  status : Int32,
  reason : String,
) -> Unit noraise {
  defer self.close()
  if self.response_state is AwaitingResponse {
    try {
      self.inner.send_response(status, reason, extra_headers={
        "Connection": "close",
      })
      self.inner.end_response()
    } catch {
      _ => ()
    }
  }
}

///|
pub fn ServerConnection::client_addr(self : ServerConnection) -> Addr {
  to_addr(self.inner.remote_addr())
}

///|
pub async fn ServerConnection::read_request(
  self : ServerConnection,
) -> Request raise HttpError {
  self.check_open()
  let first_request = self.upstream_request is None
  if !first_request &&
    (self.limits.enabled() || self.request_head_limit is Some(_)) {
    self.skip_request_body()
  }
  self.read_controller = @io.BinaryReaderController()
  self.upstream_request = None
  self.response_state = AwaitingResponse
  let req = with_native_http_timeout(
    self.limits.header_timeout(first_request),
    () => {
      self.check_request_head()
      self.inner.read_request()
    },
  ) catch {
    HttpError::TimeoutError => {
      self.close()
      raise HttpError::TimeoutError
    }
    HttpError::_ as err => raise err
    err => raise classify_http_error(err.to_string())
  }
  self.upstream_request = Some(req)
  if !self.limits.enabled() {
    return to_request(req)
  }
  let declared = match req.headers.get("Content-Length") {
    None => None
    Some(value) =>
      Some(@string.parse_uint64(value, radix=10)) catch {
        err => raise classify_http_error(err.to_string())
      }
  }
  if self.limits.max_body_bytes > 0 &&
    declared is Some(size) &&
    size > self.limits.max_body_bytes.to_uint64() {
    self.reject_request(413, "Payload Too Large")
    raise HttpError::NetworkError("Request body exceeds the configured limit")
  }
  self.body_remaining = if self.limits.max_body_bytes > 0 {
    Some(self.limits.max_body_bytes)
  } else {
    None
  }
  self.body_finished = declared.unwrap_or(0UL) == 0UL &&
    !req.headers.contains("Transfer-Encoding") &&
    !req.headers.contains("Content-Encoding")
  self.body_deadline_ms = if self.limits.request_timeout_ms > 0 &&
    !self.body_finished {
    Some(@async.now() + self.limits.request_timeout_ms.to_int64())
  } else {
    None
  }
  to_request(req)
}

///|
/// Recover the core header for a request read from this connection.
pub fn ServerConnection::upstream_request(
  self : ServerConnection,
  request : Request,
) -> @async_http.RequestHeader? {
  guard self.upstream_request is Some(header) else { return None }
  let parsed = to_request(header) catch { _ => return None }
  if parsed.meth == request.meth &&
    parsed.path == request.path &&
    parsed.headers == request.headers {
    Some(header)
  } else {
    None
  }
}

///|
async fn ServerConnection::check_request_head(self : ServerConnection) -> Unit {
  guard self.request_head_limit is Some(limit) else { return }
  for needed = 1, search_from = 0 {
    let buffered = limit.socket.peek_at_least(needed)
    let head_end = @cmp.minimum(buffered.length(), limit.max_bytes)
    if buffered[search_from:head_end].find(b"\r\n\r\n") is Some(_) {
      return
    }
    if head_end == limit.max_bytes {
      self.reject_request(431, "Request Header Fields Too Large")
      raise HttpError::NetworkError("Request head exceeds the configured limit")
    }
    // Keep the delimiter overlap, then wait for at least one more byte.
    continue head_end + 1, @cmp.maximum(0, head_end - 3)
  }
}

///|
pub async fn ServerConnection::skip_request_body(
  self : ServerConnection,
) -> Unit raise HttpError {
  self.check_open()
  if self.limits.enabled() {
    ignore(@io.BinaryReader::drop_all(self)) catch {
      err => raise classify_http_error(error_message(err))
    }
  } else {
    self.read_controller = @io.BinaryReaderController()
    self.inner.skip_request_body() catch {
      err => raise classify_http_error(err.to_string())
    }
  }
}

///|
pub async fn ServerConnection::send_response(
  self : ServerConnection,
  code : Int32,
  reason : String,
  extra_headers? : Map[String, String],
  cookies~ : Array[Cookie] = [],
) -> Unit raise HttpError {
  self.check_open()
  let cookies = cookies.map(from_cookie)
  self.inner.send_response(
    code,
    reason,
    extra_headers=to_upstream_headers(extra_headers.unwrap_or({})),
    cookies~,
  ) catch {
    err => raise classify_http_error(err.to_string())
  }
  self.response_state = SendingResponse
}

///|
pub async fn ServerConnection::flush(
  self : ServerConnection,
) -> Unit raise HttpError {
  self.inner.flush_partial_data() catch {
    err => raise classify_http_error(err.to_string())
  }
}

///|
pub async fn ServerConnection::end_response(
  self : ServerConnection,
) -> Unit raise HttpError {
  self.check_open()
  self.inner.end_response() catch {
    err => raise classify_http_error(err.to_string())
  }
  self.response_state = ResponseFinished
}

///|
pub async fn ServerConnection::enter_passthrough_mode(
  self : ServerConnection,
) -> Unit raise HttpError {
  self.check_open()
  if self.limits.enabled() {
    self.skip_request_body()
  }
  self.read_controller = @io.BinaryReaderController()
  self.inner.enter_passthrough_mode() catch {
    err => raise classify_http_error(err.to_string())
  }
  self.response_state = Passthrough
}

///|
impl @io.BinaryReaderImpl for ServerConnection with fn get_controller(self) {
  self.read_controller
}

///|
impl @io.BinaryReaderImpl for ServerConnection with fn raw_read_impl(
  self,
  buf,
  offset~,
  max_len~,
) {
  self.check_open()
  if !self.limits.enabled() || self.response_state is Passthrough {
    return self.inner.read_into(
      buf.mut_view(start=offset, end=offset + max_len),
    )
  }
  if self.body_finished {
    return 0
  }
  guard self.body_deadline_ms is Some(deadline) else {
    return self.read_limited_body(buf, offset~, max_len~)
  }
  let remaining = deadline - @async.now()
  if remaining <= 0 {
    self.reject_request(408, "Request Timeout")
    raise HttpError::TimeoutError
  }
  let timeout_ms = @cmp.minimum(
    remaining,
    self.limits.request_timeout_ms.to_int64(),
  ).to_int()
  with_native_http_timeout(timeout_ms, () => {
    self.read_limited_body(buf, offset~, max_len~)
  }) catch {
    HttpError::TimeoutError => {
      self.reject_request(408, "Request Timeout")
      raise HttpError::TimeoutError
    }
    err => raise err
  }
}

///|
async fn ServerConnection::read_limited_body(
  self : ServerConnection,
  buf : FixedArray[Byte],
  offset~ : Int32,
  max_len~ : Int32,
) -> Int32 {
  if self.body_remaining is Some(0) {
    if self.inner.peek() is Some(_) {
      self.reject_request(413, "Payload Too Large")
      raise HttpError::NetworkError("Request body exceeds the configured limit")
    }
    self.body_finished = true
    return 0
  }
  let read_len = @cmp.minimum(max_len, self.body_remaining.unwrap_or(max_len))
  let n = self.inner.read_into(
    buf.mut_view(start=offset, end=offset + read_len),
  )
  if self.body_remaining is Some(left) {
    self.body_remaining = Some(left - n)
  }
  self.body_finished = n == 0
  n
}

///|
impl @io.BinaryWriterImpl for ServerConnection with fn raw_write_impl(
  self,
  buf,
  offset~,
  len~,
) {
  self.inner.write(buf[offset:offset + len])
  len
}

///|
pub impl @io.BinaryReader for Client

///|
pub extend Client with @io.BinaryReader::{
  read_into,
  read_at_least,
  peek,
  peek_at_least,
  read_exactly,
  drop_exactly,
  peek_exactly,
  drop_all,
  peek_until,
}

///|
pub impl @io.BinaryReader for ServerConnection

///|
pub extend ServerConnection with @io.BinaryReader::{
  read_into,
  read_at_least,
  peek,
  peek_at_least,
  read_exactly,
  drop_exactly,
  peek_exactly,
  drop_all,
  peek_until,
}

///|
pub impl @io.BinaryWriter for Client

///|
pub extend Client with @io.BinaryWriter::{write_reader}

///|
impl @io.BinaryWriterImpl for Client with fn get_controller(self) {
  self.write_controller
}

///|
pub impl @io.BinaryWriter for ServerConnection

///|
pub extend ServerConnection with @io.BinaryWriter::{write_reader}

///|
impl @io.BinaryWriterImpl for ServerConnection with fn get_controller(self) {
  self.write_controller
}

///|
impl @io.BinaryReaderImpl for Client with fn name(_self) {
  "Client"
}

///|
impl @io.BinaryReaderImpl for ServerConnection with fn name(_self) {
  "ServerConnection"
}

///|
impl @io.BinaryWriterImpl for Client with fn name(_self) {
  "Client"
}

///|
impl @io.BinaryWriterImpl for Client with fn flush_partial_data(self) {
  self.flush()
}

///|
impl @io.BinaryWriterImpl for ServerConnection with fn name(_self) {
  "ServerConnection"
}

///|
impl @io.BinaryWriterImpl for ServerConnection with fn flush_partial_data(self) {
  self.flush()
}

///|
/// Core's reader/writer errors only derive `Debug`; `Error` still has `Show`.
fn error_message(err : Error) -> String {
  err.to_string()
}