| 55 | private final List<TimestampedCost> timestamps = new ArrayList<>(); |
| 56 | |
| 57 | @SuppressWarnings("unchecked") |
| 58 | public Throttler(Object config) { |
| 59 | // Defaults |
| 60 | this.refillRate = 1.0; |
| 61 | this.delay = 0.001; |
| 62 | this.capacity = 1.0; |
| 63 | this.tokens = 0; |
| 64 | this.defaultCost = 1.0; |
| 65 | this.algorithm = "leakyBucket"; |
| 66 | this.windowSize = 60000.0; |
| 67 | this.maxWeight = 0.0; |
| 68 | |
| 69 | if (config instanceof Map) { |
| 70 | Map<String, Object> cfg = (Map<String, Object>) config; |
| 71 | if (cfg.containsKey("refillRate")) this.refillRate = toDouble(cfg.get("refillRate")); |
| 72 | if (cfg.containsKey("delay")) this.delay = toDouble(cfg.get("delay")); |
| 73 | if (cfg.containsKey("capacity")) this.capacity = toDouble(cfg.get("capacity")); |
| 74 | if (cfg.containsKey("tokens")) this.tokens = toDouble(cfg.get("tokens")); |
| 75 | if (cfg.containsKey("cost")) this.defaultCost = toDouble(cfg.get("cost")); |
| 76 | if (cfg.containsKey("algorithm")) this.algorithm = String.valueOf(cfg.get("algorithm")); |
| 77 | if (cfg.containsKey("windowSize")) this.windowSize = toDouble(cfg.get("windowSize")); |
| 78 | if (cfg.containsKey("rateLimit")) { |
| 79 | double rateLimit = toDouble(cfg.get("rateLimit")); |
| 80 | if (!"leakyBucket".equals(this.algorithm) && rateLimit > 0) { |
| 81 | this.maxWeight = this.windowSize / rateLimit; |
| 82 | } |
| 83 | } |
| 84 | if (cfg.containsKey("maxWeight") && cfg.get("maxWeight") != null) { |
| 85 | double mw = toDouble(cfg.get("maxWeight")); |
| 86 | if (mw > 0) this.maxWeight = mw; |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | /** |
| 92 | * Throttle with the given cost. Returns a CompletableFuture that completes |