| 61 | } |
| 62 | |
| 63 | func (st *Tracker) applySampleLocked(sample Sample, activeAt time.Time) { |
| 64 | entry, exists := st.stats[sample.PublicKey] |
| 65 | if !exists { |
| 66 | entry = &Entry{ |
| 67 | Email: sample.Email, |
| 68 | } |
| 69 | st.stats[sample.PublicKey] = entry |
| 70 | } |
| 71 | entry.Email = sample.Email |
| 72 | entry.IsDeleted = false |
| 73 | |
| 74 | // Restore pending delta baseline when a deleted entry is re-added. |
| 75 | readded := false |
| 76 | if entry.LastDeltaRx != 0 || entry.LastDeltaTx != 0 { |
| 77 | entry.BaseRx = sample.Rx - entry.LastDeltaRx |
| 78 | entry.BaseTx = sample.Tx - entry.LastDeltaTx |
| 79 | entry.LastDeltaRx = 0 |
| 80 | entry.LastDeltaTx = 0 |
| 81 | readded = true |
| 82 | } |
| 83 | |
| 84 | // Skip update if values haven't changed |
| 85 | if entry.CurrentRx == sample.Rx && entry.CurrentTx == sample.Tx { |
| 86 | entry.EndpointIP = sample.EndpointIP |
| 87 | return |
| 88 | } |
| 89 | |
| 90 | // Detect kernel counter rollback/reset and preserve pending deltas |
| 91 | if !readded && (sample.Rx < entry.CurrentRx || sample.Tx < entry.CurrentTx) { |
| 92 | pendingRx := entry.CurrentRx - entry.BaseRx |
| 93 | pendingTx := entry.CurrentTx - entry.BaseTx |
| 94 | if pendingRx < 0 { |
| 95 | pendingRx = 0 |
| 96 | } |
| 97 | if pendingTx < 0 { |
| 98 | pendingTx = 0 |
| 99 | } |
| 100 | entry.BaseRx = sample.Rx - pendingRx |
| 101 | entry.BaseTx = sample.Tx - pendingTx |
| 102 | } |
| 103 | |
| 104 | // Any traffic growth implies peer is active. |
| 105 | if sample.Rx > entry.CurrentRx || sample.Tx > entry.CurrentTx { |
| 106 | entry.LastActiveTime = activeAt |
| 107 | } |
| 108 | |
| 109 | entry.CurrentRx = sample.Rx |
| 110 | entry.CurrentTx = sample.Tx |
| 111 | |
| 112 | // Update endpoint from periodic check. |
| 113 | entry.EndpointIP = sample.EndpointIP |
| 114 | } |
| 115 | |
| 116 | // GetStats returns stats for specific public keys (direct map lookup) |
| 117 | func (st *Tracker) GetStats(_ context.Context, keys []string, reset bool) *common.StatResponse { |