ioSend function

Future<HttpResponse> ioSend(
  1. HttpClient client,
  2. HttpRequest r, {
  3. Duration timeout = const Duration(seconds: 20),
})

One call of ioFetch: r sent over client, no redirect followed (a 3xx answered as it came, which the kit reads as no answer), at most fetchBodyMost bytes of the answer read (one that runs past it, or says it will, throws: no answer, and it is never held whole), an answer that is not UTF-8 refused (so its text is never longer than its bytes, and dartFetch's cap on the text is the same 4 MiB), the whole call given timeout. Past the timeout nothing more is sent: a request still waiting for its connection (a client of the app's with few connections a host, say) is aborted as soon as it has one, before a byte of it leaves, so a swap the kit has taken for unanswered never reaches the mint later. Nothing is kept between calls, so any number may run at once.

Implementation

Future<HttpResponse> ioSend(io.HttpClient client, HttpRequest r, {Duration timeout = const Duration(seconds: 20)}) async {
  io.HttpClientRequest? q;
  var expired = false;
  TimeoutException timedOut() => TimeoutException('no answer within $timeout', timeout);
  // nothing goes out once the timeout has fired: checked after every wait and before every byte is handed over
  void stillInTime(io.HttpClientRequest req) {
    if (expired) {
      req.abort();
      throw timedOut();
    }
  }

  Future<HttpResponse> call() async {
    final req = await client.openUrl(r.method, Uri.parse(r.url));
    q = req;
    stillInTime(req);
    req.followRedirects = false;
    req.maxRedirects = 0;
    r.headers.forEach(req.headers.set);
    if (r.method != 'GET' && r.method != 'HEAD') {
      final body = utf8.encode(r.body);
      if (!r.headers.keys.any((k) => k.toLowerCase() == 'content-type')) req.headers.contentType = io.ContentType.json;
      req.contentLength = body.length;
      stillInTime(req);
      req.add(body);
    }
    stillInTime(req);
    final res = await req.close();
    stillInTime(req);
    if (res.contentLength > fetchBodyMost) {
      req.abort();
      throw StateError('an answer longer than $fetchBodyMost bytes');
    }
    final bytes = BytesBuilder(copy: false);
    await for (final chunk in res) {
      if (bytes.length + chunk.length > fetchBodyMost) {
        req.abort();
        throw StateError('an answer longer than $fetchBodyMost bytes');
      }
      bytes.add(chunk);
    }
    // the raw bytes are capped above; refused when not UTF-8, the text is no longer than them (a replacement
    // character for each bad byte would make up to three times as much)
    return HttpResponse(status: res.statusCode, body: utf8.decode(bytes.takeBytes()));
  }

  return call().timeout(
    timeout,
    onTimeout: () {
      expired = true;
      q?.abort();
      throw timedOut();
    },
  );
}