From ab9d9f7c07b088463b992fb9419b8ff9ab510677 Mon Sep 17 00:00:00 2001 From: Neil Booth Date: Sat, 3 Dec 2016 22:57:14 +0900 Subject: [PATCH] Reduce bandwith usage over the bandwith interval So if e.g. your limit is 10MB per hour, then every minute your cumulative usage will be reduced by 1/6MB. --- lib/jsonrpc.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/jsonrpc.py b/lib/jsonrpc.py index f58cf6c..861b565 100644 --- a/lib/jsonrpc.py +++ b/lib/jsonrpc.py @@ -129,10 +129,12 @@ class JSONRPC(asyncio.Protocol, LoggedClass): def using_bandwidth(self, amount): now = time.time() - if now >= self.bandwidth_start + self.bandwidth_interval: - self.bandwidth_start = now - self.bandwidth_used = 0 - self.bandwidth_used += amount + # Reduce the recorded usage in proportion to the elapsed time + elapsed = now - self.bandwidth_start + self.bandwidth_start = now + refund = int(elapsed / self.bandwidth_interval * self.bandwidth_limit) + refund = min(refund, self.bandwidth_used) + self.bandwidth_used += amount - refund def data_received(self, data): '''Handle incoming data (synchronously).