import 'dart:collection'; /// Sliding-window packets-per-second counter. /// /// Measures wall-clock arrival rate, which intentionally differs from the /// timestamp_us field in the packet (server time). Network jitter makes the /// two diverge. class PpsCounter { PpsCounter({this.window = const Duration(seconds: 1)}); final Duration window; final Queue _arrivals = Queue(); void recordArrival([DateTime? now]) { _arrivals.add(now ?? DateTime.now()); _evictOld(now); } /// Current PPS measurement. double current([DateTime? now]) { _evictOld(now); final secs = window.inMilliseconds / 1000.0; return _arrivals.length / secs; } void reset() => _arrivals.clear(); void _evictOld(DateTime? now) { final cutoff = (now ?? DateTime.now()).subtract(window); while (_arrivals.isNotEmpty && _arrivals.first.isBefore(cutoff)) { _arrivals.removeFirst(); } } }