summaryrefslogtreecommitdiff
path: root/common/testutils/devicetests/com/android/testutils/async/RateLimiter.java
blob: d5cca0a4cd72e182de5134d8cb5891f25f57dc39 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.testutils.async;

import com.android.net.module.util.async.OsAccess;

import java.util.Arrays;

/**
 * Limits the number of bytes processed to the given maximum of bytes per second.
 *
 * The limiter tracks the total for the past second, along with sums for each 10ms
 * in the past second, allowing the total to be adjusted as the time passes.
 */
public final class RateLimiter {
    private static final int PERIOD_DURATION_MS = 1000;
    private static final int BUCKET_COUNT = 100;

    public static final int BUCKET_DURATION_MS = PERIOD_DURATION_MS / BUCKET_COUNT;

    private final OsAccess mOsAccess;
    private final int[] mStatBuckets = new int[BUCKET_COUNT];
    private int mMaxPerPeriodBytes;
    private int mMaxPerBucketBytes;
    private int mRecordedPeriodBytes;
    private long mLastLimitTimestamp;
    private int mLastRequestReduction;

    public RateLimiter(OsAccess osAccess, int bytesPerSecond) {
        mOsAccess = osAccess;
        setBytesPerSecond(bytesPerSecond);
        clear();
    }

    public int getBytesPerSecond() {
        return mMaxPerPeriodBytes;
    }

    public void setBytesPerSecond(int bytesPerSecond) {
        mMaxPerPeriodBytes = bytesPerSecond;
        mMaxPerBucketBytes = Math.max(1, (mMaxPerPeriodBytes / BUCKET_COUNT) * 2);
    }

    public void clear() {
        mLastLimitTimestamp = mOsAccess.monotonicTimeMillis();
        mRecordedPeriodBytes = 0;
        Arrays.fill(mStatBuckets, 0);
    }

    public static int limit(RateLimiter limiter1, RateLimiter limiter2, int requestedBytes) {
        final long now = limiter1.mOsAccess.monotonicTimeMillis();
        final int allowedCount = Math.min(limiter1.calculateLimit(now, requestedBytes),
            limiter2.calculateLimit(now, requestedBytes));
        limiter1.recordBytes(now, requestedBytes, allowedCount);
        limiter2.recordBytes(now, requestedBytes, allowedCount);
        return allowedCount;
    }

    public int limit(int requestedBytes) {
        final long now = mOsAccess.monotonicTimeMillis();
        final int allowedCount = calculateLimit(now, requestedBytes);
        recordBytes(now, requestedBytes, allowedCount);
        return allowedCount;
    }

    public int getLastRequestReduction() {
        return mLastRequestReduction;
    }

    public boolean acceptAllOrNone(int requestedBytes) {
        final long now = mOsAccess.monotonicTimeMillis();
        final int allowedCount = calculateLimit(now, requestedBytes);
        if (allowedCount < requestedBytes) {
            return false;
        }
        recordBytes(now, requestedBytes, allowedCount);
        return true;
    }

    private int calculateLimit(long now, int requestedBytes) {
        // First remove all stale bucket data and adjust the total.
        final long currentBucketAbsIdx = now / BUCKET_DURATION_MS;
        final long staleCutoffIdx = currentBucketAbsIdx - BUCKET_COUNT;
        for (long i = mLastLimitTimestamp / BUCKET_DURATION_MS; i < staleCutoffIdx; i++) {
            final int idx = (int) (i % BUCKET_COUNT);
            mRecordedPeriodBytes -= mStatBuckets[idx];
            mStatBuckets[idx] = 0;
        }

        final int bucketIdx = (int) (currentBucketAbsIdx % BUCKET_COUNT);
        final int maxAllowed = Math.min(mMaxPerPeriodBytes - mRecordedPeriodBytes,
            Math.min(mMaxPerBucketBytes - mStatBuckets[bucketIdx], requestedBytes));
        return Math.max(0, maxAllowed);
    }

    private void recordBytes(long now, int requestedBytes, int actualBytes) {
        mStatBuckets[(int) ((now / BUCKET_DURATION_MS) % BUCKET_COUNT)] += actualBytes;
        mRecordedPeriodBytes += actualBytes;
        mLastRequestReduction = requestedBytes - actualBytes;
        mLastLimitTimestamp = now;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{max=");
        sb.append(mMaxPerPeriodBytes);
        sb.append(",max_bucket=");
        sb.append(mMaxPerBucketBytes);
        sb.append(",total=");
        sb.append(mRecordedPeriodBytes);
        sb.append(",last_red=");
        sb.append(mLastRequestReduction);
        sb.append('}');
        return sb.toString();
    }
}