Debian Codegraph @

crt/aws-c-mqtt/source/v5/rate_limiters.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <aws/mqtt/private/v5/rate_limiters.h>
7
8 #include <aws/common/clock.h>
9
10 static int s_rate_limit_time_fn(const struct aws_rate_limiter_token_bucket_options *options, uint64_t *current_time) {
11 if (options->clock_fn != NULL) {
12 return (*options->clock_fn)(current_time);
13 }
14
15 return aws_high_res_clock_get_ticks(current_time);
16 }
17
18 int aws_rate_limiter_token_bucket_init(
19 struct aws_rate_limiter_token_bucket *limiter,
20 const struct aws_rate_limiter_token_bucket_options *options) {
21 AWS_ZERO_STRUCT(*limiter);
22
23 if (options->tokens_per_second == 0 || options->maximum_token_count == 0) {
24 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
25 }
26
27 limiter->config = *options;
28
29 aws_rate_limiter_token_bucket_reset(limiter);
30
31 return AWS_OP_SUCCESS;
32 }
33
34 void aws_rate_limiter_token_bucket_reset(struct aws_rate_limiter_token_bucket *limiter) {
35
36 limiter->current_token_count =
37 aws_min_u64(limiter->config.initial_token_count, limiter->config.maximum_token_count);
38 limiter->fractional_nanos = 0;
39 limiter->fractional_nano_tokens = 0;
40
41 uint64_t now = 0;
42 AWS_FATAL_ASSERT(s_rate_limit_time_fn(&limiter->config, &now) == AWS_OP_SUCCESS);
43
44 limiter->last_service_time = now;
45 }
46
47 static void s_regenerate_tokens(struct aws_rate_limiter_token_bucket *limiter) {
48 uint64_t now = 0;
49 AWS_FATAL_ASSERT(s_rate_limit_time_fn(&limiter->config, &now) == AWS_OP_SUCCESS);
50
51 if (now <= limiter->last_service_time) {
52 return;
53 }
54
55 uint64_t nanos_elapsed = now - limiter->last_service_time;
56
57 /*
58 * We break the regeneration calculation into two distinct steps:
59 * (1) Perform regeneration based on whole seconds elapsed (nice and easy just multiply times the regen rate)
60 * (2) Perform regeneration based on the remaining fraction of a second elapsed
61 *
62 * We do this to minimize the chances of multiplication saturation before the divide necessary to normalize to
63 * nanos.
64 *
65 * In particular, by doing this, we won't see saturation unless a regeneration rate in the multi-billions is used
66 * or elapsed_seconds is in the billions. This is similar reasoning to what we do in aws_timestamp_convert_u64.
67 *
68 * Additionally, we use a (sub-second) fractional counter/accumulator (fractional_nanos, fractional_nano_tokens)
69 * in order to prevent error accumulation due to integer division rounding.
70 */
71
72 /* break elapsed time into seconds and remainder nanos */
73 uint64_t remainder_nanos = 0;
74 uint64_t elapsed_seconds =
75 aws_timestamp_convert(nanos_elapsed, AWS_TIMESTAMP_NANOS, AWS_TIMESTAMP_SECS, &remainder_nanos);
76
77 /* apply seconds-based regeneration */
78 uint64_t tokens_regenerated = aws_mul_u64_saturating(elapsed_seconds, limiter->config.tokens_per_second);
79
80 /* apply fractional remainder regeneration */
81 limiter->fractional_nanos += remainder_nanos;
82
83 /* fractional overflow check */
84 if (limiter->fractional_nanos < AWS_TIMESTAMP_NANOS) {
85 /*
86 * no overflow, just do the division to figure out how many tokens are represented by the updated
87 * fractional nanos
88 */
89 uint64_t new_fractional_tokens =
90 aws_mul_u64_saturating(limiter->fractional_nanos, limiter->config.tokens_per_second) / AWS_TIMESTAMP_NANOS;
91
92 /*
93 * update token count by how much fractional tokens changed
94 */
95 tokens_regenerated += new_fractional_tokens - limiter->fractional_nano_tokens;
96 limiter->fractional_nano_tokens = new_fractional_tokens;
97 } else {
98 /*
99 * overflow. In this case, update token count by the remaining tokens left to regenerate to make the
100 * original fractional nano amount equal to one second. This is the key part (a pseudo-reset) that lets us
101 * avoid error accumulation due to integer division rounding over time.
102 */
103 tokens_regenerated += limiter->config.tokens_per_second - limiter->fractional_nano_tokens;
104
105 /*
106 * subtract off a second from the fractional part. Guaranteed to be less than a second afterwards.
107 */
108 limiter->fractional_nanos -= AWS_TIMESTAMP_NANOS;
109
110 /*
111 * Calculate the new fractional nano token amount, and add them in.
112 */
113 limiter->fractional_nano_tokens =
114 aws_mul_u64_saturating(limiter->fractional_nanos, limiter->config.tokens_per_second) / AWS_TIMESTAMP_NANOS;
115 tokens_regenerated += limiter->fractional_nano_tokens;
116 }
117
118 limiter->current_token_count = aws_add_u64_saturating(tokens_regenerated, limiter->current_token_count);
119 if (limiter->current_token_count > limiter->config.maximum_token_count) {
120 limiter->current_token_count = limiter->config.maximum_token_count;
121 }
122
123 limiter->last_service_time = now;
124 }
125
126 bool aws_rate_limiter_token_bucket_can_take_tokens(
127 struct aws_rate_limiter_token_bucket *limiter,
128 uint64_t token_count) {
129 s_regenerate_tokens(limiter);
130
131 return limiter->current_token_count >= token_count;
132 }
133
134 int aws_rate_limiter_token_bucket_take_tokens(struct aws_rate_limiter_token_bucket *limiter, uint64_t token_count) {
135 s_regenerate_tokens(limiter);
136
137 if (limiter->current_token_count < token_count) {
138 /* TODO: correct error once seated in aws-c-common */
139 return aws_raise_error(AWS_ERROR_INVALID_STATE);
140 }
141
142 limiter->current_token_count -= token_count;
143 return AWS_OP_SUCCESS;
144 }
145
146 uint64_t aws_rate_limiter_token_bucket_compute_wait_for_tokens(
147 struct aws_rate_limiter_token_bucket *limiter,
148 uint64_t token_count) {
149 s_regenerate_tokens(limiter);
150
151 if (limiter->current_token_count >= token_count) {
152 return 0;
153 }
154
155 uint64_t token_rate = limiter->config.tokens_per_second;
156 AWS_FATAL_ASSERT(limiter->fractional_nanos < AWS_TIMESTAMP_NANOS);
157 AWS_FATAL_ASSERT(limiter->fractional_nano_tokens <= token_rate);
158
159 uint64_t expected_wait = 0;
160
161 uint64_t deficit = token_count - limiter->current_token_count;
162 uint64_t remaining_fractional_tokens = token_rate - limiter->fractional_nano_tokens;
163
164 if (deficit < remaining_fractional_tokens) {
165 /*
166 * case 1:
167 * The token deficit is less than what will be regenerated by waiting for the fractional nanos accumulator
168 * to reach one second's worth of time.
169 *
170 * In this case, base the calculation off of just a wait from fractional nanos.
171 */
172 uint64_t target_fractional_tokens = aws_add_u64_saturating(deficit, limiter->fractional_nano_tokens);
173 uint64_t remainder_wait_unnormalized = aws_mul_u64_saturating(target_fractional_tokens, AWS_TIMESTAMP_NANOS);
174
175 expected_wait = remainder_wait_unnormalized / token_rate - limiter->fractional_nanos;
176
177 /* If the fractional wait is itself, fractional, then add one more nano second to push us over the edge */
178 if (remainder_wait_unnormalized % token_rate) {
179 ++expected_wait;
180 }
181 } else {
182 /*
183 * case 2:
184 * The token deficit requires regeneration for a time interval at least as large as what is needed
185 * to overflow the fractional nanos accumulator.
186 */
187
188 /* First account for making the fractional nano accumulator exactly one second */
189 expected_wait = AWS_TIMESTAMP_NANOS - limiter->fractional_nanos;
190 deficit -= remaining_fractional_tokens;
191
192 /*
193 * Now, for the remaining tokens, split into tokens from whole seconds worth of regeneration as well
194 * as a remainder requiring a fractional regeneration
195 */
196 uint64_t expected_wait_seconds = deficit / token_rate;
197 uint64_t deficit_remainder = deficit % token_rate;
198
199 /*
200 * Account for seconds worth of waiting
201 */
202 expected_wait += aws_mul_u64_saturating(expected_wait_seconds, AWS_TIMESTAMP_NANOS);
203
204 /*
205 * And finally, calculate the fractional wait to give us the last few tokens
206 */
207 uint64_t remainder_wait_unnormalized = aws_mul_u64_saturating(deficit_remainder, AWS_TIMESTAMP_NANOS);
208 expected_wait += remainder_wait_unnormalized / token_rate;
209
210 /* If the fractional wait is itself, fractional, then add one more nano second to push us over the edge */
211 if (remainder_wait_unnormalized % token_rate) {
212 ++expected_wait;
213 }
214 }
215
216 return expected_wait;
217 }