/
BucketStateIEEE754.java
360 lines (301 loc) · 14.1 KB
/
BucketStateIEEE754.java
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*-
* ========================LICENSE_START=================================
* Bucket4j
* %%
* Copyright (C) 2015 - 2020 Vladimir Bukhtoyarov
* %%
* 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.
* =========================LICENSE_END==================================
*/
package io.github.bucket4j;
import io.github.bucket4j.distributed.serialization.DeserializationAdapter;
import io.github.bucket4j.distributed.serialization.SerializationAdapter;
import io.github.bucket4j.distributed.serialization.SerializationHandle;
import io.github.bucket4j.distributed.versioning.Version;
import io.github.bucket4j.distributed.versioning.Versions;
import io.github.bucket4j.util.ComparableByContent;
import java.io.IOException;
import java.util.Arrays;
import static io.github.bucket4j.distributed.versioning.Versions.v_7_0_0;
public class BucketStateIEEE754 implements BucketState, ComparableByContent<BucketStateIEEE754> {
// holds the current amount of tokens per each bandwidth
double[] tokens;
// holds the last refill time per each bandwidth
long[] lastRefillTime;
BucketConfiguration configuration;
public static SerializationHandle<BucketStateIEEE754> SERIALIZATION_HANDLE = new SerializationHandle<BucketStateIEEE754>() {
@Override
public <S> BucketStateIEEE754 deserialize(DeserializationAdapter<S> adapter, S input, Version backwardCompatibilityVersion) throws IOException {
int formatNumber = adapter.readInt(input);
Versions.check(formatNumber, v_7_0_0, v_7_0_0);
double[] tokens = adapter.readDoubleArray(input);
long[] lastRefillTime = adapter.readLongArray(input);
return new BucketStateIEEE754(tokens, lastRefillTime);
}
@Override
public <O> void serialize(SerializationAdapter<O> adapter, O output, BucketStateIEEE754 state, Version backwardCompatibilityVersion) throws IOException {
adapter.writeInt(output, v_7_0_0.getNumber());
adapter.writeDoubleArray(output, state.tokens);
adapter.writeLongArray(output, state.lastRefillTime);
}
@Override
public int getTypeId() {
return 4;
}
@Override
public Class<BucketStateIEEE754> getSerializedType() {
return BucketStateIEEE754.class;
}
};
BucketStateIEEE754(double[] tokens, long[] lastRefillTime) {
this.tokens = tokens;
this.lastRefillTime = lastRefillTime;
}
public BucketStateIEEE754(BucketConfiguration configuration, long currentTimeNanos) {
this.configuration = configuration;
Bandwidth[] bandwidths = configuration.getBandwidths();
this.tokens = new double[bandwidths.length];
this.lastRefillTime = new long[bandwidths.length];
for(int i = 0; i < bandwidths.length; i++) {
tokens[i] = calculateInitialTokens(bandwidths[i], currentTimeNanos);
lastRefillTime[i] = calculateLastRefillTimeNanos(bandwidths[i], currentTimeNanos);
}
}
@Override
public BucketConfiguration getConfiguration() {
return configuration;
}
@Override
public void setConfiguration(BucketConfiguration configuration) {
this.configuration = configuration;
}
@Override
public BucketState replaceConfiguration(BucketConfiguration newConfiguration, TokensInheritanceStrategy tokensInheritanceStrategy, long currentTimeNanos) {
// TODO
throw new UnsupportedOperationException();
}
@Override
public void forceAddTokens(long tokensToAdd) {
// TODO
throw new UnsupportedOperationException();
}
@Override
public BucketStateIEEE754 copy() {
BucketStateIEEE754 copy = new BucketStateIEEE754(tokens.clone(), lastRefillTime.clone());
copy.setConfiguration(configuration);
return copy;
}
@Override
public void copyStateFrom(BucketState sourceState) {
BucketStateIEEE754 sourceStateIEEE754 = (BucketStateIEEE754) sourceState;
if (sourceStateIEEE754.configuration == configuration) {
System.arraycopy(sourceStateIEEE754.tokens, 0, tokens, 0, tokens.length);
System.arraycopy(sourceStateIEEE754.lastRefillTime, 0, lastRefillTime, 0, lastRefillTime.length);
} else {
this.configuration = sourceStateIEEE754.configuration;
this.lastRefillTime = sourceStateIEEE754.lastRefillTime.clone();
this.tokens = sourceStateIEEE754.tokens.clone();
}
}
@Override
public long getCurrentSize(int bandwidth) {
return (long) tokens[bandwidth];
}
@Override
public long getRoundingError(int bandwidth) {
// accumulated computational error is always zero for this type of state
return 0;
}
@Override
public MathType getMathType() {
return MathType.IEEE_754;
}
@Override
public long getAvailableTokens() {
long availableTokens = (long) tokens[0];
for (int i = 1; i < tokens.length; i++) {
availableTokens = Math.min(availableTokens, (long) tokens[i]);
}
return availableTokens;
}
@Override
public void consume(long toConsume) {
for (int i = 0; i < tokens.length; i++) {
tokens[i] -= toConsume;
}
}
@Override
public void addTokens(long tokensToAdd) {
Bandwidth[] bandwidths = configuration.getBandwidths();
for (int i = 0; i < bandwidths.length; i++) {
double currentSize = tokens[i];
double newSize = currentSize + tokensToAdd;
if (newSize >= bandwidths[i].getCapacity()) {
tokens[i] = bandwidths[i].getCapacity();
} else {
tokens[i] = newSize;
}
}
}
@Override
public void reset() {
Bandwidth[] bandwidths = configuration.getBandwidths();
for (int i = 0; i < bandwidths.length; i++) {
tokens[i] = bandwidths[i].getCapacity();
}
}
@Override
public void refillAllBandwidth(long currentTimeNanos) {
Bandwidth[] limits = configuration.getBandwidths();
for (int i = 0; i < limits.length; i++) {
refill(i, limits[i], currentTimeNanos);
}
}
private void refill(int bandwidthIndex, Bandwidth bandwidth, long currentTimeNanos) {
long previousRefillNanos = lastRefillTime[bandwidthIndex];
if (currentTimeNanos <= previousRefillNanos) {
return;
}
if (bandwidth.isRefillIntervally()) {
long incompleteIntervalCorrection = (currentTimeNanos - previousRefillNanos) % bandwidth.getRefillPeriodNanos();
currentTimeNanos -= incompleteIntervalCorrection;
}
if (currentTimeNanos <= previousRefillNanos) {
return;
} else {
lastRefillTime[bandwidthIndex] = currentTimeNanos;
}
final long capacity = bandwidth.getCapacity();
final long refillPeriodNanos = bandwidth.getRefillPeriodNanos();
final long refillTokens = bandwidth.getRefillTokens();
double newSize = tokens[bandwidthIndex];
long durationSinceLastRefillNanos = currentTimeNanos - previousRefillNanos;
if (durationSinceLastRefillNanos > refillPeriodNanos) {
long elapsedPeriods = durationSinceLastRefillNanos / refillPeriodNanos;
long calculatedRefill = elapsedPeriods * refillTokens;
newSize += calculatedRefill;
if (newSize > capacity) {
tokens[bandwidthIndex] = capacity;
return;
}
durationSinceLastRefillNanos %= refillPeriodNanos;
}
double calculatedRefill = (double) durationSinceLastRefillNanos / (double) refillPeriodNanos * (double) refillTokens;
newSize += calculatedRefill;
if (newSize >= capacity) {
newSize = capacity;
}
tokens[bandwidthIndex] = newSize;
}
@Override
public long calculateDelayNanosAfterWillBePossibleToConsume(long tokensToConsume, long currentTimeNanos, boolean checkTokensToConsumeShouldBeLessThenCapacity) {
Bandwidth[] bandwidths = configuration.getBandwidths();
long delayAfterWillBePossibleToConsume = calculateDelayNanosAfterWillBePossibleToConsumeForBandwidth(0, bandwidths[0], tokensToConsume, currentTimeNanos, checkTokensToConsumeShouldBeLessThenCapacity);
for (int i = 1; i < bandwidths.length; i++) {
Bandwidth bandwidth = bandwidths[i];
long delay = calculateDelayNanosAfterWillBePossibleToConsumeForBandwidth(i, bandwidth, tokensToConsume, currentTimeNanos, checkTokensToConsumeShouldBeLessThenCapacity);
delayAfterWillBePossibleToConsume = Math.max(delayAfterWillBePossibleToConsume, delay);
}
return delayAfterWillBePossibleToConsume;
}
@Override
public long calculateFullRefillingTime(long currentTimeNanos) {
Bandwidth[] bandwidths = configuration.getBandwidths();
long maxTimeToFullRefillNanos = calculateFullRefillingTime(0, bandwidths[0], currentTimeNanos);
for (int i = 1; i < bandwidths.length; i++) {
maxTimeToFullRefillNanos = Math.max(maxTimeToFullRefillNanos, calculateFullRefillingTime(i, bandwidths[i], currentTimeNanos));
}
return maxTimeToFullRefillNanos;
}
private long calculateFullRefillingTime(int bandwidthIndex, Bandwidth bandwidth, long currentTimeNanos) {
long availableTokens = getCurrentSize(bandwidthIndex);
if (availableTokens >= bandwidth.capacity) {
return 0L;
}
double deficit = bandwidth.capacity - availableTokens;
double nanosToWait;
if (bandwidth.isRefillIntervally()) {
nanosToWait = calculateDelayNanosAfterWillBePossibleToConsumeForIntervalBandwidth(bandwidthIndex, bandwidth, deficit, currentTimeNanos);
} else {
nanosToWait = calculateDelayNanosAfterWillBePossibleToConsumeForGreedyBandwidth(bandwidth, deficit);
}
return nanosToWait < Long.MAX_VALUE? (long) nanosToWait : Long.MAX_VALUE;
}
private long calculateDelayNanosAfterWillBePossibleToConsumeForBandwidth(int bandwidthIndex, Bandwidth bandwidth, long tokensToConsume, long currentTimeNanos, boolean checkTokensToConsumeShouldBeLessThenCapacity) {
if (checkTokensToConsumeShouldBeLessThenCapacity && tokensToConsume > bandwidth.capacity) {
return Long.MAX_VALUE;
}
double currentSize = tokens[bandwidthIndex];
if (tokensToConsume <= currentSize) {
return 0;
}
double deficit = tokensToConsume - currentSize;
double nanosToWait;
if (bandwidth.isRefillIntervally()) {
nanosToWait = calculateDelayNanosAfterWillBePossibleToConsumeForIntervalBandwidth(bandwidthIndex, bandwidth, deficit, currentTimeNanos);
} else {
nanosToWait = calculateDelayNanosAfterWillBePossibleToConsumeForGreedyBandwidth(bandwidth, deficit);
}
return nanosToWait < Long.MAX_VALUE? (long) nanosToWait : Long.MAX_VALUE;
}
private double calculateDelayNanosAfterWillBePossibleToConsumeForGreedyBandwidth(Bandwidth bandwidth, double deficit) {
return (double) bandwidth.getRefillPeriodNanos() * deficit /(double) bandwidth.getRefillTokens();
}
private double calculateDelayNanosAfterWillBePossibleToConsumeForIntervalBandwidth(int bandwidthIndex, Bandwidth bandwidth, double deficit, long currentTimeNanos) {
long refillPeriodNanos = bandwidth.getRefillPeriodNanos();
long refillTokens = bandwidth.getRefillTokens();
long previousRefillNanos = lastRefillTime[bandwidthIndex];
long timeOfNextRefillNanos = previousRefillNanos + refillPeriodNanos;
long waitForNextRefillNanos = timeOfNextRefillNanos - currentTimeNanos;
if (deficit <= refillTokens) {
return waitForNextRefillNanos;
}
deficit -= refillTokens;
double deficitPeriodsAsDouble = Math.ceil(deficit / refillTokens);
double deficitNanos = deficitPeriodsAsDouble * refillPeriodNanos;
return deficitNanos + waitForNextRefillNanos;
}
private long calculateLastRefillTimeNanos(Bandwidth bandwidth, long currentTimeNanos) {
if (!bandwidth.isIntervallyAligned()) {
return currentTimeNanos;
}
return bandwidth.timeOfFirstRefillMillis * 1_000_000 - bandwidth.refillPeriodNanos;
}
private long calculateInitialTokens(Bandwidth bandwidth, long currentTimeNanos) {
if (!bandwidth.useAdaptiveInitialTokens) {
return bandwidth.initialTokens;
}
long timeOfFirstRefillNanos = bandwidth.timeOfFirstRefillMillis * 1_000_000;
if (currentTimeNanos >= timeOfFirstRefillNanos) {
return bandwidth.initialTokens;
}
long guaranteedBase = Math.max(0, bandwidth.capacity - bandwidth.refillTokens);
long nanosBeforeFirstRefill = timeOfFirstRefillNanos - currentTimeNanos;
return Math.min(
bandwidth.capacity,
guaranteedBase + (long)((double)nanosBeforeFirstRefill * (double) bandwidth.refillTokens / (double) bandwidth.refillPeriodNanos));
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("BucketState{");
sb.append("tokens=").append(Arrays.toString(tokens));
sb.append(", lastRefillTime=").append(Arrays.toString(lastRefillTime));
sb.append('}');
return sb.toString();
}
@Override
public boolean equalsByContent(BucketStateIEEE754 other) {
return Arrays.equals(tokens, other.tokens) &&
Arrays.equals(lastRefillTime, other.lastRefillTime);
}
}