flush method

Future<int> flush()

Sends what is queued, a batch at a time, until a send does not succeed. Answers how many records were accepted.

Implementation

Future<int> flush() async {
  if (_sending) return 0;
  _sending = true;
  int accepted = 0;
  try {
    while (_pending.isNotEmpty) {
      final List<DVLogRecord> sending =
          _pending.take(batch).toList(growable: false);
      final int status;
      try {
        status = await _post(jsonEncode(<String, Object?>{
          'install': installId,
          'release': release,
          'platform': platform,
          'records': <Object?>[
            for (final DVLogRecord record in sending) record.toJson(),
          ],
        }));
      } on Object {
        break; // Unreachable: kept, and sent with the next flush.
      }
      if (status >= 200 && status < 300) {
        _removeFirst(sending.length);
        accepted += sending.length;
        continue;
      }
      // Worth sending again: a busy backend, or one deployed before it
      // served this endpoint.
      if (status == 404 || status == 429 || status >= 500) break;
      // Any other 4xx is a batch that will never be accepted.
      _removeFirst(sending.length);
      _dropped += sending.length;
    }
  } finally {
    _sending = false;
  }
  return accepted;
}