|
| 1 | +import 'dart:async'; |
| 2 | +import 'dart:convert'; |
| 3 | + |
| 4 | +import 'package:flutter/foundation.dart'; |
| 5 | +import 'package:shared_preferences/shared_preferences.dart'; |
| 6 | + |
| 7 | +import 'package:sentracore_dashboard/models/history_sample.dart'; |
| 8 | +import 'package:sentracore_dashboard/models/system_state.dart'; |
| 9 | + |
| 10 | +class HistoryProvider extends ChangeNotifier { |
| 11 | + static const _kHistorySamples = 'history_samples_v1'; |
| 12 | + |
| 13 | + /// Default sampling cadence (engine pushes every ~2s; we downsample to keep storage sane). |
| 14 | + static const Duration sampleInterval = Duration(seconds: 30); |
| 15 | + |
| 16 | + /// Hard cap to prevent unbounded growth in SharedPreferences. |
| 17 | + static const int maxSamples = |
| 18 | + 12000; // ~4 days at 30s; UI ranges use downsampling |
| 19 | + |
| 20 | + final List<HistorySample> _samples = []; |
| 21 | + bool _loaded = false; |
| 22 | + DateTime? _lastSampleAt; |
| 23 | + Timer? _saveDebounce; |
| 24 | + |
| 25 | + List<HistorySample> get samples => List<HistorySample>.unmodifiable(_samples); |
| 26 | + bool get loaded => _loaded; |
| 27 | + |
| 28 | + Future<void> load() async { |
| 29 | + if (_loaded) return; |
| 30 | + final p = await SharedPreferences.getInstance(); |
| 31 | + final raw = p.getString(_kHistorySamples); |
| 32 | + if (raw == null || raw.trim().isEmpty) { |
| 33 | + _loaded = true; |
| 34 | + notifyListeners(); |
| 35 | + return; |
| 36 | + } |
| 37 | + try { |
| 38 | + final decoded = jsonDecode(raw); |
| 39 | + if (decoded is List) { |
| 40 | + _samples |
| 41 | + ..clear() |
| 42 | + ..addAll( |
| 43 | + decoded.whereType<Map>().map( |
| 44 | + (m) => HistorySample.fromJson(Map<String, dynamic>.from(m)), |
| 45 | + ), |
| 46 | + ); |
| 47 | + _samples.sort((a, b) => a.at.compareTo(b.at)); |
| 48 | + _lastSampleAt = _samples.isNotEmpty ? _samples.last.at : null; |
| 49 | + } |
| 50 | + } catch (_) { |
| 51 | + // Corrupt payload -> start clean. |
| 52 | + _samples.clear(); |
| 53 | + } |
| 54 | + _loaded = true; |
| 55 | + notifyListeners(); |
| 56 | + } |
| 57 | + |
| 58 | + void clear() { |
| 59 | + _samples.clear(); |
| 60 | + _lastSampleAt = null; |
| 61 | + notifyListeners(); |
| 62 | + _scheduleSave(); |
| 63 | + } |
| 64 | + |
| 65 | + /// Called by EngineProvider on every live state; this function decides whether |
| 66 | + /// we should record a new sample based on [sampleInterval]. |
| 67 | + void recordIfDue({ |
| 68 | + required DateTime now, |
| 69 | + required SystemState state, |
| 70 | + required List<ProcessImpact> processes, |
| 71 | + }) { |
| 72 | + final n = state.normalized; |
| 73 | + if (n == null) return; |
| 74 | + |
| 75 | + final last = _lastSampleAt; |
| 76 | + if (last != null && now.difference(last) < sampleInterval) return; |
| 77 | + |
| 78 | + final diskPct = |
| 79 | + ((n.diskIo.totalOpsPerSec) / 500.0 * 100.0).clamp(0.0, 100.0); |
| 80 | + final top = List<ProcessImpact>.from(processes) |
| 81 | + ..sort((a, b) => b.impactScore.compareTo(a.impactScore)); |
| 82 | + final top10 = top.take(10).map((p) { |
| 83 | + return HistoryProcessSample( |
| 84 | + name: p.name, |
| 85 | + pid: p.pid, |
| 86 | + cpuPercent: p.cpuImpact, |
| 87 | + memPercent: p.memoryPercent, |
| 88 | + impact: p.impactScore, |
| 89 | + ); |
| 90 | + }).toList(); |
| 91 | + |
| 92 | + _samples.add( |
| 93 | + HistorySample( |
| 94 | + at: now, |
| 95 | + cpuPercent: n.cpu.smoothed.clamp(0.0, 100.0).toDouble(), |
| 96 | + memPercent: n.memory.smoothed.clamp(0.0, 100.0).toDouble(), |
| 97 | + diskPressurePercent: diskPct.toDouble(), |
| 98 | + topProcesses: top10, |
| 99 | + ), |
| 100 | + ); |
| 101 | + _samples.sort((a, b) => a.at.compareTo(b.at)); |
| 102 | + _lastSampleAt = now; |
| 103 | + |
| 104 | + // Retain only the newest maxSamples. |
| 105 | + if (_samples.length > maxSamples) { |
| 106 | + _samples.removeRange(0, _samples.length - maxSamples); |
| 107 | + } |
| 108 | + |
| 109 | + notifyListeners(); |
| 110 | + _scheduleSave(); |
| 111 | + } |
| 112 | + |
| 113 | + void _scheduleSave() { |
| 114 | + _saveDebounce?.cancel(); |
| 115 | + _saveDebounce = Timer(const Duration(milliseconds: 600), () { |
| 116 | + unawaited(_saveNow()); |
| 117 | + }); |
| 118 | + } |
| 119 | + |
| 120 | + Future<void> _saveNow() async { |
| 121 | + final p = await SharedPreferences.getInstance(); |
| 122 | + final payload = jsonEncode(_samples.map((s) => s.toJson()).toList()); |
| 123 | + await p.setString(_kHistorySamples, payload); |
| 124 | + } |
| 125 | + |
| 126 | + @override |
| 127 | + void dispose() { |
| 128 | + _saveDebounce?.cancel(); |
| 129 | + _saveDebounce = null; |
| 130 | + super.dispose(); |
| 131 | + } |
| 132 | +} |
0 commit comments