Files
syncthing/lib/protocol/counting.go
T

69 lines
1.5 KiB
Go
Raw Normal View History

// Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
2014-09-22 21:42:11 +02:00
package protocol
import (
"io"
"sync/atomic"
"time"
)
type countingReader struct {
io.Reader
2025-10-21 22:00:44 +02:00
idString string
tot atomic.Int64 // bytes
last atomic.Int64 // unix nanos
2014-09-22 21:42:11 +02:00
}
var (
2023-02-07 12:07:34 +01:00
totalIncoming atomic.Int64
totalOutgoing atomic.Int64
2014-09-22 21:42:11 +02:00
)
func (c *countingReader) Read(bs []byte) (int, error) {
n, err := c.Reader.Read(bs)
2023-02-07 12:07:34 +01:00
c.tot.Add(int64(n))
totalIncoming.Add(int64(n))
c.last.Store(time.Now().UnixNano())
metricDeviceRecvBytes.WithLabelValues(c.idString).Add(float64(n))
2014-09-22 21:42:11 +02:00
return n, err
}
2023-02-07 12:07:34 +01:00
func (c *countingReader) Tot() int64 { return c.tot.Load() }
2014-09-22 21:42:11 +02:00
func (c *countingReader) Last() time.Time {
2023-02-07 12:07:34 +01:00
return time.Unix(0, c.last.Load())
2014-09-22 21:42:11 +02:00
}
type countingWriter struct {
io.Writer
2025-10-21 22:00:44 +02:00
idString string
tot atomic.Int64 // bytes
last atomic.Int64 // unix nanos
2014-09-22 21:42:11 +02:00
}
func (c *countingWriter) Write(bs []byte) (int, error) {
n, err := c.Writer.Write(bs)
2023-02-07 12:07:34 +01:00
c.tot.Add(int64(n))
totalOutgoing.Add(int64(n))
c.last.Store(time.Now().UnixNano())
metricDeviceSentBytes.WithLabelValues(c.idString).Add(float64(n))
2014-09-22 21:42:11 +02:00
return n, err
}
2023-02-07 12:07:34 +01:00
func (c *countingWriter) Tot() int64 { return c.tot.Load() }
2014-09-22 21:42:11 +02:00
func (c *countingWriter) Last() time.Time {
2023-02-07 12:07:34 +01:00
return time.Unix(0, c.last.Load())
2014-09-22 21:42:11 +02:00
}
2015-01-18 01:26:52 +01:00
func TotalInOut() (int64, int64) {
2023-02-07 12:07:34 +01:00
return totalIncoming.Load(), totalOutgoing.Load()
2014-09-22 21:42:11 +02:00
}