import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:path_provider/path_provider.dart'; /// Passive motion tracing. This class never sends commands or awaits a network /// operation. File writes are buffered and serialized separately from control. class RemoteControlDiagnostics { RemoteControlDiagnostics({Future Function(String)? append}) : _appendOverride = append; static RemoteControlDiagnostics instance = RemoteControlDiagnostics(); static final Object _frameKey = Object(); final Future Function(String)? _appendOverride; final Stopwatch _clock = Stopwatch()..start(); final String _run = DateTime.now().microsecondsSinceEpoch.toString(); final List _pending = []; Future? _directory; Future? _inFlight; Timer? _flushTimer; int _sequence = 0; int _frameSequence = 0; int _sessionSequence = 0; int _dropped = 0; String? activeDevice; int get elapsedUs => _clock.elapsedMicroseconds; void begin(String? device, Map configuration) { activeDevice = device; _sessionSequence++; event('session_start', configuration); } void end(String reason) { event('session_end', {'reason': reason}); activeDevice = null; unawaited(flush()); } /// Local correlation only; no identifiers are added to the wire protocol. T frame(String source, Map fields, T Function() send) { final context = { 'session': _sessionSequence, 'device': activeDevice, 'frame': ++_frameSequence, 'source': source, ...fields, }; return runZoned(send, zoneValues: {_frameKey: context}); } void event(String stage, Map fields) { try { final frame = Zone.current[_frameKey] as Map?; final record = { 'time': DateTime.now().toIso8601String(), 'us': elapsedUs, 'run': _run, 'session': _sessionSequence, 'seq': ++_sequence, 'device': activeDevice, if (frame != null) ...frame, 'stage': stage, ...fields, }; for (final key in record.keys.toList()) { final value = record[key]; if (value is double && !value.isFinite) record[key] = value.toString(); } // A stalled filesystem cannot grow memory without bounds or block control. if (_pending.length >= 2000) { _pending.removeAt(0); _dropped++; } _pending.add('${jsonEncode(record)}\n'); _flushTimer ??= Timer(const Duration(milliseconds: 500), () { _flushTimer = null; unawaited(flush()); }); } catch (_) { // Diagnostics must never interrupt an input, control or safety callback. } } Future _append(String content) async { final override = _appendOverride; if (override != null) return override(content); final directory = await (_directory ??= getApplicationDocumentsDirectory()); final day = DateTime.now().toIso8601String().substring(0, 10); await File( '${directory.path}/remote_control_$day.jsonl', ).writeAsString(content, mode: FileMode.append); } Future flush() { _flushTimer?.cancel(); _flushTimer = null; return _inFlight ??= _drain().whenComplete(() => _inFlight = null); } Future _drain() async { while (_pending.isNotEmpty) { final dropped = _dropped; _dropped = 0; final batch = _pending.join(); _pending.clear(); try { await _append( '${dropped == 0 ? '' : '${jsonEncode({'stage': 'diagnostic_overflow', 'dropped': dropped})}\n'}$batch', ); } catch (_) { // Mark missing records in the next successful write instead of silently // making a logging failure look like a gap in TCP transmission. _dropped += dropped + '\n'.allMatches(batch).length; return; } } } }