RateLimiter

class RateLimiter(scope: CoroutineScope, updateIntervalMs: Long = 250)

Session-wide upload/download rate limiting: the live driver for the pure BandwidthManager/BandwidthChannel port.

libtorrent gives session_impl one bandwidth_manager per direction plus a global bandwidth_channel pair, with per-torrent channels layered on top; a peer_connection asks for quota before moving payload and is parked in the manager's queue when the buckets are empty. This class is that wiring on coroutines: acquireUpload/acquireDownload suspend until the requested bytes are granted, and a periodic update (driven by start's ticker, or by a test directly) refills the buckets and releases parked waiters. This is the on_tickupdate_quotas cadence.

A channel whose limit is 0 is unlimited and never participates (libtorrent skips zero-throttle channels when assembling a request's channel list), so with no limits configured every acquire returns immediately.

Download limiting works by delaying the receive path after the bytes arrived (back-pressure: a reader that stops draining stalls the sender's TCP window), which is also how libtorrent's receive quota throttles a peer.

Constructors

Link copied to clipboard
constructor(scope: CoroutineScope, updateIntervalMs: Long = 250)

Types

Link copied to clipboard
object Companion

Properties

Link copied to clipboard

The session-global download token bucket (m_download_channel).

Link copied to clipboard

The session-global upload token bucket (m_upload_channel).

Functions

Link copied to clipboard
suspend fun acquireDownload(bytes: Int, torrent: TorrentBandwidth? = null)

Suspend until bytes of download quota are granted.

Link copied to clipboard
suspend fun acquireUpload(bytes: Int, torrent: TorrentBandwidth? = null)

Suspend until bytes of upload quota are granted.

Link copied to clipboard
fun close()

Stop granting and release every parked waiter with what it has (the bandwidth_manager::close semantics). Safe to call from non-suspending teardown; pending dispatch runs on scope.

Link copied to clipboard
Link copied to clipboard

A per-torrent channel pair to layer under the global limit (peer_class lite).

Link copied to clipboard
fun setDownloadLimit(bytesPerSecond: Int)

Cap session download at bytesPerSecond (0 = unlimited). download_rate_limit.

Link copied to clipboard
fun setUploadLimit(bytesPerSecond: Int)

Cap session upload at bytesPerSecond (0 = unlimited). upload_rate_limit.

Link copied to clipboard
fun start()

Start the periodic refill ticker. Idempotent.

Link copied to clipboard
suspend fun update(dtMilliseconds: Long)

One scheduling round: refill the buckets with dtMilliseconds worth of quota and dispatch satisfied waiters. Exposed for deterministic tests.

Link copied to clipboard