BandwidthChannel

A single token bucket. This is a pure-Kotlin port of libtorrent's bandwidth_channel (aux_/bandwidth_limit.hpp, bandwidth_limit.cpp).

Each channel enforces one rate limit (bytes/second). A peer connection belongs to several at once (its own limit, its torrent's limit, the global limit, …) and the BandwidthManager hands it the minimum the most-constrained channel allows.

Token bucket

updateQuota is called every scheduling round with the elapsed milliseconds and pours limit * dt / 1000 fresh bytes into quotaLeft. The bucket is capped at three seconds' worth of limit so an idle channel cannot hoard unbounded burst. Consumers withdraw with useQuota and refund unused quota on disconnect with returnQuota.

A limit of 0 means infinite (unlimited). Such a channel always reports inf quota and ignores updateQuota, useQuota and returnQuota.

The fields tmp and distributeQuota are scratch space owned by the manager during a distribution round; see BandwidthManager.updateQuotas.

Constructors

Link copied to clipboard
constructor()

Types

Link copied to clipboard
object Companion

Properties

Link copied to clipboard

The number of bytes this channel offers for distribution this round.

Link copied to clipboard
var tmp: Int

Scratch accumulator the manager uses while distributing quota: the sum of the priorities of all requests competing for this channel in the current round.

Functions

Link copied to clipboard
fun needQueueing(amount: Int): Boolean

Fast path that lets a consumer skip the manager's queue: if more than one second of quota is already banked, amount is withdrawn directly and this returns false (no queueing needed). Otherwise nothing is withdrawn and it returns true. Faithful to bandwidth_channel::need_queueing.

Link copied to clipboard
fun quotaLeft(): Int

Bytes currently available, or inf when the channel is unlimited.

Link copied to clipboard
fun returnQuota(amount: Int)

Refunds amount bytes to the bucket. Call it when a consumer disconnects with quota it never spent. No-op on an unlimited channel. (return_quota)

Link copied to clipboard
fun throttle(): Int

The current rate limit in bytes/second; 0 means infinite.

fun throttle(value: Int)

Sets the rate limit to value bytes/second; 0 means infinite. Must be in 0 until inf: at or beyond inf the token-bucket arithmetic could overflow.

Link copied to clipboard
fun updateQuota(dtMilliseconds: Int)

Pours dtMilliseconds worth of fresh quota into the bucket, faithful to bandwidth_channel::update_quota:

Link copied to clipboard
fun useQuota(amount: Int)

Withdraws amount bytes from the bucket. No-op on an unlimited channel. (use_quota)