byterate

package module
v0.0.0-...-2da608d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

byterate

Byte rate limiting, byte budgets, traffic counting and throughput for Go connections and streams.

Install

go get github.com/djylb/byterate

Usage

Count a connection's bytes, or limit it as well; the result is still a net.Conn:

counted := byterate.NewConn(conn)                                         // counts only
limited := byterate.NewConn(conn, byterate.WithLimiter(byterate.NewRate(1<<20))) // 1 MiB/s both ways

read, written := limited.Meter().Total()

A connection without a limit passes its reads and writes straight through and only counts them. SetLimiters adds, changes or lifts a limit at any time, also for a transfer in progress, whose wait starts over on the new limit:

counted.SetLimiters(nil, byterate.NewRate(512<<10)) // writes at 512 KiB/s from now on
counted.SetLimiters(nil, nil)                         // unlimited again

Nest limits, such as a connection's within its user's within a global one. A limit changed later applies to open connections too:

global := byterate.NewRate(0)      // unlimited for now
user := byterate.NewRate(10 << 20) // 10 MiB/s across the user's connections

c := byterate.NewConn(conn, byterate.WithLimiter(byterate.NewHierarchy(byterate.NewRate(2<<20), user, global)))
user.SetLimit(20 << 20)

Limit downloads and uploads apart:

c := byterate.NewConn(conn, byterate.WithLimiters(byterate.NewRate(8<<20), byterate.NewRate(1<<20)))

NewStream does the same for an io.ReadWriteCloser, NewReader and NewWriter for a plain io.Reader or io.Writer, whose Close ends a wait, and NewPacketConn for a net.PacketConn. The zero value of Rate is ready to use, unlimited until SetLimit.

A server that limits, counts and caps the connections of many users is simplest with a Group per user under one for the server, below.

More

Groups. A Group is a level of a tree, such as a server, a user, a client and a tunnel. A connection opened in a Group is limited by every level above it, counts in every level's traffic and connections, and each level can cap its connections:

server := byterate.NewGroup(nil)
user := byterate.NewGroup(server)
tunnel := byterate.NewGroup(user)

user.SetLimiters(byterate.NewRate(10<<20), byterate.NewRate(2<<20)) // reads, writes
user.SetMaxConns(100)

c, err := tunnel.Open(conn) // a *byterate.TooManyConnsError past a cap
if err != nil {
	conn.Close()
	return err
}
defer c.Close() // gives the slot back

user.Conns()                           // connections of the user and below
read, written := user.Traffic().Load() // bytes read and written below the user
readBps, writtenBps := user.Traffic().Throughput()
tunnel.SetParent(otherUser)            // move the tunnel, its connections with it

OpenPacketConn and OpenStream do the same as NewPacketConn and NewStream. The options of the wrappers apply to Open too:

c, err := tunnel.Open(conn,
	byterate.WithLimiters(nil, byterate.NewRate(1<<20)), // a limit of the connection's own
	byterate.WithCounter(&perConn),                       // also counted here
	byterate.WithWait(ctx))                               // wait for a slot instead of refusing

errors.Is(err, byterate.ErrTooManyConns) matches a refusal, and errors.As gives the *TooManyConnsError, whose Group is the level that refused. Acquire, AcquireContext and Release take, wait for and give back a slot alone, and Reads and Writes return the limiters of a group's reads and writes, for relays that call hooks per read and write. A level's limiters can be any limiter, such as a Budget or a NewHierarchy of several.

Budgets. A Budget counts the bytes used in a period and applies steps as they grow: past each step's After, its Limit slows the traffic down, or Stop ends it with ErrBudgetExhausted:

daily := byterate.NewBudget(
	byterate.Step{After: 10 << 30, Limit: byterate.NewRate(1 << 20)},  // past 10 GiB: 1 MiB/s
	byterate.Step{After: 20 << 30, Limit: byterate.NewRate(64 << 10)}, // past 20 GiB: 64 KiB/s
	byterate.Step{After: 30 << 30, Stop: true},                        // past 30 GiB: stop
)
daily.OnStep(func(step int, used int64) { /* notify */ })

c := byterate.NewConn(conn, byterate.WithLimiter(byterate.NewHierarchy(user, daily)))

daily.Reset()        // a new period starts over
daily.SetSteps(...)  // new steps, from the next read or write; Steps() returns them
daily.Used()         // the bytes used in the period
daily.Remaining()    // the bytes left before the stop, 0 once stopped

A step with Pause holds the traffic without refusing it, such as until a quota is confirmed: reads and writes wait, and TryWait returns ErrWouldWait, until SetSteps, Reset, SetUsed, SetExpiry or the expiry lets the bytes through or stops them. A paused reader's NotifyReadable holds no goroutine while it waits:

held := byterate.NewBudget(byterate.Step{Pause: true}) // nothing passes yet
held.SetSteps()                                         // everything waiting passes

None of these changes ends a connection. Periods are up to the caller, such as each hour, day or week:

var next func()
next = func() { daily.Reset(); time.AfterFunc(24*time.Hour, next) }
time.AfterFunc(time.Until(midnight), next)

A wrapper leases a Budget's bytes ahead instead of charging it at every read and write, so a quota costs no more than counting. Code that passes bytes itself can lease too:

lease, err := daily.Lease(1 << 20) // up to 1 MiB, ErrBudgetExhausted once stopped
// pass up to lease.Bytes bytes
daily.Settle(lease, sent)          // give back what was not used

Counting. Every wrapper counts its bytes in its Meter. A Counter adds up bytes: those of Add, and those of the Meters attached to it, by WithCounter or Attach, which cost the connections' reads and writes nothing, since the Counter adds them up when read. A wrapper stays attached until its Close; one dropped without Close is detached, keeping its bytes, once the garbage collector finds it, which can be much later, so close every wrapper for timely accounting. Swap takes the totals since the last Swap, so that each byte is reported once, and Total the running totals, to persist or report as snapshots; Restore adds persisted totals back after a restart and Set replaces the totals, neither counting as traffic:

var traffic byterate.Counter // shared by many connections
c := byterate.NewConn(conn, byterate.WithCounter(&traffic))

read, written := traffic.Swap()

Throughput. Throughput reports a Counter's bytes per second between its last two samples. Counting never reads the clock: the totals are sampled by Throughput itself or by Sample, at most once in each second of the Counter's clock, and the bytes between two samples are averaged over the whole seconds between them. So the first Throughput without a ticker only takes the first sample and reports 0, and a later one reports the average over the interval since the previous call, such as the whole of a long pause, not its last second. What it reports depends on when the samples were taken, by any caller; for the throughput of every second, independent of how often it is read, call SampleEverySecond, which samples it from a ticker that all such Counters share and drops it once it is garbage, or call Sample once a second from a ticker of your own. Limiters, such as a Rate in a NewHierarchy, measure no throughput: give the connection a Counter with WithCounter, or open it in a Group, whose Traffic counts it:

traffic.SampleEverySecond()
readBps, writtenBps := traffic.Throughput()

SetClock gives a Counter, and a Budget for its expiry, a clock of the caller's, such as a fake one in tests: any type with Now() time.Time.

Switching. A Switch moves the traffic of every connection it limits to another limiter at once, while they run:

sw := byterate.NewSwitch(oldUser)
c := byterate.NewConn(conn, byterate.WithLimiter(sw))
sw.Set(newUser) // waits in progress start over on newUser

Relays. A relay that calls a hook before each read and after each write can use any limiter's Ready and Charge: Ready blocks until the limit is ready and says how many bytes may pass, and Charge records the bytes that did. A Group's Reads and Writes fit both, and count the bytes in its traffic; a Counter's Add counts them alone:

type hooks struct {
	Wait func(ctx context.Context, max int64) (int64, error)
	Done func(n int64) error
}

l := byterate.NewHierarchy(connRate, user, budget)
upload := hooks{Wait: l.Ready, Done: l.Charge}
download := hooks{Wait: tunnel.Reads().Ready, Done: tunnel.Reads().Charge}

Datagrams. UDP, IP and Unix datagram sockets are never split: each message is charged and sent whole. WithDatagram does the same for other connections that carry one message per Read and Write. NewPacketConn charges each ReadFrom and WriteTo of a net.PacketConn whole. With WithDrop, it drops the datagrams that would wait instead, as a UDP relay does: such a datagram is not charged, WriteTo reports it sent and ReadFrom reads on to the next one; a refusal such as ErrBudgetExhausted is still returned:

pc := byterate.NewPacketConn(udp, byterate.WithLimiter(limit), byterate.WithDrop())

Code that sends datagrams itself asks TryWait, which charges the bytes only if they may pass at once, at every level of a hierarchy or none:

if err := limit.TryWait(int64(len(packet))); err != nil {
	continue // byterate.ErrWouldWait, or a refusal such as ErrBudgetExhausted
}
if _, err := pc.WriteTo(packet, addr); err != nil {
	limit.Refund(int64(len(packet))) // not sent
}

Saving limits. The package has no JSON form of its own, since what an application stores, and under which names, is its own format; ExampleRate_json shows a small wrapper that saves Limit and restores it with NewRate or SetLimit.

Direct use. Any limiter can be charged directly: Wait(ctx, n) charges n bytes and blocks until the limit allows them, TryWait(n) charges them only if it need not block, and Refund(n) gives back bytes that were not transferred.

How it behaves

The fast path. A direction of a wrapper with no limiter, or none but Budgets with leases left, reads and writes without charging anything. Which path a read or write takes is chosen anew each time, and both give the same results: the same bytes counted, the same limits and budgets kept.

Limits. Limits are in bytes per second; 0 or less means unlimited. After an idle period a Rate lets a burst through at once: two seconds' worth, or what SetBurst sets; a smaller burst smooths traffic out. SetLimit takes effect from the next charge and keeps what is owed: bytes charged at the old limit are repaid at the new one. Reset instead wakes blocked callers, drops the debt and starts over with a full burst. An unlimited Rate in a wrapper's levels still costs a charge per read and write, as it can be limited later; leave it out, or use SetLimiters, for connections that should be counted alone.

Disable is not a block. Disable turns a Rate's limit off until Enable: traffic charged to it passes without limit and blocked callers are woken. To cut traffic, close the connections.

Waits are not first come, first served. A caller that a limit makes wait sleeps until the debt its own charge added is repaid, so callers sharing a limit get their share in grants, but are not woken in the order they came. AcquireContext wakes the callers waiting for a group's slot in order, one per freed slot, but another Acquire can take the slot first.

Connections pass data in grants. A grant is what the limit lets through at once: its credit, or without credit about 20 ms of traffic.

  • A Write sends its bytes a grant at a time, so a large Write neither bursts past the limit nor holds a shared limit while other connections wait. Concurrent limited Writes on one connection do not interleave.
  • A Read first waits until the limit has no debt, then reads at most a grant. A reader in debt leaves the data with the sender, and a reader waiting for data holds no share of the limit. Readers waiting on one shared limit read together when its debt is repaid, a grant each.
  • Datagrams are never split: each one is charged and sent whole.

Fair sharing. Connections that keep a shared limit busy take turns of a grant each, but a connection that sends little, such as an interactive one, still queues behind the grants already charged. Rate.SetFair(true) lets such a sparse connection through first: a direction of a wrapper counts as sparse while it has charged at most a grant since it last paused, and its transfers then pass through a sparse lane without waiting for the busy connections' debt. The bytes are still charged to the Rate, so the busy connections pay for them and the limit holds over time; the lane runs at the limit with a burst of one grant, which bounds what passes ahead of the others, and a connection that keeps sending becomes busy and takes turns again. Plain Wait, Ready and Charge calls and TryWait are not connections and queue as before.

Ending waits. Close ends a wait with net.ErrClosed, and CloseRead or CloseWrite do the same for their side. Deadlines set through the wrapper end waits with os.ErrDeadlineExceeded; a deadline set on the connection before wrapping it does not. A Write that is ended part way returns the bytes it sent and refunds the rest; a Read ended in its wait returns no bytes.

Half-close. The wrapper always has CloseRead and CloseWrite, which return an error matching errors.ErrUnsupported when the wrapped connection lacks them, so check the error rather than the method.

Abort. Abort(cause) ends a connection so that its peer sees a cut, not an end of data, and then closes the wrapper as Close does: a wrapped connection with an Abort(cause error) method is aborted, and a TCP connection, also beneath wrappers with a NetConn() net.Conn method, is closed with RST (SO_LINGER 0). Relays that abort their ends on an error find it by that method.

Nested limits. NewHierarchy charges every level and waits for the strictest. Disable on one level ends the wait it imposes; the others still apply. Every level is charged when the bytes are, so a looser level counts bytes still waiting on a stricter one: it keeps its long-run limit, but when many waits on stricter levels end together, it can pass more than its burst at once. Pass nil for levels that should not limit.

Refusals. A level that refuses bytes, such as a stopped Budget, is asked first and refuses them for the whole hierarchy: the other levels neither take them nor make the caller wait. Charge, which records bytes already transferred, keeps them on every level and returns the refusal.

Budgets. A Budget blocks by itself only at a Pause step; otherwise the Limit of its step does. A wait at a pause ends with the change that ends the pause, the end of its context, or a wrapper's Close, deadline or SetLimiters, and charges nothing until it passes. Once the usage reaches a Stop step, it refuses everything until the next period. Writes never take the usage past it, even concurrent ones: a Write sends what fits and fails. A Read reads no more than is left: the Read that reaches the stop returns its bytes and a nil error, and the next one returns ErrBudgetExhausted; a read counts what arrived, so a datagram, read whole, and a read in progress when its lease is taken back can pass the stop by what they read, which counts as used: at most one datagram, or one read buffer, per read in progress, such as up to 64 KiB for each concurrent read of a UDP socket. Steps apply from their After. The bytes used count everything charged to the Budget, whichever step applied, and a step's Limit only the bytes of its step; a Limit adds to the other limits, so it can only slow traffic down. For steps that also speed it up, leave the base speed out of the hierarchy and give the first step, at After: 0, a Limit as well.

Leases. A wrapper leases about half of what a Budget has left, between 16 KiB and 1 MiB, never past the next step or the stop, and passes that many bytes without asking the Budget again; with less than 16 KiB of its lease left, a read or write leases more first, so that it is not split. While a step's Limit applies, or while a Budget with an expiry reads a clock of SetClock, the wrapper charges the Budget at every read and write instead, and leases again once a change, such as a Reset, ends that. Leased bytes count as used when leased, so connections that share a Budget never pass its stop together, and Used and Remaining leave out what the leases hold unused, so they report the bytes that passed. A Budget takes back what the other connections' leases hold unused before it refuses bytes, so any one connection can use it up to its stop.

Reset, SetUsed, SetSteps, SetExpiry and the expiry itself take every lease back at once: the next read or write leases under the change, and what passes after a Reset counts in the new period. The bounds that remain:

  • a read counts what arrived after it, so concurrent reads on one direction of a connection, and a read in progress when its lease is taken back, can pass the lease by what each reads, which then counts as used;
  • a write that fails or is cut short after a Reset or SetUsed took its lease back, and another write of the connection leased again, leaves its unsent bytes to the new lease, which the new period then does not count;
  • a write that fails or is cut short after SetLimiters took a Budget off its connection keeps its unsent bytes charged to that Budget;
  • the expiry takes leases back when its timer fires, so a read or write already admitted then completes;
  • OnStep reports a step once the bytes that passed reach it, not when a lease reaches it, so a lease taken back unused reports nothing, and each step at most once a period; a connection that reaches a step finds it at its next read, write or Close, and a step applies from its After in each connection's leases.

Close gives back what a lease did not use; a wrapper dropped without Close gives it back once the garbage collector finds it.

Reset, SetUsed and SetSteps take effect from the next read or write, without ending connections; a slowed connection gets its full speed back from its next grant. SetUsed takes back persisted usage after a restart, or a total that several budgets share, and SetExpiry stops all bytes after a time; AfterExpiry runs a function then, such as to close connections that sit idle and so never meet the refusal. Reset drops the usage of the period, so keep what is billed in a Counter.

Groups. Every read and write is limited by the limits of the group and each ancestor at that moment, and counted in each one's Traffic. After SetParent, a moved group's connections count in the new ancestors, their slots too, even past a cap, which then refuses new connections until enough close; the bytes counted before stay with the old ancestors. SetParent and SetLimiters apply to the open connections from their next grant, which is at most one chunk of traffic away; a wait in progress ends on the limits it began with. SetMaxConns limits the connections of a level and everything below it. Acquire takes a slot at every level or none. A limiter given to several levels is charged once. A Counter may be the Traffic of sibling groups, adding them up, but never counts the same bytes twice: SetTraffic, SetParent, Open with WithCounter and Counter.Attach return ErrCounterOverlap, and change nothing, where the Counter would count a group together with an ancestor or descendant, or a connection together with its group or an ancestor.

Switching. After Switch.Set, new charges go to the new limiter, and a wait in progress on a Rate of the old one ends, is refunded there, and starts over on the new one. A wrapper's SetLimiters does the same.

Refunds. The wrappers, hierarchies, switches, budgets and groups keep a receipt of each charge and refund exactly what it took: a Rate only within the generation it charged, a Budget within the period, also inside a Switch or a budget step. A direct Refund(n) has no receipt: it gives the bytes back to the limiter as it is now, so call it only for bytes the same limiter charged since its last Enable, Reset, SetUsed or Set, such as the unsent part of a Wait of your own.

Throughput. Counter.Throughput reports the average between the last two samples, the first reading 0: the bytes between two samples count evenly over the whole seconds between them, so a reading lags by up to the interval between samples, one to two seconds with a ticker calling Sample each second. Refunds are taken off, those of an earlier window off the following ones; Restore and Set are not traffic.

Reserving ahead

A forwarder or a batched writer often learns how much it sends only after it has reserved room for it. Every limiter of this package is a Reserver for that: Acquire(ctx, min, max) waits until at least min bytes may be taken and takes as many of max as the limit allows at once; TryAcquire(min, max) does the same without waiting, or takes nothing and returns ErrWouldWait; Refund gives back what was not sent. (n, n) asks for all n bytes or none, (1, n) for what the limit allows of them. Grants never add up to more than the limit, however many goroutines share it; a hierarchy takes them on every level or on none, and unlike Wait, a canceled or refused Acquire keeps nothing. NewHierarchy and a Group's Reads and Writes return a Reserver.

l := byterate.NewHierarchy(user, global)
n, err := l.Acquire(ctx, 1, int64(len(buf)))
if err != nil {
	return err
}
m, err := src.Read(buf[:n])
l.Refund(n - int64(m))

Writing a Limiter

Most code combines the limiters of this package. A Limiter of your own needs five methods: Wait charges bytes before they are sent and blocks until they may go, or returns an error, keeping no charge, to refuse them; TryWait charges them only if they may go at once and otherwise returns ErrWouldWait; Refund gives bytes back; Ready blocks until the limit is ready and says how many bytes may pass, without charging; and Charge records bytes already transferred. The wrappers use Ready to size each Read and Write.

Performance

A read or write on the fast path costs an atomic load and an uncontended atomic add on the connection's own cache line; it reads no clock and writes nothing that other connections share, so it does not slow down with the number of processors. A Counter or Group adds up its Meters when read, at a cost per attached connection, and a Group those of its children; opening and closing a connection registers it with its own Group alone, so connections of different Groups open and close without contending.

Charges are lock-free; a refund takes the Rate's lock briefly. A throttled connection reuses one timer per direction and does not allocate per Read or Write while a write charges up to eight limiters, a Budget and the limiter of its step counting as two. Wait and Ready called directly make a timer for each wait that needs one. Waits of up to 200 µs are accumulated as debt rather than slept. Callers waiting on a shared Rate are spread over several channels, so that many throttled connections do not contend on one. Counter.Add is an atomic add per direction; a Counter that many goroutines add to at once spreads their adds over more counters as it finds them contending, up to one per processor, so one that few add to stays small.

io.Copy to and from a wrapper keeps its zero-copy paths: the wrapper hands the connection, or the one at the other end, a chunk of at most 256 KiB at a time as an io.LimitedReader, within the limit and the leases, so sendfile from files and, on Linux, splice between sockets still move the data; a change of limit applies from the next chunk. Other copies go through Read and Write.

A connection or stream that reads without blocking and tells when it becomes readable, with methods TryRead(p []byte) (int, error) and NotifyReadable(f func()) (stop func() bool), such as a stream of a multiplexed connection, keeps them through Notifying, so that a relay need not hold a goroutine while it is idle. TryRead is charged and counted as Read is; while the read limit has debt it returns ErrWouldBlock, whose WouldBlock method reports true, and NotifyReadable calls back once the debt is repaid and the source is readable. Only a goroutine waiting out that debt is held, never one for an idle source. Notifying of a wrapper over any other connection returns the wrapper unchanged, without those methods.

Testing

Rate, Budget and Counter work inside testing/synctest bubbles, on the bubble's clock. Create them inside the bubble that uses them. A Counter and a Budget also take a clock of their own with SetClock.

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

Examples

Constants

This section is empty.

Variables

View Source
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")
)
View Source
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.

View Source
var ErrNilConn = errors.New("byterate: nil connection")

ErrNilConn is returned when a wrapper has no underlying connection.

View Source
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.

View Source
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

func NewBudget(steps ...Step) *Budget

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

func (b *Budget) Acquire(ctx context.Context, minBytes, maxBytes int64) (int64, error)

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

func (b *Budget) AfterExpiry(f func()) (stop func() bool)

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

func (b *Budget) Charge(n int64) error

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) Expiry

func (b *Budget) Expiry() time.Time

Expiry returns the time SetExpiry set, or the zero time for none.

func (*Budget) Lease

func (b *Budget) Lease(n int64) (Lease, error)

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

func (b *Budget) OnStep(f func(step int, used int64))

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

func (b *Budget) Ready(ctx context.Context, n int64) (int64, error)

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

func (b *Budget) Refund(n int64)

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

func (b *Budget) Remaining() int64

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

func (b *Budget) Return(l Lease, n int64)

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

func (b *Budget) SetClock(c Clock)

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

func (b *Budget) SetExpiry(t time.Time)

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

func (b *Budget) SetSteps(steps ...Step)

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

func (b *Budget) SetUsed(n int64)

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

func (b *Budget) Settle(l Lease, used int64)

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

func (b *Budget) Step() int

Step returns the index of the step that applies to Used, in the order of After, or -1 before the first step.

func (*Budget) Steps

func (b *Budget) Steps() []Step

Steps returns b's steps, sorted by After.

func (*Budget) TryAcquire

func (b *Budget) TryAcquire(minBytes, maxBytes int64) (int64, error)

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

func (b *Budget) TryWait(n int64) error

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.

func (*Budget) Used

func (b *Budget) Used() int64

Used returns the bytes used in the period.

func (*Budget) Wait

func (b *Budget) Wait(ctx context.Context, n int64) error

Wait charges n bytes to b and to the Limit of the step that applies, and waits for that Limit. It refuses them with ErrBudgetExhausted, charging nothing, when they would take the usage past a step with Stop, or after the expiry.

type Clock

type Clock interface {
	Now() time.Time
}

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

func NewConn(c net.Conn, opts ...Option) *Conn

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

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local address of the wrapped connection, or nil without one.

func (*Conn) Meter

func (s *Conn) Meter() *Meter

Meter returns the Meter of the wrapper's bytes.

func (*Conn) Notifying

func (c *Conn) Notifying() net.Conn

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) RawConn

func (c *Conn) RawConn() net.Conn

RawConn returns the wrapped connection.

func (*Conn) Read

func (s *Conn) Read(b []byte) (int, error)

func (*Conn) ReadFrom

func (s *Conn) ReadFrom(r io.Reader) (int64, error)

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

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote address of the wrapped connection, or nil without one.

func (*Conn) SetDeadline

func (c *Conn) SetDeadline(t time.Time) error

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

func (c *Conn) SetLimiters(read, write Limiter)

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

func (c *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline of the wrapped connection and, unless it rejects it, of the waits in the read limiter.

func (*Conn) SetWriteDeadline

func (c *Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline of the wrapped connection and, unless it rejects it, of the waits in the write limiter.

func (*Conn) Write

func (s *Conn) Write(b []byte) (int, error)

func (*Conn) WriteTo

func (s *Conn) WriteTo(w io.Writer) (int64, error)

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

func (c *Counter) Add(read, written int64)

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

func (c *Counter) Attach(m *Meter) error

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

func (c *Counter) Detach(m *Meter)

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) Load

func (c *Counter) Load() (read, written int64)

Load returns the bytes read and written since the last Swap.

func (*Counter) Restore

func (c *Counter) Restore(read, written int64)

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

func (c *Counter) Set(read, written int64)

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

func (c *Counter) SetClock(clk Clock)

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

func (c *Counter) Swap() (read, written int64)

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

func (c *Counter) Throughput() (readBps, writtenBps int64)

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

func (c *Counter) Total() (read, written int64)

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 NewGroup

func NewGroup(parent *Group) *Group

NewGroup returns a Group under parent, or a root for a nil parent.

func (*Group) Acquire

func (g *Group) Acquire() error

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

func (g *Group) AcquireContext(ctx context.Context) error

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) Conns

func (g *Group) Conns() int64

Conns returns the connection slots taken in g and its descendants.

func (*Group) Limiters

func (g *Group) Limiters() (read, write Limiter)

Limiters returns the Limiters of g's own level, as SetLimiters set them.

func (*Group) MaxConns

func (g *Group) MaxConns() int64

MaxConns returns g's cap on connections, or 0 for none.

func (*Group) Open

func (g *Group) Open(c net.Conn, opts ...Option) (*Conn, error)

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

func (g *Group) OpenStream(rwc io.ReadWriteCloser, opts ...Option) (*Stream, error)

OpenStream is Open for an io.ReadWriteCloser, wrapped as NewStream does.

func (*Group) Parent

func (g *Group) Parent() *Group

Parent returns g's parent, or nil for a root.

func (*Group) Reads

func (g *Group) Reads() Reserver

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

func (g *Group) SetLimiters(read, write Limiter)

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

func (g *Group) SetMaxConns(n int64)

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

func (g *Group) SetParent(p *Group) error

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

func (g *Group) SetTraffic(c *Counter) error

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.

func (*Group) Traffic

func (g *Group) Traffic() *Counter

Traffic returns the Counter of the bytes that the connections of g and its descendants read and wrote, and their throughput. A moved Group's bytes count where it was when they passed.

func (*Group) Writes

func (g *Group) Writes() Reserver

Writes returns the Limiter of the writes of g's connections, as Reads does for reads, counting the bytes written.

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.

func (*Meter) Total

func (m *Meter) Total() (read, written int64)

Total returns the bytes read and written so far.

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) Read

func (s NotifyConn) Read(b []byte) (int, error)

func (NotifyConn) ReadFrom

func (s NotifyConn) ReadFrom(r io.Reader) (int64, error)

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) Write

func (s NotifyConn) Write(b []byte) (int, error)

func (NotifyConn) WriteTo

func (s NotifyConn) WriteTo(w io.Writer) (int64, error)

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) Read

func (s NotifyStream) Read(b []byte) (int, error)

func (NotifyStream) ReadFrom

func (s NotifyStream) ReadFrom(r io.Reader) (int64, error)

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) Write

func (s NotifyStream) Write(b []byte) (int, error)

func (NotifyStream) WriteTo

func (s NotifyStream) WriteTo(w io.Writer) (int64, error)

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

func WithCounter(c *Counter) Option

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

func WithLimiter(l Limiter) Option

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

func WithLimiters(read, write Limiter) Option

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

func WithWait

func WithWait(ctx context.Context) Option

WithWait makes a Group's Open wait for a connection slot, as AcquireContext does, until ctx is done, instead of refusing it with a *TooManyConnsError.

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

func (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error)

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.

func (*PacketConn) WriteTo

func (c *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error)

WriteTo charges the datagram b and sends it whole to addr; with WithDrop, it drops one that would wait and reports it sent.

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

func NewRate(limitBps int64) *Rate

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

func (r *Rate) Acquire(ctx context.Context, minBytes, maxBytes int64) (int64, error)

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) Burst

func (r *Rate) Burst() time.Duration

Burst returns how much traffic r lets through at once after an idle period.

func (*Rate) Charge

func (r *Rate) Charge(n int64) error

Charge records n transferred bytes without waiting, as debt that the next Ready or Wait waits for. It returns nil.

func (*Rate) Clone

func (r *Rate) Clone() *Rate

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) Fair

func (r *Rate) Fair() bool

Fair reports whether SetFair turned fair scheduling on.

func (*Rate) Limit

func (r *Rate) Limit() int64

Limit returns the limit in bytes per second, or 0 if unlimited.

func (*Rate) Ready

func (r *Rate) Ready(ctx context.Context, n int64) (int64, error)

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

func (r *Rate) Refund(n int64)

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

func (r *Rate) Reset(limitBps int64)

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

func (r *Rate) SetBurst(d time.Duration)

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

func (r *Rate) SetFair(on bool)

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

func (r *Rate) SetLimit(limitBps int64)

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

func (r *Rate) TryAcquire(minBytes, maxBytes int64) (int64, error)

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

func (r *Rate) TryWait(n int64) error

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

func (r *Rate) Wait(ctx context.Context, n int64) error

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

func NewHierarchy(limiters ...Limiter) Reserver

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

func NewReader(r io.Reader, opts ...Option) *Stream

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

func NewWriter(w io.Writer, opts ...Option) *Stream

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) Read

func (s *Stream) Read(b []byte) (int, error)

func (*Stream) ReadFrom

func (s *Stream) ReadFrom(r io.Reader) (int64, error)

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) Write

func (s *Stream) Write(b []byte) (int, error)

func (*Stream) WriteTo

func (s *Stream) WriteTo(w io.Writer) (int64, error)

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 NewSwitch

func NewSwitch(l Limiter) *Switch

NewSwitch returns a Switch that passes charges on to l; a nil l limits nothing.

func (*Switch) Acquire

func (s *Switch) Acquire(ctx context.Context, minBytes, maxBytes int64) (int64, error)

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) Charge

func (s *Switch) Charge(n int64) error

Charge records n transferred bytes on the current Limiter.

func (*Switch) Limiter

func (s *Switch) Limiter() Limiter

Limiter returns the Limiter s passes charges on to.

func (*Switch) Ready

func (s *Switch) Ready(ctx context.Context, n int64) (int64, error)

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) Refund

func (s *Switch) Refund(n int64)

Refund gives back n bytes to the current Limiter.

func (*Switch) Set

func (s *Switch) Set(l Limiter)

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

func (s *Switch) TryAcquire(minBytes, maxBytes int64) (int64, error)

TryAcquire takes between minBytes and maxBytes bytes from the current Limiter, as its TryAcquire does.

func (*Switch) TryWait

func (s *Switch) TryWait(n int64) error

TryWait charges n bytes to the current Limiter if it lets them through without waiting, as its TryWait does.

func (*Switch) Wait

func (s *Switch) Wait(ctx context.Context, n int64) error

Wait charges n bytes to the current Limiter and waits for it; if Set replaces it meanwhile, the charge moves to the new one.

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.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL