flushToNative method

Future<void> flushToNative()

Drains everything buffered on the Dart side to native, then asks native to persist its in-memory bridge queue to the disk buffer. Completes only once the spans are durable (or the attempt failed).

Used by Dart error handlers (before the isolate dies) and app lifecycle transitions (paused/detached).

Implementation

Future<void> flushToNative() async {
  // Wait for any in-flight eager push so we don't interleave batches.
  while (_isFlushing) {
    await Future<void>.delayed(const Duration(milliseconds: 5));
  }
  _isFlushing = true;
  try {
    while (_spanBuffer.isNotEmpty) {
      final batchSize = _spanBuffer.length < _maxExportBatchSize
          ? _spanBuffer.length
          : _maxExportBatchSize;
      final batch = _spanBuffer.sublist(0, batchSize);
      _spanBuffer.removeRange(0, batchSize);
      final payload = batch.map(_serialize).toList();
      try {
        await _platform.exportSpans(payload);
      } catch (e) {
        _log.warning('Failed to bridge ${batch.length} spans to native. $e');
        break;
      }
    }
  } finally {
    _isFlushing = false;
  }
  try {
    await _platform.flushSpans();
  } catch (e) {
    _log.warning('Native durable flush failed. $e');
  }
}