计算限流时间(throttleTime)的逻辑:
O * W / (W + X) = T => X = (O - T)/T * W
O:实际速率(10M/s)
T:目标速率 (1M/s)
W:窗口时间 (10s)
X:延迟时间 (9s)
/*
- This calculates the amount of time needed to bring the metric within quota
- assuming that no new metrics are recorded.
- Basically, if O is the observed rate and T is the target rate over a window of W, to bring O down to T,
- we need to add a delay of X to W such that O * W / (W + X) = T.
- Solving for X, we get X = (O - T)/T * W.
*/
private def throttleTime(clientMetric: KafkaMetric, config: MetricConfig): Int = {
val rateMetric: Rate = measurableAsRate(clientMetric.metricName(), clientMetric.measurable())
val quota = config.quota()
val difference = clientMetric.value() - quota.bound
// Use the precise window used by the rate calculation
val throttleTimeMs = difference / quota.bound * rateMetric.windowSize(config, time.milliseconds())
throttleTimeMs.round.toInt
}