package routers // Counter deltas belong on Node, using the router boot and uptime clock. // Samples remain bounded in RAM; restart, missing source, netdev or session // changes reset the baseline instead of fabricating a spike or a zero. type wanTraffic struct { RX *float64 `json:"rx_bytes"` TX *float64 `json:"tx_bytes"` RXPackets *float64 `json:"rx_packets"` TXPackets *float64 `json:"tx_packets"` RXErrors *float64 `json:"rx_errors"` TXErrors *float64 `json:"tx_errors"` RXDropped *float64 `json:"rx_dropped"` TXDropped *float64 `json:"tx_dropped"` } func readTraffic(raw any) *wanTraffic { t := object(raw) if t == nil { return nil } n := func(k string) *float64 { return number(t[k], 0, 9007199254740991) } return &wanTraffic{n("rx_bytes"), n("tx_bytes"), n("rx_packets"), n("tx_packets"), n("rx_errors"), n("tx_errors"), n("rx_dropped"), n("tx_dropped")} } type trafficSample struct { boot string wan []clientWAN } func counterRate(current, old *float64, elapsed float64) *float64 { if current == nil || old == nil || *current < *old || elapsed <= 0 || elapsed > 60 { return nil } return number((*current-*old)*8/elapsed/1000, 0, 1e9) } func (c *Collector) rates(d *Device) { if d.ClientAPI == nil { return } previous, ok := c.traffic[d.ID] c.traffic[d.ID] = trafficSample{d.ClientAPI.BootID, d.ClientAPI.WAN} if !ok || previous.boot != d.ClientAPI.BootID { return } count := 0 down, up := float64(0), float64(0) allDown, allUp := true, true for i := range d.Modems { m := &d.Modems[i] var current, old *clientWAN for j := range d.ClientAPI.WAN { if d.ClientAPI.WAN[j].Slot == m.Slot { current = &d.ClientAPI.WAN[j] } } for j := range previous.wan { if previous.wan[j].Slot == m.Slot { old = &previous.wan[j] } } if current == nil || current.Up == nil || !*current.Up { continue } count++ valid := old != nil && old.Up != nil && *old.Up && current.Interface != "" && current.Interface == old.Interface && current.Traffic != nil && old.Traffic != nil && current.ObservedUptime != nil && old.ObservedUptime != nil if valid && current.SessionUptime != nil && old.SessionUptime != nil && *current.SessionUptime < *old.SessionUptime { valid = false } if valid { elapsed := *current.ObservedUptime - *old.ObservedUptime m.DownKbps = counterRate(current.Traffic.RX, old.Traffic.RX, elapsed) m.UpKbps = counterRate(current.Traffic.TX, old.Traffic.TX, elapsed) } if m.DownKbps == nil { allDown = false } else { down += *m.DownKbps } if m.UpKbps == nil { allUp = false } else { up += *m.UpKbps } } if count > 0 && allDown { d.DownKbps = number(down, 0, 1e9) } if count > 0 && allUp { d.UpKbps = number(up, 0, 1e9) } }