Documentation
¶
Overview ¶
Package byterate limits, counts and meters the bytes of Go connections and streams.
NewConn wraps a net.Conn so that its bytes count in its Meter and, with WithLimiter or WithLimiters, are limited. Without a limit the reads and writes pass straight through, counted by an uncontended atomic add, and SetLimiters adds, changes or lifts a limit at any time, also for a transfer in progress:
rate := byterate.NewRate(1 << 20) // 1 MiB/s limited := byterate.NewConn(conn, byterate.WithLimiter(rate))
A Rate is a limit in bytes per second; its zero value is ready to use. NewHierarchy nests limiters, such as a connection's Rate within its user's Rate and a global one, and waits for the strictest. A Budget counts the bytes used in a period and, step by step as they grow, slows them down or stops them; the wrappers lease its bytes ahead, so that a quota costs no more than counting. A Switch passes charges on to a limiter that can be replaced while many connections use it. A Counter adds up bytes, from its own Adds or from the Meters attached to it, and measures their throughput from samples, never on the path of a read or write.
A Group is a level of a tree, such as a server, a user and a tunnel: the connections opened in it are limited and counted at every level, with their number capped where needed, and follow later changes of the levels.
NewPacketConn does the same for the datagrams of a net.PacketConn, NewStream, NewReader and NewWriter for plain streams. A Limiter's TryWait charges bytes only if they may pass at once, for senders that drop datagrams rather than wait, and its Ready and Charge methods serve relays that call a hook before each read and after each write.
Index ¶
- Variables
- type Budget
- func (b *Budget) Acquire(ctx context.Context, minBytes, maxBytes int64) (int64, error)
- func (b *Budget) AfterExpiry(f func()) (stop func() bool)
- func (b *Budget) Charge(n int64) error
- func (b *Budget) Expiry() time.Time
- func (b *Budget) Lease(n int64) (Lease, error)
- func (b *Budget) OnStep(f func(step int, used int64))
- func (b *Budget) Ready(ctx context.Context, n int64) (int64, error)
- func (b *Budget) Refund(n int64)
- func (b *Budget) Remaining() int64
- func (b *Budget) Reset()
- func (b *Budget) Return(l Lease, n int64)
- func (b *Budget) SetClock(c Clock)
- func (b *Budget) SetExpiry(t time.Time)
- func (b *Budget) SetSteps(steps ...Step)
- func (b *Budget) SetUsed(n int64)
- func (b *Budget) Settle(l Lease, used int64)
- func (b *Budget) Step() int
- func (b *Budget) Steps() []Step
- func (b *Budget) TryAcquire(minBytes, maxBytes int64) (int64, error)
- func (b *Budget) TryWait(n int64) error
- func (b *Budget) Used() int64
- func (b *Budget) Wait(ctx context.Context, n int64) error
- type Clock
- type Conn
- func (s *Conn) Abort(cause error)
- func (s *Conn) Close() error
- func (s *Conn) CloseRead() error
- func (s *Conn) CloseWrite() error
- func (c *Conn) LocalAddr() net.Addr
- func (s *Conn) Meter() *Meter
- func (c *Conn) Notifying() net.Conn
- func (c *Conn) RawConn() net.Conn
- func (s *Conn) Read(b []byte) (int, error)
- func (s *Conn) ReadFrom(r io.Reader) (int64, error)
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) SetDeadline(t time.Time) error
- func (c *Conn) SetLimiters(read, write Limiter)
- func (c *Conn) SetReadDeadline(t time.Time) error
- func (c *Conn) SetWriteDeadline(t time.Time) error
- func (s *Conn) Write(b []byte) (int, error)
- func (s *Conn) WriteTo(w io.Writer) (int64, error)
- type Counter
- func (c *Counter) Add(read, written int64)
- func (c *Counter) Attach(m *Meter) error
- func (c *Counter) Detach(m *Meter)
- func (c *Counter) Load() (read, written int64)
- func (c *Counter) Restore(read, written int64)
- func (c *Counter) Sample()
- func (c *Counter) SampleEverySecond()
- func (c *Counter) Set(read, written int64)
- func (c *Counter) SetClock(clk Clock)
- func (c *Counter) Swap() (read, written int64)
- func (c *Counter) Throughput() (readBps, writtenBps int64)
- func (c *Counter) Total() (read, written int64)
- type Group
- func (g *Group) Acquire() error
- func (g *Group) AcquireContext(ctx context.Context) error
- func (g *Group) Conns() int64
- func (g *Group) Limiters() (read, write Limiter)
- func (g *Group) MaxConns() int64
- func (g *Group) Open(c net.Conn, opts ...Option) (*Conn, error)
- func (g *Group) OpenPacketConn(c net.PacketConn, opts ...Option) (*PacketConn, error)
- func (g *Group) OpenStream(rwc io.ReadWriteCloser, opts ...Option) (*Stream, error)
- func (g *Group) Parent() *Group
- func (g *Group) Reads() Reserver
- func (g *Group) Release()
- func (g *Group) SetLimiters(read, write Limiter)
- func (g *Group) SetMaxConns(n int64)
- func (g *Group) SetParent(p *Group) error
- func (g *Group) SetTraffic(c *Counter) error
- func (g *Group) Traffic() *Counter
- func (g *Group) Writes() Reserver
- type Lease
- type Limiter
- type Meter
- type NotifyConn
- func (s NotifyConn) Abort(cause error)
- func (s NotifyConn) Close() error
- func (s NotifyConn) CloseRead() error
- func (s NotifyConn) CloseWrite() error
- func (s NotifyConn) Meter() *Meter
- func (c *NotifyConn) NotifyReadable(f func()) (stop func() bool)
- func (s NotifyConn) Read(b []byte) (int, error)
- func (s NotifyConn) ReadFrom(r io.Reader) (int64, error)
- func (c *NotifyConn) TryRead(b []byte) (int, error)
- func (s NotifyConn) Write(b []byte) (int, error)
- func (s NotifyConn) WriteTo(w io.Writer) (int64, error)
- type NotifyStream
- func (s NotifyStream) Abort(cause error)
- func (s NotifyStream) Close() error
- func (s NotifyStream) CloseRead() error
- func (s NotifyStream) CloseWrite() error
- func (s NotifyStream) Meter() *Meter
- func (s *NotifyStream) NotifyReadable(f func()) (stop func() bool)
- func (s NotifyStream) Read(b []byte) (int, error)
- func (s NotifyStream) ReadFrom(r io.Reader) (int64, error)
- func (s NotifyStream) SetLimiters(read, write Limiter)
- func (s *NotifyStream) TryRead(b []byte) (int, error)
- func (s NotifyStream) Write(b []byte) (int, error)
- func (s NotifyStream) WriteTo(w io.Writer) (int64, error)
- type Option
- type PacketConn
- func (c *PacketConn) Abort(cause error)
- func (c *PacketConn) Close() error
- func (c *PacketConn) LocalAddr() net.Addr
- func (c *PacketConn) Meter() *Meter
- func (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error)
- func (c *PacketConn) SetDeadline(t time.Time) error
- func (c *PacketConn) SetLimiters(read, write Limiter)
- func (c *PacketConn) SetReadDeadline(t time.Time) error
- func (c *PacketConn) SetWriteDeadline(t time.Time) error
- func (c *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error)
- type Rate
- func (r *Rate) Acquire(ctx context.Context, minBytes, maxBytes int64) (int64, error)
- func (r *Rate) Burst() time.Duration
- func (r *Rate) Charge(n int64) error
- func (r *Rate) Clone() *Rate
- func (r *Rate) Disable()
- func (r *Rate) Enable()
- func (r *Rate) Fair() bool
- func (r *Rate) Limit() int64
- func (r *Rate) Ready(ctx context.Context, n int64) (int64, error)
- func (r *Rate) Refund(n int64)
- func (r *Rate) Reset(limitBps int64)
- func (r *Rate) SetBurst(d time.Duration)
- func (r *Rate) SetFair(on bool)
- func (r *Rate) SetLimit(limitBps int64)
- func (r *Rate) TryAcquire(minBytes, maxBytes int64) (int64, error)
- func (r *Rate) TryWait(n int64) error
- func (r *Rate) Wait(ctx context.Context, n int64) error
- type Reserver
- type Step
- type Stream
- func (s *Stream) Abort(cause error)
- func (s *Stream) Close() error
- func (s *Stream) CloseRead() error
- func (s *Stream) CloseWrite() error
- func (s *Stream) Meter() *Meter
- func (s *Stream) Notifying() io.ReadWriteCloser
- func (s *Stream) Read(b []byte) (int, error)
- func (s *Stream) ReadFrom(r io.Reader) (int64, error)
- func (s *Stream) SetLimiters(read, write Limiter)
- func (s *Stream) Write(b []byte) (int, error)
- func (s *Stream) WriteTo(w io.Writer) (int64, error)
- type Switch
- func (s *Switch) Acquire(ctx context.Context, minBytes, maxBytes int64) (int64, error)
- func (s *Switch) Charge(n int64) error
- func (s *Switch) Limiter() Limiter
- func (s *Switch) Ready(ctx context.Context, n int64) (int64, error)
- func (s *Switch) Refund(n int64)
- func (s *Switch) Set(l Limiter)
- func (s *Switch) TryAcquire(minBytes, maxBytes int64) (int64, error)
- func (s *Switch) TryWait(n int64) error
- func (s *Switch) Wait(ctx context.Context, n int64) error
- type TooManyConnsError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrTooManyConns is matched by the *TooManyConnsError of Acquire and // Open, for a Group, or one of its ancestors, that has as many // connections as its MaxConns. ErrTooManyConns = errors.New("byterate: too many connections") // ErrGroupCycle is returned by SetParent for a parent that is the Group // itself or one of its descendants. ErrGroupCycle = errors.New("byterate: group would be its own ancestor") // ErrCounterOverlap is returned where a Counter would count the same // bytes twice: given as the Traffic of a Group and of one of its // ancestors or descendants, or to a connection by WithCounter or Attach // while it is the Traffic of the connection's Group or of an ancestor. // Groups that share a Counter must not be above one another; siblings // may share one. ErrCounterOverlap = errors.New("byterate: counter would count the same bytes twice") )
var ErrBudgetExhausted = errors.New("byterate: budget exhausted")
ErrBudgetExhausted is returned for bytes that a Budget stops: once its usage reaches a step with Stop, or once its expiry has passed.
var ErrNilConn = errors.New("byterate: nil connection")
ErrNilConn is returned when a wrapper has no underlying connection.
var ErrWouldBlock error = wouldBlockError{}
ErrWouldBlock is returned by the TryRead of a wrapper while its read limit has debt to wait out: the read would block on the limit, as it would on a source without data. Its WouldBlock method reports true, the way a source of such reads tells that a read found nothing yet.
var ErrWouldWait = errors.New("byterate: limit would wait")
ErrWouldWait is returned by TryWait for bytes that the limit would make the caller wait for.
Functions ¶
This section is empty.
Types ¶
type Budget ¶
type Budget struct {
// contains filtered or unexported fields
}
Budget is a Limiter that counts the bytes used in a period and applies a Step once they reach its After: from there on, its Limit sets their pace, Pause holds them, or Stop refuses them. Steps can slow traffic down in stages and stop it, such as to 1 MiB/s past 10 GiB, to 64 KiB/s past 20 GiB and not at all past 30 GiB. Before the first step a Budget limits nothing, and without steps it only counts.
Reset starts a new period, and SetSteps and SetUsed change the steps and the bytes used, at any time and without ending the connections charged to the Budget: the next charge sees the change. When periods begin, such as each hour, day or month, is up to the caller. SetExpiry makes the Budget stop all bytes after a time, until it is set again.
The bytes used count everything charged to the Budget, refunds taken off, whichever step applied; a step's Limit sees only the bytes of its step. Ready and the connection wrappers end a grant at the next step, so a step applies from its After, and a Write never takes the usage past a Stop. A Read charges what it read, so concurrent Reads can each pass a Stop by their last grant, as can a Read in progress when a change takes back the lease it read on, as Lease describes; Charge, which records bytes already transferred, counts them in the step that applied before them.
All methods are safe for concurrent use and on a nil *Budget, which never limits. The zero value only counts until SetSteps.
Example ¶
Stop a connection once it has used its allowance: Write sends what fits and fails.
package main
import (
"fmt"
"io"
"net"
"github.com/djylb/byterate"
)
func main() {
client, server := net.Pipe()
defer func() { _ = server.Close() }()
go func() { _, _ = io.Copy(io.Discard, server) }()
budget := byterate.NewBudget(byterate.Step{After: 1000, Stop: true})
conn := byterate.NewConn(client, byterate.WithLimiter(byterate.NewHierarchy(byterate.NewRate(1<<20), budget)))
defer func() { _ = conn.Close() }()
n, err := conn.Write(make([]byte, 4000))
fmt.Println(n, err, budget.Used())
}
Output: 1000 byterate: budget exhausted 1000
func NewBudget ¶
NewBudget returns a Budget with steps, at the start of a period.
Example ¶
Slow traffic down in stages as it is used, and stop it at the end. Each period, such as a day, starts over with Reset; changing the steps or their limits keeps connections open.
package main
import (
"fmt"
"github.com/djylb/byterate"
)
func main() {
slow, slower := byterate.NewRate(1<<20), byterate.NewRate(64<<10)
daily := byterate.NewBudget(
byterate.Step{After: 10 << 30, Limit: slow}, // past 10 GiB: 1 MiB/s
byterate.Step{After: 20 << 30, Limit: slower}, // past 20 GiB: 64 KiB/s
byterate.Step{After: 30 << 30, Stop: true}, // past 30 GiB: stop
)
daily.OnStep(func(step int, used int64) { fmt.Println("step", step, "at", used) })
_ = daily.Charge(15 << 30)
fmt.Println(daily.Step(), daily.Used())
daily.Reset() // the next day starts over
slow.SetLimit(2 << 20) // a new speed for the first step
fmt.Println(daily.Step(), daily.Used())
}
Output: step 0 at 16106127360 0 16106127360 -1 0
func (*Budget) Acquire ¶
Acquire takes between minBytes and maxBytes bytes from b and from the Limit of the step that applies, up to the next step, and waits for that Limit. It refuses with ErrBudgetExhausted, taking nothing, when min bytes would take the usage past a step with Stop, or after the expiry.
func (*Budget) AfterExpiry ¶
AfterExpiry arranges for f to run in its own goroutine once b's expiry passes, such as to close connections that sit idle and so never meet the refusal of their next read or write. An expiry that SetExpiry moves or clears before it passes keeps f waiting for the next one; when b has already expired, f runs at once. f runs at most once. The timer of the expiry runs it; with a Clock set, which no timer follows, the first charge, Remaining or Lease that finds the expiry passed does. stop unregisters f and reports whether it did so before f was started. A nil b never expires, so f never runs.
func (*Budget) Charge ¶
Charge records n transferred bytes on b and on the Limit of the step that applied before them, without waiting. It returns ErrBudgetExhausted when the usage has reached a step with Stop, or after the expiry, and otherwise the Limit's error; the bytes stay charged either way.
func (*Budget) Lease ¶
Lease takes up to n bytes of b's usage at once and returns them as a Lease: n, or fewer when b reaches the next step or a step with Stop first. It refuses with ErrBudgetExhausted once b is stopped or expired, and with ErrWouldWait while the step that applies has a Limit, whose bytes must be charged to b as a Limiter instead. A nil b leases all n; an n <= 0 leases nothing.
Leased bytes count as used from the moment they are leased, so that the holders of leases together never take the usage past a Stop. Before it refuses, b takes back what the wrappers' leases hold unused, so that the bytes they hold never keep anyone else from the Budget. OnStep reports a step that a Lease taken here reaches as it is taken, since its bytes count as used; the wrappers' leases report a step once the bytes that passed on them reach it, so that one taken back unused reports none. Leases never span a step, so a step's Limit applies from its After.
The wrappers of this package lease from the Budgets among their levels by themselves, and Used and Remaining leave out what their leases hold unused. Reset, SetUsed, SetSteps, SetExpiry and the expiry itself take those leases back at once; a Lease taken here stays with its holder.
Example ¶
Lease bytes of a Budget for a transfer of one's own, and give back what it did not use.
package main
import (
"fmt"
"github.com/djylb/byterate"
)
func main() {
quota := byterate.NewBudget(byterate.Step{After: 10_000, Stop: true})
lease, err := quota.Lease(4096)
if err != nil {
return // byterate.ErrBudgetExhausted
}
sent := int64(1000) // pass up to lease.Bytes bytes here
quota.Settle(lease, sent)
fmt.Println(lease.Bytes, quota.Used(), quota.Remaining())
}
Output: 4096 1000 9000
func (*Budget) OnStep ¶
OnStep makes b call f with the index of the step that the usage reached and the bytes used then, each time it reaches a later step than any before in the period; of several steps passed at once, it reports the last. Each step is reported at most once a period, however refunds and leases taken back move the usage below it again. The wrappers report a step once the bytes that passed reach it, not the bytes they leased ahead. f runs on the goroutine of the charge or I/O that found the step reached, so it must return quickly. A step that a TryWait reached before another level of a hierarchy refused the bytes counts as reached. A nil f stops the reports.
func (*Budget) Ready ¶
Ready returns how many of n bytes may pass at once: up to the next step, and as the Limit of the step that applies allows. It refuses with ErrBudgetExhausted once the usage reaches a step with Stop, or after the expiry, and charges nothing.
func (*Budget) Refund ¶
Refund takes back the last n bytes charged, which were not transferred, and gives them back to the Limits of the steps they were charged in, as far as those took them, from the latest step down. The connection wrappers and a hierarchy's Wait refund the exact charges they made instead, in the step and period they made them.
func (*Budget) Remaining ¶
Remaining returns how many more bytes b lets through before it stops them: the bytes up to the first step with Stop, 0 once the usage has reached it or the expiry has passed, and math.MaxInt64 without such a step. It charges nothing, so a concurrent charge can take the bytes first.
func (*Budget) Reset ¶
func (b *Budget) Reset()
Reset starts a new period: the bytes used go back to zero, and with them the step that applies. Refunds of bytes charged before it are dropped.
func (*Budget) Return ¶
Return gives back n unused bytes of l to b's usage, at most l.Bytes, unless a Reset or SetUsed since ended the period l was taken in.
func (*Budget) SetClock ¶
SetClock makes b read the time of its expiry from c; nil goes back to the monotonic clock. Set it before SetExpiry.
func (*Budget) SetExpiry ¶
SetExpiry makes b stop all bytes after t, as a step with Stop does; a zero t means never. The expiry is kept on the monotonic clock, as a deadline is, so a later change of the wall clock does not move it. A timer takes the wrappers' leases back when it passes; with a Clock set, which no timer follows, the wrappers charge b at every read and write instead while it has an expiry.
func (*Budget) SetSteps ¶
SetSteps replaces the steps of b, given in any order, from the next charge; Steps returns them sorted. Of steps with the same After, the last one given applies, except that a step with Stop always does: from its After on, b refuses everything. The waits on a step with Pause wake to look at the new steps. It panics if a step's Limit passes charges on to b, which would charge b without end.
func (*Budget) SetUsed ¶
SetUsed makes n the bytes used in a new period, such as the bytes persisted before a restart, or a total that several Budgets share. Refunds of bytes charged before it are dropped, and OnStep does not report the step it brings b into. The wrappers' leases of the old period end with it: what passes from then on counts in the new one.
func (*Budget) Settle ¶
Settle ends l after used of its bytes were transferred, giving back the rest as Return does. A used beyond l.Bytes, such as the overshoot of concurrent transfers that shared the lease, is added to the usage of l's period.
func (*Budget) Step ¶
Step returns the index of the step that applies to Used, in the order of After, or -1 before the first step.
func (*Budget) TryAcquire ¶
TryAcquire takes between minBytes and maxBytes bytes from b and the Limit of the step that applies, as many as they let through at once, or refuses them as Acquire does, or returns ErrWouldWait.
func (*Budget) TryWait ¶
TryWait charges n bytes to b and to the Limit of the step that applies if that Limit lets them through without waiting, and otherwise charges nothing and returns ErrWouldWait. It refuses them with ErrBudgetExhausted, as Wait does.
type Clock ¶
Clock is the time source of the parts of this package that read time off the charge path: the throughput of a Counter and the expiry of a Budget. Any type with a Now method fits, such as a fake clock that tests step by hand.
A Rate keeps the monotonic clock, which a testing/synctest bubble fakes.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is the wrapper of a net.Conn made by NewConn and Group.Open. It reports the wrapped connection's addresses, sets its deadlines and returns it from RawConn, which wrapper-aware helpers use to unwrap it.
func NewConn ¶
NewConn wraps c so that its bytes are counted in the Meter, and, with WithLimiter or WithLimiters, limited. Without a limit, and while none applies, reads and writes pass straight through and only count, at the cost of an atomic add; SetLimiters adds or changes a limit at any time, also for a transfer in progress.
Limited data passes in grants of what the limit lets through at once: its credit, up to the limit's burst after an idle period, or without credit a quantum of about 20 ms of traffic, no more than the credit at its cap. A Write sends its bytes a grant at a time, each charged before it goes out, so a large Write neither bursts past the credit nor holds a shared limit while other connections wait; concurrent limited Writes do not interleave. A Read first waits until the limit has no debt, then reads at most a grant and charges what arrived, so a reader in debt leaves the data with the sender and one blocked waiting for data holds no share of the limit. Readers waiting for the debt of one shared limit read together when it is repaid, up to a grant each.
A Budget among the levels leases bytes to the connection instead of being charged at each read and write, as Budget.Lease describes, and while a step's Limit applies it is charged at every read and write as a Limiter. A Write counts its bytes before it sends them, so writes, also concurrent ones, never pass a Budget's Stop; the bytes it does not send, also when a change of the Budget takes its lease back meanwhile, are not charged. A Read reads no more than the leases cover and counts what arrived, so concurrent Reads, and a Read in progress when its lease is taken back, can pass the leases by what each reads, which counts as used.
Close settles the wrapper: it gives back what its leases hold unused and takes it out of its Counters and Group. A wrapper dropped without Close is settled once the garbage collector finds it, which can be much later, so close every wrapper for timely accounting.
The result keeps the zero-copy paths of c: io.Copy to it, through its ReadFrom, and from it, through its WriteTo, hands c, and the connection or file at the other end, a chunk at a time as an io.LimitedReader, so that sendfile and splice still move the data between files and sockets where the system has them, counted and within the limit. Copies that cannot take such a path go through Read and Write.
Close ends a wait with net.ErrClosed, and CloseRead and CloseWrite do the same for their side; they are passed on to c when it has them, so relays can half-close through the wrapper, and return an error matching errors.ErrUnsupported when it has not. Deadlines set through the result bound the waits too; one set on c before wrapping it does not. A wait that a deadline ends returns os.ErrDeadlineExceeded, a net.Error whose Timeout method reports true. A Write that is ended or fails part way returns the bytes it sent and refunds the rest, and one that c reports short without an error returns io.ErrShortWrite. A Read ended in its wait returns no bytes. Moving a deadline later does not end a wait. Any other error from a Limiter is returned as it is.
UDP, IP and Unix datagram sockets, and connections given WithDatagram, are never split: each Write is charged and sent whole, and a Read may take a whole datagram. With a Limiter other than a *Rate, the grant is what its Ready allows; one that refuses bytes ends the Read or Write with its error, a Read keeping the bytes it already read.
Example ¶
Limit a connection to 1 MiB/s in both directions; the result is still a net.Conn.
package main
import (
"fmt"
"io"
"net"
"github.com/djylb/byterate"
)
func main() {
client, server := net.Pipe()
defer func() { _ = server.Close() }()
conn := byterate.NewConn(client, byterate.WithLimiter(byterate.NewRate(1<<20)))
defer func() { _ = conn.Close() }()
go func() { _, _ = conn.Write([]byte("hello")) }()
buf := make([]byte, 5)
_, _ = io.ReadFull(server, buf)
fmt.Println(string(buf), conn.RemoteAddr())
}
Output: hello pipe
func (*Conn) Abort ¶
func (s *Conn) Abort(cause error)
Abort ends the connection abnormally, so that its peer sees a cut instead of an end of data, and then closes the wrapper as Close does: a wrapped connection with a method Abort(cause error), such as a stream of a multiplexed connection, is aborted with cause; otherwise a wrapped connection with a method SetLinger(sec int) error, a *net.TCPConn, also beneath wrappers that return what they wrap from a NetConn method, gets SO_LINGER 0, so that its close sends RST instead of FIN. A connection with neither is just closed. Relays that end a transfer on an error, such as netx.Relay, call it through the same method set.
func (*Conn) Close ¶
func (s *Conn) Close() error
Close ends the waits in progress with net.ErrClosed, gives back the unused bytes of the leases, takes the wrapper's bytes out of its Counters as counted, gives back its Group's slot and closes what it wraps. Only the first Close does all but the last.
func (*Conn) CloseRead ¶
func (s *Conn) CloseRead() error
CloseRead shuts down the reading side of the wrapped connection, as *net.TCPConn does, or returns an error matching errors.ErrUnsupported when it cannot. On success it also ends a read's limiter wait with net.ErrClosed.
func (*Conn) CloseWrite ¶
func (s *Conn) CloseWrite() error
CloseWrite shuts down the writing side of the wrapped connection, as *net.TCPConn and *tls.Conn do, or returns an error matching errors.ErrUnsupported when it cannot. On success it also ends a write's limiter wait with net.ErrClosed and refunds the unsent bytes.
func (*Conn) LocalAddr ¶
LocalAddr returns the local address of the wrapped connection, or nil without one.
func (*Conn) Notifying ¶
Notifying returns c as a *NotifyConn when the wrapped connection has methods TryRead(p []byte) (int, error) and NotifyReadable(f func()) (stop func() bool), such as a stream of a multiplexed connection, so that a relay can copy from it without a goroutine waiting while it is idle; otherwise it returns c itself, without those methods.
func (*Conn) ReadFrom ¶
ReadFrom copies r to the wrapped writer until EOF, as io.Copy does. When the writer has a ReadFrom of its own and r is a file or, where the system splices them, a socket, the copy goes to that ReadFrom in chunks, each an io.LimitedReader of r within the limit and leases, so that it keeps a zero-copy path; otherwise it goes through Write.
func (*Conn) RemoteAddr ¶
RemoteAddr returns the remote address of the wrapped connection, or nil without one.
func (*Conn) SetDeadline ¶
SetDeadline sets the read and write deadlines of the wrapped connection and, unless it rejects them, of the waits in the limiters.
func (*Conn) SetLimiters ¶
SetLimiters replaces the Limiters of the connection's reads and writes, as WithLimiters set them, from the next read or write; a wait in progress ends and starts over on the new ones, and nil leaves a direction unlimited. A Group's levels still apply on top.
Example ¶
Count a connection without limiting it, and limit it later: it passes straight through until a limit applies.
package main
import (
"fmt"
"io"
"net"
"github.com/djylb/byterate"
)
func main() {
client, server := net.Pipe()
defer func() { _ = server.Close() }()
go func() { _, _ = io.Copy(io.Discard, server) }()
conn := byterate.NewConn(client)
defer func() { _ = conn.Close() }()
_, _ = conn.Write(make([]byte, 1000))
conn.SetLimiters(nil, byterate.NewRate(1<<20)) // from now on, writes at 1 MiB/s
_, _ = conn.Write(make([]byte, 500))
fmt.Println(conn.Meter().Total())
}
Output: 0 1500
func (*Conn) SetReadDeadline ¶
SetReadDeadline sets the read deadline of the wrapped connection and, unless it rejects it, of the waits in the read limiter.
func (*Conn) SetWriteDeadline ¶
SetWriteDeadline sets the write deadline of the wrapped connection and, unless it rejects it, of the waits in the write limiter.
func (*Conn) WriteTo ¶
WriteTo copies the wrapped reader to w until EOF, as io.Copy does. When w has a ReadFrom of its own and is a socket, a file or a writer of this package, and the reader is a socket that the system splices, the copy goes to that ReadFrom in chunks, each an io.LimitedReader of the reader within the limit and leases, so that it keeps a zero-copy path; otherwise it goes through Read.
type Counter ¶
type Counter struct {
// contains filtered or unexported fields
}
Counter adds up the bytes read and written by a transfer, for accounting and for measuring throughput, without limiting it. Swap takes the totals since the last Swap, so that each byte is reported exactly once however Adds and Swaps interleave, and Throughput reports the bytes per second of the last whole second.
The zero value is ready to use. Add costs an atomic add per direction and does not read the clock; a Counter that many goroutines add to at once spreads their Adds over counters of their own as it finds them contending, and one that few add to stays one pair of counters. Attach adds up the Meters of connections instead, which costs their reads and writes nothing at all.
All methods are safe for concurrent use and on a nil *Counter. A Counter must not be copied after first use.
Example ¶
Count the bytes of a transfer and take the totals for a report.
package main
import (
"fmt"
"github.com/djylb/byterate"
)
func main() {
var c byterate.Counter
c.Add(1500, 0)
c.Add(0, 300)
in, out := c.Swap() // the totals so far, and start over
fmt.Println(in, out)
in, out = c.Load()
fmt.Println(in, out)
}
Output: 1500 300 0 0
func (*Counter) Add ¶
Add adds read bytes read and written bytes written; negative counts subtract. It does not read the clock: Throughput samples the totals.
func (*Counter) Attach ¶
Attach adds m's bytes from now on to c's totals, without counting them on every read and write: c adds up its Meters when it is read, so that a Counter shared by many connections costs their reads and writes nothing. The bytes m counted before stay out of c. Detach ends it, keeping the bytes in c. A Meter attached more than once counts once, until as many Detaches. It returns ErrCounterOverlap, and attaches nothing, when c is the Traffic of the Group m's wrapper was opened in or of an ancestor, which counts m already.
func (*Counter) Detach ¶
Detach ends an Attach of m, and with the last one stops adding m's bytes to c, keeping those it added so far as if they had been counted by Add.
func (*Counter) Restore ¶
Restore adds read and written to c's totals as bytes counted before, such as the persisted totals of a counter that resumes after a restart: Total includes them, but neither Swap nor Throughput reports them as new traffic.
func (*Counter) Sample ¶
func (c *Counter) Sample()
Sample samples c's totals for Throughput if a second has passed since the last sample. A caller that wants the throughput of every second, however rarely it reads it, calls Sample once a second, such as from a ticker shared by all its Counters; it costs a lock and a read of the clock.
Example ¶
Report throughput every second from one ticker of the application's, for all its Counters: counting itself never reads the clock.
package main
import (
"fmt"
"time"
"github.com/djylb/byterate"
)
func main() {
users := []*byterate.Counter{new(byterate.Counter)} // such as each user Group's Traffic
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
report := func() {
for _, c := range users {
c.Sample()
in, out := c.Throughput() // bytes per second of the last second
_, _ = in, out
}
}
report() // on every tick: for range ticker.C { report() }
fmt.Println(len(users))
}
Output: 1
func (*Counter) SampleEverySecond ¶
func (c *Counter) SampleEverySecond()
SampleEverySecond samples c's totals now and then once a second, from a ticker that all the Counters given to it share, so that Throughput reports each second however rarely it is read. The ticker holds c weakly: it drops c once c is no longer referenced elsewhere, and stops while it has no Counter. A Counter given more than once is sampled once.
func (*Counter) Set ¶
Set makes read and written c's totals, as Restore does for a difference: Total returns them, but neither Swap nor Throughput reports the change as traffic. Each byte that an Add adds while Set runs counts as added before Set, and is replaced, or after it, and is added to the new totals.
func (*Counter) SetClock ¶
SetClock makes c read the time of its throughput samples from clk, such as a fake clock in a test; nil goes back to the monotonic clock. Set it before the first sample.
func (*Counter) Swap ¶
Swap returns the bytes read and written since the last Swap and starts counting them over. A count that an Add adds while Swap runs lands in this Swap's result or in the next one's, never in both or neither; the two counts of one Add may land in different Swaps. Swap does not change Throughput.
func (*Counter) Throughput ¶
Throughput returns the bytes per second read and written between the last two samples of c's totals, or 0s until a second sample. Counting never reads the clock: the totals are sampled by Throughput itself or by Sample, at most once in each whole second of c's clock, and the bytes counted between two samples are averaged over the whole seconds between them. So the first call without Sample reports 0, a reader that samples once a second sees about each second on its own, and one that reads every N seconds sees the average of those N seconds. What it reports depends on when the samples were taken, by any caller: call Sample once a second, as from a ticker of the caller's, for readings that do not depend on how often or by how many Throughput is called. Bytes counted before c's first sample count in none. A span in which more was refunded than counted reports 0 and takes the rest off the following ones.
func (*Counter) Total ¶
Total returns the bytes read and written since c began, which Swap does not change: the running totals to persist, or to report as snapshots that the receiver takes differences of. Refunds through c's views take bytes off, so a total can also go down. Restore and Set take persisted totals back.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group is a level of a tree of traffic controls, such as a whole server, one of its users, a user's client and one of its tunnels: the connections opened in a Group are charged to the limiters of the Group and of each of its ancestors, count in each one's Traffic and Conns, and each level can cap its connections. A Group with a nil parent is a root.
Open takes a connection slot and wraps a connection; a connection opened so costs its reads and writes no more than counting while no level limits it, as its Meter adds up into the Traffic of each level only when that is read. Acquire and Release take and give back a slot alone, and Reads and Writes return the Limiters of a Group's reads and writes, for relays that call a hook per read and write, which count in Traffic as they are charged. SetParent moves a Group and its connections under another parent at any time: from then on, their bytes go to the new ancestors, as do their slots, while the bytes counted before stay where they are.
Acquire and Release take no lock: SetParent waits for those in progress in the trees it changes, and they wait for it. Charges take no lock, and a connection registers with its own Group alone, so opening and closing connections in different Groups does not contend. A Group's Traffic adds up those of its connections and of its children's Traffic when it is read, so a read costs in proportion to the Groups and connections below.
All methods are safe for concurrent use. The zero value is a root without limits.
Example ¶
Account for and limit connections in a tree of levels, such as a server, a user, a client and a tunnel: every level counts the bytes and connections below it, caps connections and can set limits of its own.
package main
import (
"fmt"
"io"
"net"
"github.com/djylb/byterate"
)
func main() {
server := byterate.NewGroup(nil)
user := byterate.NewGroup(server)
tunnel := byterate.NewGroup(user)
user.SetLimiters(byterate.NewRate(1<<20), byterate.NewRate(1<<20)) // 1 MiB/s each way
user.SetMaxConns(100)
client, peer := net.Pipe()
defer func() { _ = peer.Close() }()
go func() { _, _ = io.Copy(io.Discard, peer) }()
conn, err := tunnel.Open(client)
if err != nil {
_ = client.Close() // a *byterate.TooManyConnsError, matching ErrTooManyConns
return
}
_, _ = conn.Write(make([]byte, 1000))
fmt.Println(server.Conns(), user.Conns())
_, out := user.Traffic().Load()
fmt.Println(out)
_ = conn.Close()
fmt.Println(server.Conns())
}
Output: 1 1 1000 0
Example (Budget) ¶
Give a user a speed and a monthly allowance shared by both directions: past 100 GiB its traffic slows to 1 MiB/s, and at 120 GiB it stops until Reset starts the next month. Open refuses connections past the user's cap.
package main
import (
"fmt"
"io"
"net"
"github.com/djylb/byterate"
)
func main() {
server := byterate.NewGroup(nil)
user := byterate.NewGroup(server)
monthly := byterate.NewBudget(
byterate.Step{After: 100 << 30, Limit: byterate.NewRate(1 << 20)},
byterate.Step{After: 120 << 30, Stop: true},
)
limit := byterate.NewHierarchy(byterate.NewRate(10<<20), monthly) // 10 MiB/s
user.SetLimiters(limit, limit)
user.SetMaxConns(10)
client, peer := net.Pipe()
defer func() { _ = peer.Close() }()
go func() { _, _ = io.Copy(io.Discard, peer) }()
conn, err := user.Open(client)
if err != nil {
_ = client.Close()
return
}
defer func() { _ = conn.Close() }()
_, _ = conn.Write(make([]byte, 1500))
in, out := user.Traffic().Total()
fmt.Println(monthly.Used(), in, out)
monthly.Reset() // at the start of the next month
fmt.Println(monthly.Used())
}
Output: 1500 0 1500 0
func (*Group) Acquire ¶
Acquire takes a connection slot in g and each of its ancestors, or none and a *TooManyConnsError when any of them has as many as its MaxConns; a racing Acquire that takes a slot and gives it back can cause such a refusal too. Each successful Acquire must be matched by one Release.
func (*Group) AcquireContext ¶
AcquireContext is Acquire that waits for a slot instead of refusing it, until ctx is done, when it returns ctx.Err() and takes no slot. Waiters are woken in the order they came as slots free up, but are not served in that order: an Acquire, or a woken waiter that a level above refuses, can take a freed slot first.
func (*Group) Open ¶
Open takes a connection slot in g, as Acquire does, and wraps c as NewConn does, limited by the Limiters of g and each of its ancestors, on top of any WithLimiter of its own, and counted in their Traffic; closing the result gives the slot back. Later changes to the levels, such as SetLimiters or SetParent, apply to it as well. When a slot cannot be taken it returns nil and the error, a *TooManyConnsError or, WithWait, the context's, leaving c open for the caller to close; it returns ErrNilConn for a nil c.
func (*Group) OpenPacketConn ¶
func (g *Group) OpenPacketConn(c net.PacketConn, opts ...Option) (*PacketConn, error)
OpenPacketConn is Open for a net.PacketConn, wrapped as NewPacketConn does.
func (*Group) OpenStream ¶
OpenStream is Open for an io.ReadWriteCloser, wrapped as NewStream does.
func (*Group) Reads ¶
Reads returns the Limiter of the reads of g's connections: it charges the read Limiters of g and its ancestors and counts the bytes read in their Traffic, along the ancestors of the moment. It is nil for a nil g.
func (*Group) Release ¶
func (g *Group) Release()
Release gives back a connection slot that Acquire took, in g and in each of its ancestors now. It panics, and gives back nothing, when g holds no slot, as a Release without its Acquire finds: the slot of the caller keeps g's count above zero whatever else runs.
func (*Group) SetLimiters ¶
SetLimiters sets the Limiters that g's own level charges the reads and the writes of its connections to, on top of its ancestors' and descendants', nil for none. A Rate, a Budget or a NewHierarchy of them suits; the same Limiter for both directions shares one limit between them, and one set at several levels is charged once. It applies from the next read or write, also of the connections open in g and below, which take it on at their next grant: a wait in progress ends on the Limiters it began with. It panics if a Limiter charges the Reads or Writes of g or of a descendant, which would charge itself without end.
func (*Group) SetMaxConns ¶
SetMaxConns caps the connections of g and its descendants at n, from the next Acquire; 0 or less means no cap. Connections over a lowered cap stay open; callers of AcquireContext waiting on g try again.
func (*Group) SetParent ¶
SetParent moves g under p, or makes it a root for a nil p, with the connection slots taken in g and its descendants: they leave g's old ancestors and count in p and its ancestors, even beyond their MaxConns, which then refuse new connections until enough close. Charges after the move go to the new ancestors; a wait in progress ends on the old ones, and so does the Refund of a wrapped connection, while a direct Refund on Reads or Writes goes to the new ones. Callers of AcquireContext waiting on an old ancestor try again. It returns ErrGroupCycle, and moves nothing, when p is g or a descendant of g, or when a Limiter of p or of one of its ancestors charges the Reads or Writes of g or of a descendant.
func (*Group) SetTraffic ¶
SetTraffic makes c the Counter of g's traffic from now on, such as a Counter restored after a restart, or one that several Groups share to add up their traffic; nil makes a new one. The bytes counted before stay in the Counter it replaces. It returns ErrCounterOverlap, and changes nothing, when c already counts an ancestor or descendant of g, or a connection in g or below, whose bytes it would count twice.
type Lease ¶
type Lease struct {
// Bytes is the number of bytes the lease allows.
Bytes int64
// contains filtered or unexported fields
}
Lease is a part of a Budget's usage taken ahead of the traffic: Budget.Lease adds its Bytes to the usage at once, the holder passes up to that many bytes without asking the Budget again, and Return or Settle gives back what it did not use. A Lease belongs to the period it was taken in: once a Reset or SetUsed ends that period, Return and Settle change nothing.
type Limiter ¶
type Limiter interface {
// Wait charges n bytes and blocks until the limit allows them, or until
// ctx is done, when it returns ctx.Err() and keeps the charge. A limit
// that refuses the bytes, such as an exhausted Budget, returns its error
// and keeps no charge. The connection wrappers pass a context that Close
// and the deadlines end.
Wait(ctx context.Context, n int64) error
// TryWait charges n bytes if the limit lets them through without
// waiting, as Wait would, and returns nil. Otherwise it charges nothing
// and returns ErrWouldWait, or the error of a limit that refuses the
// bytes, such as ErrBudgetExhausted.
TryWait(n int64) error
// Refund gives back n bytes charged by Wait, TryWait or Charge that
// were not transferred.
Refund(n int64)
// Ready blocks until the limit is ready for a transfer, or until ctx is
// done, and returns how many of n bytes it may take, at least 1 for a
// positive n. It charges nothing. A limit that refuses any more
// bytes returns its error.
Ready(ctx context.Context, n int64) (int64, error)
// Charge records n transferred bytes without waiting, as debt that the
// next Ready waits for. The bytes stay charged even when it returns an
// error, which says that the limit refuses further bytes.
Charge(n int64) error
}
Limiter charges and refunds byte budgets. *Rate, *Budget, *Switch, the result of NewHierarchy and the Reads and Writes of a Group implement it, and the connection wrappers take any implementation. Most code combines those and never implements Limiter itself.
A transfer is charged one of three ways. Wait charges the bytes before they are sent and blocks until the limit allows them, as a Write does. TryWait does the same without blocking: it charges the bytes only if the limit lets them through at once, so that a sender of datagrams can drop those it may not send yet. Ready and Charge instead charge the bytes after: Ready blocks until the limit is ready and says how many bytes may pass, without charging, and Charge records the bytes that did, as debt that the next Ready waits for, as a Read does. Ready and Charge have the signatures of the hooks that a relay calls before each read and after each write.
Callers that a limit makes wait are woken when it allows them, not in the order they came: a wait is a sleep until the debt the caller's charge added is repaid, and Disable, a Switch's Set and the end of ctx wake it early. Callers that share a limit get their share in grants, so none waits for long, but none is served first by right either.
A charge that was not transferred, wholly or in part, is given back with Refund. Refund takes no receipt, so it gives back bytes to the limit as it is now: refund only bytes that the same Limiter charged, before any change that voids charges, such as a Rate's Enable or Reset, a Budget's Reset or SetUsed, or a Switch's Set. The connection wrappers, hierarchies, Switches, Budgets and Groups of this package refund their own charges themselves, each to the Limiter and the generation, period or step it charged, and leave out the charges that such a change voided.
type Meter ¶
type Meter struct {
// contains filtered or unexported fields
}
Meter holds the bytes read and written through one wrapper: the wrapper's reads and writes add to it alone, each direction on a cache line of its own, so counting costs an uncontended atomic add. Counter.Attach adds a Meter's bytes to a Counter shared by many wrappers without any cost to their reads and writes.
A wrapper's Meter, with its leases, is kept apart from the wrapper, so that the Counters and Budgets that hold it do not keep the wrapper: one that is dropped without Close is settled once it is collected.
type NotifyConn ¶
type NotifyConn struct {
*Conn
// contains filtered or unexported fields
}
NotifyConn is a Conn over a connection that reads without blocking and tells when it becomes readable, made by Conn.Notifying. Its TryRead and NotifyReadable pass those of the wrapped connection on, charged, counted and limited as Read is.
func (NotifyConn) Abort ¶
func (s NotifyConn) Abort(cause error)
Abort ends the connection abnormally, so that its peer sees a cut instead of an end of data, and then closes the wrapper as Close does: a wrapped connection with a method Abort(cause error), such as a stream of a multiplexed connection, is aborted with cause; otherwise a wrapped connection with a method SetLinger(sec int) error, a *net.TCPConn, also beneath wrappers that return what they wrap from a NetConn method, gets SO_LINGER 0, so that its close sends RST instead of FIN. A connection with neither is just closed. Relays that end a transfer on an error, such as netx.Relay, call it through the same method set.
func (NotifyConn) Close ¶
func (s NotifyConn) Close() error
Close ends the waits in progress with net.ErrClosed, gives back the unused bytes of the leases, takes the wrapper's bytes out of its Counters as counted, gives back its Group's slot and closes what it wraps. Only the first Close does all but the last.
func (NotifyConn) CloseRead ¶
func (s NotifyConn) CloseRead() error
CloseRead shuts down the reading side of the wrapped connection, as *net.TCPConn does, or returns an error matching errors.ErrUnsupported when it cannot. On success it also ends a read's limiter wait with net.ErrClosed.
func (NotifyConn) CloseWrite ¶
func (s NotifyConn) CloseWrite() error
CloseWrite shuts down the writing side of the wrapped connection, as *net.TCPConn and *tls.Conn do, or returns an error matching errors.ErrUnsupported when it cannot. On success it also ends a write's limiter wait with net.ErrClosed and refunds the unsent bytes.
func (NotifyConn) Meter ¶
func (s NotifyConn) Meter() *Meter
Meter returns the Meter of the wrapper's bytes.
func (*NotifyConn) NotifyReadable ¶
func (c *NotifyConn) NotifyReadable(f func()) (stop func() bool)
NotifyReadable calls f once TryRead would not block: once the read limit has no debt and the wrapped connection is readable, or on Close or when the read deadline passes. It returns a function that stops the call, as the wrapped connection's NotifyReadable does.
func (NotifyConn) ReadFrom ¶
ReadFrom copies r to the wrapped writer until EOF, as io.Copy does. When the writer has a ReadFrom of its own and r is a file or, where the system splices them, a socket, the copy goes to that ReadFrom in chunks, each an io.LimitedReader of r within the limit and leases, so that it keeps a zero-copy path; otherwise it goes through Write.
func (*NotifyConn) TryRead ¶
func (c *NotifyConn) TryRead(b []byte) (int, error)
TryRead reads as Read does without blocking: where Read would wait for data, it returns what the wrapped connection's TryRead returns, an error whose WouldBlock method reports true; where it would wait for the read limit, it returns ErrWouldBlock. What it reads is charged and counted as Read charges and counts it.
func (NotifyConn) WriteTo ¶
WriteTo copies the wrapped reader to w until EOF, as io.Copy does. When w has a ReadFrom of its own and is a socket, a file or a writer of this package, and the reader is a socket that the system splices, the copy goes to that ReadFrom in chunks, each an io.LimitedReader of the reader within the limit and leases, so that it keeps a zero-copy path; otherwise it goes through Read.
type NotifyStream ¶
type NotifyStream struct {
*Stream
// contains filtered or unexported fields
}
NotifyStream is a Stream over a stream that reads without blocking and tells when it becomes readable, made by Stream.Notifying; see NotifyConn.
func (NotifyStream) Abort ¶
func (s NotifyStream) Abort(cause error)
Abort ends the connection abnormally, so that its peer sees a cut instead of an end of data, and then closes the wrapper as Close does: a wrapped connection with a method Abort(cause error), such as a stream of a multiplexed connection, is aborted with cause; otherwise a wrapped connection with a method SetLinger(sec int) error, a *net.TCPConn, also beneath wrappers that return what they wrap from a NetConn method, gets SO_LINGER 0, so that its close sends RST instead of FIN. A connection with neither is just closed. Relays that end a transfer on an error, such as netx.Relay, call it through the same method set.
func (NotifyStream) Close ¶
func (s NotifyStream) Close() error
Close ends the waits in progress with net.ErrClosed, gives back the unused bytes of the leases, takes the wrapper's bytes out of its Counters as counted, gives back its Group's slot and closes what it wraps. Only the first Close does all but the last.
func (NotifyStream) CloseRead ¶
func (s NotifyStream) CloseRead() error
CloseRead shuts down the reading side of the wrapped connection, as *net.TCPConn does, or returns an error matching errors.ErrUnsupported when it cannot. On success it also ends a read's limiter wait with net.ErrClosed.
func (NotifyStream) CloseWrite ¶
func (s NotifyStream) CloseWrite() error
CloseWrite shuts down the writing side of the wrapped connection, as *net.TCPConn and *tls.Conn do, or returns an error matching errors.ErrUnsupported when it cannot. On success it also ends a write's limiter wait with net.ErrClosed and refunds the unsent bytes.
func (NotifyStream) Meter ¶
func (s NotifyStream) Meter() *Meter
Meter returns the Meter of the wrapper's bytes.
func (*NotifyStream) NotifyReadable ¶
func (s *NotifyStream) NotifyReadable(f func()) (stop func() bool)
NotifyReadable calls f once TryRead would not block, as NotifyConn's NotifyReadable does.
func (NotifyStream) ReadFrom ¶
ReadFrom copies r to the wrapped writer until EOF, as io.Copy does. When the writer has a ReadFrom of its own and r is a file or, where the system splices them, a socket, the copy goes to that ReadFrom in chunks, each an io.LimitedReader of r within the limit and leases, so that it keeps a zero-copy path; otherwise it goes through Write.
func (NotifyStream) SetLimiters ¶
func (s NotifyStream) SetLimiters(read, write Limiter)
SetLimiters replaces the Limiters of the wrapper's reads and writes, as WithLimiters set them, from the next read or write; a wait in progress ends and starts over on the new ones, and nil leaves a direction unlimited. A Group's levels still apply on top.
func (*NotifyStream) TryRead ¶
func (s *NotifyStream) TryRead(b []byte) (int, error)
TryRead reads without blocking, as NotifyConn's TryRead does.
func (NotifyStream) WriteTo ¶
WriteTo copies the wrapped reader to w until EOF, as io.Copy does. When w has a ReadFrom of its own and is a socket, a file or a writer of this package, and the reader is a socket that the system splices, the copy goes to that ReadFrom in chunks, each an io.LimitedReader of the reader within the limit and leases, so that it keeps a zero-copy path; otherwise it goes through Read.
type Option ¶
type Option struct {
// contains filtered or unexported fields
}
Option changes how a wrapper of this package, or a Group's Open, wraps a connection or stream.
func WithCounter ¶
WithCounter adds the bytes of the wrapper to c, as Counter.Attach does, until it is closed. It may be given more than once.
Example ¶
Count a connection's bytes in a Counter shared with others.
package main
import (
"fmt"
"io"
"net"
"github.com/djylb/byterate"
)
func main() {
client, server := net.Pipe()
defer func() { _ = server.Close() }()
go func() { _, _ = server.Write([]byte("hello")) }()
var traffic byterate.Counter
conn := byterate.NewConn(client, byterate.WithCounter(&traffic))
defer func() { _ = conn.Close() }()
_, _ = io.ReadFull(conn, make([]byte, 5))
fmt.Println(traffic.Total())
}
Output: 5 0
func WithDatagram ¶
func WithDatagram() Option
WithDatagram treats every Read and Write as one whole message, which is never split, as for a message-oriented tunnel. UDP, IP and Unix datagram sockets are recognized without it.
func WithDrop ¶
func WithDrop() Option
WithDrop makes a PacketConn drop the datagrams that its limit does not let through at once, as TryWait decides, instead of waiting for them: such a datagram is not charged, a WriteTo of it returns len(b) and nil, as a UDP socket whose buffer is full does, and a ReadFrom discards it and reads the next one. A limit that refuses a datagram, such as an exhausted Budget, still ends the WriteTo or ReadFrom with its error.
func WithLimiter ¶
WithLimiter charges both directions to l, the same Limiter, so that reads and writes share one limit. A Group's Open charges it on top of the Group's levels.
func WithLimiters ¶
WithLimiters charges reads to read and writes to write, each limited and counted on its own; a nil Limiter leaves its direction unlimited.
Example ¶
Limit downloads and uploads apart, each metered on its own.
package main
import (
"fmt"
"io"
"net"
"github.com/djylb/byterate"
)
func main() {
download, upload := byterate.NewRate(4<<20), byterate.NewRate(1<<20)
client, server := net.Pipe()
defer func() { _ = server.Close() }()
conn := byterate.NewConn(client, byterate.WithLimiters(download, upload))
defer func() { _ = conn.Close() }()
go func() { _, _ = conn.Write([]byte("up")) }()
_, _ = io.ReadFull(server, make([]byte, 2))
fmt.Println(download.Limit(), upload.Limit())
}
Output: 4194304 1048576
type PacketConn ¶
type PacketConn struct {
// contains filtered or unexported fields
}
PacketConn is the wrapper of a net.PacketConn made by NewPacketConn and Group.OpenPacketConn.
func NewPacketConn ¶
func NewPacketConn(c net.PacketConn, opts ...Option) *PacketConn
NewPacketConn wraps c so that the datagrams it reads and writes are counted in the Meter and, with WithLimiter or WithLimiters, limited, as NewConn does for a connection's datagrams: a WriteTo is charged and sent whole, and a ReadFrom waits until the limit has no debt, then reads a whole datagram and charges it. Without a limit, they pass straight through and only count. Close, the deadlines set through the result and errors end its waits as they end those of NewConn. A sender that would rather drop the datagrams that the limit does not let through at once than wait for them passes WithDrop.
func (*PacketConn) Abort ¶
func (c *PacketConn) Abort(cause error)
Abort aborts the wrapped connection, as Conn's Abort does, and closes the wrapper; a datagram socket has no reset, so for one it only closes.
func (*PacketConn) Close ¶
func (c *PacketConn) Close() error
Close closes the wrapped connection and ends c's waits, as Conn's Close does.
func (*PacketConn) LocalAddr ¶
func (c *PacketConn) LocalAddr() net.Addr
LocalAddr returns the local address of the wrapped connection, or nil without one.
func (*PacketConn) Meter ¶
func (c *PacketConn) Meter() *Meter
Meter returns the Meter of the datagrams' bytes.
func (*PacketConn) ReadFrom ¶
ReadFrom reads a whole datagram into b, once the read limit has no debt, and charges it; with WithDrop, it drops the datagrams that the limit does not let through at once and reads the next.
func (*PacketConn) SetDeadline ¶
func (c *PacketConn) SetDeadline(t time.Time) error
SetDeadline sets the read and write deadlines of the wrapped connection and ends c's limit waits at them, as Conn's does.
func (*PacketConn) SetLimiters ¶
func (c *PacketConn) SetLimiters(read, write Limiter)
SetLimiters replaces the Limiters of reads and writes, as Conn's does.
func (*PacketConn) SetReadDeadline ¶
func (c *PacketConn) SetReadDeadline(t time.Time) error
SetReadDeadline sets the read deadline, as SetDeadline does for both.
func (*PacketConn) SetWriteDeadline ¶
func (c *PacketConn) SetWriteDeadline(t time.Time) error
SetWriteDeadline sets the write deadline, as SetDeadline does for both.
type Rate ¶
type Rate struct {
// contains filtered or unexported fields
}
Rate is a bytes-per-second limiter (GCRA, a token-bucket variant). A limit <= 0 means unlimited, and after an idle period a burst of bytes passes without waiting, two seconds' worth unless SetBurst sets another. Disable turns the limit off for a while, waking the callers waiting for it; unlimited and disabled alike, a Rate passes everything. A Counter measures throughput.
All methods are safe for concurrent use and on a nil *Rate, which never limits. The zero value is an enabled, unlimited Rate, ready for SetLimit. A Rate must not be copied after first use; use Clone.
Example ¶
The zero value of a Rate is ready to use.
package main
import (
"fmt"
"github.com/djylb/byterate"
)
func main() {
var r byterate.Rate // unlimited
r.SetLimit(64 << 10)
fmt.Println(r.Limit())
}
Output: 65536
Example (Json) ¶
Keep a Rate in JSON. The package leaves the JSON form to the application, since what is stored, and under which names, is the application's format. The field is a pointer, so that encoding/json finds the methods also when the struct around it is not addressable.
package main
import (
"encoding/json"
"fmt"
"github.com/djylb/byterate"
)
// savedRate stores a Rate in a configuration file or an API response in the
// application's own JSON form.
type savedRate struct {
*byterate.Rate
}
type savedRateJSON struct {
Limit int64 `json:"limit"` // bytes/s, 0 for none
}
func (r *savedRate) MarshalJSON() ([]byte, error) {
return json.Marshal(savedRateJSON{Limit: max(r.Limit(), 0)})
}
func (r *savedRate) UnmarshalJSON(b []byte) error {
var v savedRateJSON
if err := json.Unmarshal(b, &v); err != nil {
return err
}
if r.Rate == nil {
r.Rate = byterate.NewRate(v.Limit)
} else {
r.SetLimit(v.Limit)
}
return nil
}
// Keep a Rate in JSON. The package leaves the JSON form to the
// application, since what is stored, and under which names, is the
// application's format. The field is a pointer, so that encoding/json finds
// the methods also when the struct around it is not addressable.
func main() {
var user struct {
Name string `json:"name"`
Rate *savedRate `json:"rate"`
}
_ = json.Unmarshal([]byte(`{"name":"alice","rate":{"limit":1048576}}`), &user)
fmt.Println(user.Rate.Limit())
out, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(out))
}
Output: 1048576 {"name":"alice","rate":{"limit":1048576}}
func NewRate ¶
NewRate returns a Rate limited to limitBps bytes per second with a full burst available. A limitBps <= 0 means unlimited; such a Rate takes no more memory than its own until something is charged to it.
func (*Rate) Acquire ¶
Acquire blocks until r lets at least minBytes bytes through and takes between minBytes and maxBytes of them, as Reserver describes: r's credit, or a quantum of about 20 ms of traffic when it has too little, but never less than minBytes. When ctx ends first it returns ctx.Err() and keeps nothing; Disable and Reset end the wait early. A nil, disabled or unlimited r grants maxBytes at once.
func (*Rate) Charge ¶
Charge records n transferred bytes without waiting, as debt that the next Ready or Wait waits for. It returns nil.
func (*Rate) Clone ¶
Clone returns an independent copy of r's limit, burst, debt, enabled or disabled state. Callers blocked on r are not affected by the copy.
func (*Rate) Disable ¶
func (r *Rate) Disable()
Disable turns r's limit off until Enable: traffic charged to it passes at once, as with no limit, and callers blocked in Wait are woken. It keeps the limit for Enable. It does not block traffic; a hierarchy keeps its other Rates.
func (*Rate) Enable ¶
func (r *Rate) Enable()
Enable undoes Disable, starting over with a full burst. It is a no-op on an enabled Rate.
func (*Rate) Ready ¶
Ready blocks until r has no debt worth a wait, or until ctx is done, and returns how many of n bytes may pass at once: r's credit or, without enough, a quantum of about 20 ms of traffic, at least 1 byte. It charges nothing; Charge records the bytes that passed.
Example ¶
Drive a relay's hooks with a limiter: Ready before each read says how many bytes may pass, and Charge after each write records them.
package main
import (
"context"
"fmt"
"github.com/djylb/byterate"
)
func main() {
r := byterate.NewRate(1 << 20)
src := make([]byte, 100<<10)
sent := 0
for sent < len(src) {
n, err := r.Ready(context.Background(), int64(len(src)-sent))
if err != nil {
break
}
sent += int(n) // read and write n bytes here
_ = r.Charge(n)
}
fmt.Println(sent)
}
Output: 102400
func (*Rate) Refund ¶
Refund gives back n bytes charged by Wait, TryWait or Charge that were not transferred, such as the unwritten part of a short write. A refund never raises the available burst above r's burst. While r is unlimited, the refund still comes off the debt left from the last limit, which SetLimit keeps as bytes; while it is disabled, it does nothing.
Refund takes no receipt, so it cannot tell which charge it gives back: bytes charged before the last Enable or Reset, which cleared the debt, are refunded all the same, and so is debt for bytes charged while r was unlimited or disabled, which added none. Refund only bytes of a charge that r took since the last Enable or Reset and while it had the same kind of limit. The connection wrappers, hierarchies, Switches, Budgets and Groups keep a receipt of each charge instead and refund exactly what it took, in the generation it took it.
func (*Rate) Reset ¶
Reset is Disable, SetLimit and Enable: it wakes blocked callers, clears the debt, and starts over with a full burst at the new limit.
func (*Rate) SetBurst ¶
SetBurst sets how much traffic r lets through at once after an idle period: d's worth at the limit, two seconds' worth by default and for a d <= 0. A smaller burst smooths traffic out, a larger one lets bursts through; it also bounds the bytes a connection passes per grant. It applies from the next charge.
func (*Rate) SetFair ¶
SetFair turns fair scheduling of r's flows on or off. A flow is a direction of a connection wrapper; plain Wait, Ready and Charge calls are not flows. Without it, every charge queues behind the debt of all charges before it, so a flow that sends little, such as an interactive one, waits behind the grants of the flows that keep r busy. With it, a sparse flow — one whose last charge did not wait, or that paused since — takes up to a quantum of traffic (about 20 ms at the limit) through a sparse lane, without waiting for that debt, while the flows that stay busy share the limit in turns of a quantum, as before. The bytes of the sparse lane are charged to r all the same, so the other flows pay for them and the limit holds over time; the lane itself runs at the limit with a burst of one quantum, which bounds what sparse flows pass ahead of the others, and a flow that fills it waits and counts as busy. TryWait does not use the lane. The zero value is off.
func (*Rate) SetLimit ¶
SetLimit sets the limit in bytes per second; limitBps <= 0 means unlimited. It applies from the next charge, and debt is kept as bytes: what callers owe at the old limit is repaid at the new one, also after a time without a limit. Callers blocked in Wait are not woken and keep their wait; Reset wakes them, drops the debt, and restores the full burst.
func (*Rate) TryAcquire ¶
TryAcquire takes between minBytes and maxBytes bytes of r's credit if it has at least minBytes, as Reserver describes, and otherwise returns ErrWouldWait. A limited r never lets through more than its burst at once, so set the burst to at least the largest datagram.
func (*Rate) TryWait ¶
TryWait charges n bytes if r lets them through without waiting, as Wait would, and otherwise charges nothing and returns ErrWouldWait. A nil, disabled or unlimited r lets everything through; a limited one never lets through more than its burst at once, so set the burst to at least the largest datagram.
Example ¶
Drop the datagrams that a limit does not let through at once, as a UDP relay does, instead of waiting for them.
package main
import (
"fmt"
"github.com/djylb/byterate"
)
func main() {
limit := byterate.NewRate(1000) // a burst of 2000 bytes
sent, dropped := 0, 0
for range 5 {
packet := make([]byte, 600)
if err := limit.TryWait(int64(len(packet))); err != nil {
dropped++ // byterate.ErrWouldWait, or a refusal such as ErrBudgetExhausted
continue
}
sent++ // conn.WriteTo(packet, addr)
}
fmt.Println(sent, dropped)
}
Output: 3 2
func (*Rate) Wait ¶
Wait charges n bytes and blocks until the limit allows them, or until ctx is done, when it returns ctx.Err() and keeps the charge; refund bytes that were not transferred with Refund. It returns at once if r is nil, disabled or unlimited; Disable and Reset wake a blocked Wait early.
type Reserver ¶
type Reserver interface {
Limiter
// Acquire blocks until the limit lets at least minBytes through, takes
// between minBytes and maxBytes, as many as it lets through at once,
// and returns how many it took. Acquire(ctx, n, n) waits for all n
// bytes, as Wait does, and a minBytes above a Rate's burst is granted
// once the debt beyond the burst is repaid. Unlike Wait, it keeps
// nothing on error: ctx.Err() when ctx ends first, or the error of a
// limit that refuses the bytes, such as ErrBudgetExhausted.
Acquire(ctx context.Context, minBytes, maxBytes int64) (int64, error)
// TryAcquire takes between minBytes and maxBytes, as many as the limit
// lets through at once, if that is at least minBytes, and returns how
// many it took. Otherwise it takes nothing and returns ErrWouldWait, or
// first the error of a limit that refuses the bytes. TryAcquire(n, n)
// takes all n or none, as TryWait does; TryAcquire(1, n) takes what it
// can of n. A limited Rate never lets through more than its burst at
// once.
TryAcquire(minBytes, maxBytes int64) (int64, error)
}
Reserver is a Limiter that also reserves a range of bytes ahead, for a forwarder or a batched writer that learns how much it sends only after it has reserved room for it. Every Limiter of this package implements it: *Rate, *Budget, *Switch, the result of NewHierarchy and the Reads and Writes of a Group, which return it as a Reserver.
Acquire and TryAcquire take as much of the range as the limit allows at once, at least minBytes, on the same charges as Wait and TryWait, and Refund gives back what was not sent. Grants never add up to more than the limit allows, however many callers share it, and a hierarchy takes them on every level or on none. A maxBytes of 0 or less takes nothing; a minBytes below 1 counts as 1 and one above maxBytes as maxBytes.
func NewHierarchy ¶
NewHierarchy combines limiters into one Limiter of nested levels, such as a connection's Rate within its user's Rate and Budget within a global Rate. It charges every level and waits until every one allows the bytes, so the strictest sets the pace. A limit set on any of them later applies to the next charge, also an unlimited Rate's. Disable on a Rate ends the wait it imposes, and the others still apply; a disabled Rate limits nothing until Enable.
The levels of a hierarchy given as a level take its place. Nil limiters, also nil pointers of this package's types, are left out, and so are repeats of a limiter of this package, so that a level given twice is charged once; unlimited Rates are kept, as they can be limited later. NewHierarchy returns nil when no level remains and that level itself when one does. Pass nil for levels that never limit: an unlimited Rate still costs a charge per call, and keeps a wrapper off its fast path.
A level that refuses a charge, such as an exhausted Budget, is asked first and refuses it for the whole: Wait then gives the bytes back to every level that took them, and the others neither take them nor make the caller wait. TryWait charges every level or none: if any refuses, or would make the caller wait, the others take nothing, and a refusal is reported before ErrWouldWait. Charge, which records bytes already transferred, leaves them on every level and returns the first refusal. Refund gives the bytes back to every level; Ready returns the least that any level grants, at least 1.
Every level is charged when the bytes are, not when the strictest lets them pass, so a looser Rate counts bytes still waiting on a stricter one. Each keeps its long-run limit, but when many waits on stricter levels end together, a looser Rate they share can pass more than its burst at once: up to the bytes of those waits.
Example ¶
Nest a connection's limit within its user's and a global one. A limit changed later applies to open connections too.
package main
import (
"fmt"
"io"
"net"
"github.com/djylb/byterate"
)
func main() {
global := byterate.NewRate(0) // unlimited for now
user := byterate.NewRate(8 << 20) // 8 MiB/s across the user's connections
client, server := net.Pipe()
defer func() { _ = server.Close() }()
conn := byterate.NewConn(client, byterate.WithLimiter(byterate.NewHierarchy(byterate.NewRate(1<<20), user, global)))
defer func() { _ = conn.Close() }()
go func() { _, _ = conn.Write(make([]byte, 4096)) }()
_, _ = io.ReadFull(server, make([]byte, 4096))
fmt.Println(global.Limit(), user.Limit())
global.SetLimit(100 << 20) // now limits the open connection too
}
Output: 0 8388608
type Step ¶
type Step struct {
// After is the number of bytes used in the period from which the step
// applies.
After int64
// Limit, if set, is charged for the bytes of the step on top of the
// other limits, so that it sets their pace, such as a slower Rate. A
// step with Stop or Pause needs none, and charges none given.
Limit Limiter
// Stop ends the period's traffic: from After on, the Budget refuses all
// bytes with ErrBudgetExhausted, which ends the connection reads and
// writes charged to it, and steps after it never apply. A step with
// Stop stops, whether it has Pause or not.
Stop bool
// Pause holds the traffic from After on without refusing it: Wait and
// Ready block, and the connection reads and writes charged to the
// Budget with them, and TryWait returns ErrWouldWait, until a change
// of the Budget lets the bytes through or refuses them. SetSteps,
// Reset, SetUsed, SetExpiry, SetClock and the expiry itself wake the
// waits, which, with a Clock set, find the expiry at the next change;
// so do the end of their ctx and a wrapper's Close, deadline and
// SetLimiters, and, for a blocking wait, a Switch it waits through.
// Bytes given back meanwhile by Refund or a Lease pass the next charge
// but wake no wait, and the levels of a Group apply to a wait from the
// next read or write. The NotifyReadable of a wrapper paused so holds
// no goroutine; the change that ends the pause has its calls made on
// a goroutine of their own.
Pause bool
}
Step is a step of a Budget: what applies once the bytes used in the period reach After.
type Stream ¶
type Stream struct {
// contains filtered or unexported fields
}
Stream is the wrapper of an io.Reader, io.Writer or io.ReadWriteCloser, made by NewReader, NewWriter and NewStream: a Conn without addresses or deadlines.
func NewReader ¶
NewReader wraps r for reading alone, as NewStream does; Close closes r if it is an io.Closer, and Write returns ErrNilConn.
func NewStream ¶
func NewStream(rwc io.ReadWriteCloser, opts ...Option) *Stream
NewStream wraps rwc as NewConn wraps a connection. Its methods return ErrNilConn if rwc is nil.
func NewWriter ¶
NewWriter wraps w for writing alone, as NewStream does; Close closes w if it is an io.Closer, and Read returns ErrNilConn.
func (*Stream) Abort ¶
func (s *Stream) Abort(cause error)
Abort ends the connection abnormally, so that its peer sees a cut instead of an end of data, and then closes the wrapper as Close does: a wrapped connection with a method Abort(cause error), such as a stream of a multiplexed connection, is aborted with cause; otherwise a wrapped connection with a method SetLinger(sec int) error, a *net.TCPConn, also beneath wrappers that return what they wrap from a NetConn method, gets SO_LINGER 0, so that its close sends RST instead of FIN. A connection with neither is just closed. Relays that end a transfer on an error, such as netx.Relay, call it through the same method set.
func (*Stream) Close ¶
func (s *Stream) Close() error
Close ends the waits in progress with net.ErrClosed, gives back the unused bytes of the leases, takes the wrapper's bytes out of its Counters as counted, gives back its Group's slot and closes what it wraps. Only the first Close does all but the last.
func (*Stream) CloseRead ¶
func (s *Stream) CloseRead() error
CloseRead shuts down the reading side of the wrapped connection, as *net.TCPConn does, or returns an error matching errors.ErrUnsupported when it cannot. On success it also ends a read's limiter wait with net.ErrClosed.
func (*Stream) CloseWrite ¶
func (s *Stream) CloseWrite() error
CloseWrite shuts down the writing side of the wrapped connection, as *net.TCPConn and *tls.Conn do, or returns an error matching errors.ErrUnsupported when it cannot. On success it also ends a write's limiter wait with net.ErrClosed and refunds the unsent bytes.
func (*Stream) Meter ¶
func (s *Stream) Meter() *Meter
Meter returns the Meter of the wrapper's bytes.
func (*Stream) Notifying ¶
func (s *Stream) Notifying() io.ReadWriteCloser
Notifying returns s as a *NotifyStream when what it reads has the methods TryRead and NotifyReadable, as Conn's Notifying does; otherwise it returns s itself.
func (*Stream) ReadFrom ¶
ReadFrom copies r to the wrapped writer until EOF, as io.Copy does. When the writer has a ReadFrom of its own and r is a file or, where the system splices them, a socket, the copy goes to that ReadFrom in chunks, each an io.LimitedReader of r within the limit and leases, so that it keeps a zero-copy path; otherwise it goes through Write.
func (*Stream) SetLimiters ¶
func (s *Stream) SetLimiters(read, write Limiter)
SetLimiters replaces the Limiters of the wrapper's reads and writes, as WithLimiters set them, from the next read or write; a wait in progress ends and starts over on the new ones, and nil leaves a direction unlimited. A Group's levels still apply on top.
func (*Stream) WriteTo ¶
WriteTo copies the wrapped reader to w until EOF, as io.Copy does. When w has a ReadFrom of its own and is a socket, a file or a writer of this package, and the reader is a socket that the system splices, the copy goes to that ReadFrom in chunks, each an io.LimitedReader of the reader within the limit and leases, so that it keeps a zero-copy path; otherwise it goes through Read.
type Switch ¶
type Switch struct {
// contains filtered or unexported fields
}
Switch is a Limiter that passes every charge on to another Limiter, which Set can replace at any time, such as when a connection's traffic moves to another account. Charges made after Set go to the new Limiter. A wait in progress on a Rate of the old one ends at once and starts over on the new one, its charge refunded to the old, so that a connection limited through a Switch follows the new Limiter for the bytes it has not yet sent or received.
The connection wrappers and a hierarchy that holds the Switch refund a canceled or failed charge to the Limiters that took it, Rates only within the generation they charged. Refund called directly goes to the current Limiter, so call it before Set for bytes charged to the old one.
All methods are safe for concurrent use and on a nil *Switch, which never limits. The zero value passes everything until Set.
Example ¶
Move a connection's traffic to another limiter while it runs.
package main
import (
"fmt"
"net"
"github.com/djylb/byterate"
)
func main() {
oldUser, newUser := byterate.NewRate(1<<20), byterate.NewRate(4<<20)
sw := byterate.NewSwitch(oldUser)
client, server := net.Pipe()
defer func() { _ = server.Close() }()
conn := byterate.NewConn(client, byterate.WithLimiter(sw))
defer func() { _ = conn.Close() }()
sw.Set(newUser) // charges, and waits in progress, move to newUser
fmt.Println(sw.Limiter() == byterate.Limiter(newUser))
}
Output: true
func (*Switch) Acquire ¶
Acquire takes between minBytes and maxBytes bytes from the current Limiter, as its Acquire does; if Set replaces it meanwhile, the charge moves to the new one.
func (*Switch) Ready ¶
Ready waits until the current Limiter is ready, as its Ready does, and starts over on a new one if Set replaces it meanwhile.
func (*Switch) Set ¶
Set makes s pass charges on to l from now on, and ends the waits in progress on the Rates of the old Limiter, which start over on l; a wait inside another kind of Limiter runs to its end there. It panics if l passes charges on to s, which would charge s without end.
func (*Switch) TryAcquire ¶
TryAcquire takes between minBytes and maxBytes bytes from the current Limiter, as its TryAcquire does.
type TooManyConnsError ¶
type TooManyConnsError struct {
// contains filtered or unexported fields
}
TooManyConnsError is the error of Acquire and Open when a Group refuses a connection slot: errors.Is reports it as ErrTooManyConns, and Group returns the Group that refused, which is the one opened or an ancestor.
func (*TooManyConnsError) Error ¶
func (e *TooManyConnsError) Error() string
func (*TooManyConnsError) Group ¶
func (e *TooManyConnsError) Group() *Group
Group returns the Group at its MaxConns that refused the slot.
func (*TooManyConnsError) Is ¶
func (e *TooManyConnsError) Is(target error) bool
Is reports whether target is ErrTooManyConns.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
leakcheck
Package leakcheck checks test binaries for leaked goroutines: Find lists the goroutines still running besides the caller, the test framework's and the runtime's own, waiting a while for them to end first, and VerifyTestMain fails a whole test binary with them.
|
Package leakcheck checks test binaries for leaked goroutines: Find lists the goroutines still running besides the caller, the test framework's and the runtime's own, waiting a while for them to end first, and VerifyTestMain fails a whole test binary with them. |