include/sa/sa_rate.h

filter: Statementstmt 90.4% 133 / 147 Branchbran 60.7% 85 / 140 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 75.9% 218 / 287 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« include/sa/sa_hist.h ↑ Summary include/sa/sa_hash.h »
1 #ifndef SA_RATE_H
2 #define SA_RATE_H
3  
4 /* sa_rate.h - a token bucket per key, shared by every process. Perl-free.
5 *
6 * ---- the problem this exists for --------------------------------------------
7 *
8 * A limit of 100/min enforced in a pre-forked pool is not a limit of 100/min.
9 * Each worker keeps its own counter, so the real limit is workers x 100/min,
10 * and the number moves when the pool is resized. The sibling implementation in
11 * Hyperman says the same thing in its own words, and the dist before that put
12 * the counters in a FILE to escape it - which buys correctness back at the
13 * price of a syscall on every request.
14 *
15 * The state belongs in memory every worker already shares. That is this.
16 *
17 * ---- a token bucket, not a fixed window -------------------------------------
18 *
19 * A fixed window is the obvious implementation and it has a hole in it: the
20 * window boundary. A caller limited to 100 per minute can spend 100 at 11:59:59
21 * and 100 more at 12:00:00, which is 200 requests in one second and is exactly
22 * what the limit was written to prevent. The bug is invisible in testing
23 * because it needs the clock to be in a particular place.
24 *
25 * A bucket has no boundary to stand on. It holds up to `limit` tokens, refills
26 * continuously at `limit` per `window`, and a request takes one. Sustained rate
27 * and burst size become two numbers a caller can set independently, which is
28 * what a caller actually wants: 100/min with a burst of 100 is a different
29 * policy from 100/min with a burst of 10, and a window cannot express either.
30 *
31 * ---- the whole bucket is ONE WORD, and that is the design -------------------
32 *
33 * Tokens and the moment they were last refilled are packed into one uint64:
34 *
35 * bits 63..32 tokens, in units of 1/1024 of a token
36 * bits 31..0 when they were counted, in milliseconds
37 *
38 * So a hit is a compare-and-swap, and the limiter needs no lock on its hot
39 * path at all. That matters for more than speed. Hyperman's takes a striped
40 * spinlock per hit and FAILS OPEN when the spin is exhausted - which means
41 * that under exactly the load a rate limiter exists for, it quietly stops
42 * limiting. This cannot do that: a CAS either wins or is retried, and the
43 * retries are counted rather than being a silent hole.
44 *
45 * It is also why a crash cannot corrupt it. A process that dies mid-update has
46 * either landed its CAS or not; there is no half-written bucket to find,
47 * nothing to repair, and no need for the peer table that the ring depends on.
48 * Of every structure in this dist, this is the one whose crash story is "there
49 * is nothing to say".
50 *
51 * THE TIMESTAMP WRAPS, deliberately. Thirty-two bits of milliseconds is 49.7
52 * days, and the elapsed time is a SIGNED difference, which is correct across a
53 * wrap for any interval up to half of that. A key idle for longer than 24.9
54 * days measures short and so refills slower than it should, once, for one hit.
55 * That is the direction to be wrong in, and the alternative is a wider field
56 * that makes every bucket bigger to fix a case that ends in one extra allowed
57 * request.
58 *
59 * Signed, not unsigned, because a caller's clock reading can be BEHIND the
60 * timestamp another process already stored, and unsigned subtraction reads
61 * that as forty-nine days of refill. See sa_rate_refill.
62 *
63 * ---- when the table is full --------------------------------------------------
64 *
65 * Open addressing, and no free list - the arena has no free anywhere and this
66 * is not the structure to invent one in. A slot is reclaimable when its bucket
67 * is FULL, because a full bucket is indistinguishable from a key that has never
68 * been seen: both allow the next `limit` requests. So an idle key's slot is
69 * handed to a new key with nothing lost, and the table drains itself with no
70 * sweep and no timer.
71 *
72 * When every slot holds a bucket that is NOT full - the table is genuinely
73 * over capacity - a new key takes over its home slot, which resets a live
74 * bucket. THAT LEAKS LOOSER, NEVER TIGHTER: the victim gets more requests than
75 * it should, never fewer, so an over-full table cannot turn into an outage.
76 * Size the table above the peak count of distinct keys in a window, and read
77 * `evicted` to find out whether you did.
78 *
79 * Needs sa_arena.h.
80 */
81  
82 #include "sa/sa_arena.h"
83  
84 #define SA_RATE_MAGIC 0x45544152u /* 'R','A','T','E' little-endian */
85  
86 /* Tokens are integers in units of 1/1024, so a refill of a fraction of a token
87 * is not lost to truncation. A limiter of 100/min refills 1.7 tokens a second,
88 * which as an integer count of tokens per millisecond is zero. */
89 #define SA_RATE_SCALE 1024u
90  
91 /* A hit is a CAS loop. This bounds it, for the same reason every wait in this
92 * dist is bounded - but reaching it is not "fail open and say nothing", it is
93 * counted in `contended`, because a limiter that has stopped limiting is
94 * something an operator has to be able to discover. */
95 #define SA_RATE_CAS_TRIES 64
96  
97 /* How far an insert probes before it gives up and takes the home slot. */
98 #define SA_RATE_PROBE 16
99  
100 typedef struct {
101 volatile uint64_t keyhash; /* 0 = empty */
102 volatile uint64_t state; /* (tokens_u << 32) | last_ms */
103 } sa_rate_slot;
104  
105 typedef struct {
106 volatile uint32_t magic; /* published LAST at init */
107 uint32_t pad;
108 uint64_t nslots; /* a power of two */
109 uint64_t slots_off; /* from the LIMITER's base */
110 uint64_t burst_u; /* the full bucket, in 1/1024 tokens */
111 uint64_t window_ms; /* time to refill from empty to full */
112 volatile uint64_t allowed;
113 volatile uint64_t denied;
114 volatile uint64_t evicted; /* live buckets taken over: the table is small */
115 volatile uint64_t contended; /* CAS loops that gave up and allowed */
116 volatile unsigned char locks[SA_LOCK_STRIPES];
117 } sa_rate_hdr;
118  
119 #ifndef SA_RATE_FWD
120 #define SA_RATE_FWD
121 typedef struct sa_rate sa_rate;
122 #endif
123  
124 struct sa_rate {
125 sa_region *arena;
126 sa_rate_hdr *hdr;
127 sa_rate_slot *slots;
128 uint64_t nslots;
129 uint64_t mask;
130 uint64_t burst_u;
131 uint64_t window_ms;
132 };
133  
134 #define SA_RATE_TOKENS(st) ((uint64_t)((st) >> 32))
135 #define SA_RATE_WHEN(st) ((uint32_t)((st) & 0xFFFFFFFFu))
136 #define SA_RATE_STATE(t, ms) \
137 ((((uint64_t)(t)) << 32) | (uint64_t)(uint32_t)(ms))
138  
139 109 static uint64_t sa_rate_bytes(uint64_t nslots) {
140 109 return sa_align_up((uint64_t)sizeof(sa_rate_hdr))
141 109 + nslots * (uint64_t)sizeof(sa_rate_slot);
142 }
143  
144 /* Round up to a power of two, so the slot index is a mask rather than a
145 * division on the hot path. */
146 37 static uint64_t sa_rate_pow2(uint64_t n) {
147 37 uint64_t p = 64;
148 37 ▶ if (n < 64) return 64;
Branch: 1 branch
BranchTrueFalseTotal
if (n < 64) return 64; 0 37 37
149 49 ▶ while (p < n && p < (uint64_t)1 << 40) p <<= 1;
Branch: 2 branches
BranchTrueFalseTotal
while (p < n && p < (uint64_t)1 << 40) p <<= 1; 12 37 49
while (p < n && p < (uint64_t)1 << 40) p <<= 1; 12 0 12
150 37 return p;
151 }
152  
153 /* Milliseconds, in the same 32-bit space the slots store. */
154 8586 static uint32_t sa_rate_now_ms(void) {
155 8586 return (uint32_t)(sa_now_us() / 1000u);
156 }
157  
158 37 static sa_rate *sa_rate_bind(sa_region *arena, sa_reg *e, uint64_t nslots,
159 uint64_t burst_u, uint64_t window_ms, int *err)
160 {
161 #if !SA_HAVE_ATOMICS
162 (void)arena; (void)e; (void)nslots; (void)burst_u; (void)window_ms;
163 if (err) *err = SA_E_NOATOMICS;
164 return NULL;
165 #else
166 sa_rate *r;
167 sa_rate_hdr *h;
168 uint64_t hash;
169  
170 37 ▶ if (err) *err = SA_E_OK;
Branch: 1 branch
BranchTrueFalseTotal
if (err) *err = SA_E_OK; 37 0 37
171 37 ▶ if (!arena || !e) { if (err) *err = SA_E_NOENT; return NULL; }
Branch: 3 branches
BranchTrueFalseTotal
if (!arena || !e) { if (err) *err = SA_E_NOENT; return NULL; } 37 0 37
if (!arena || !e) { if (err) *err = SA_E_NOENT; return NULL; } 0 37 37
if (!arena || !e) { if (err) *err = SA_E_NOENT; return NULL; } 0 0 0
172  
173 37 h = (sa_rate_hdr *)sa_ptr_len(arena, e->off, sizeof(sa_rate_hdr));
174 37 ▶ if (!h) { if (err) *err = SA_E_NOENT; return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (!h) { if (err) *err = SA_E_NOENT; return NULL; } 0 37 37
if (!h) { if (err) *err = SA_E_NOENT; return NULL; } 0 0 0
175  
176 37 ▶ if (sa_at_load32_acq(&h->magic) != SA_RATE_MAGIC) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa_at_load32_acq(&h->magic) != SA_RATE_MAGIC) { 36 1 37
177 36 hash = sa_at_fnv(e->name, strlen(e->name));
178 36 ▶ if (sa_at_lock(h->locks, hash)) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa_at_lock(h->locks, hash)) { 36 0 36
179 36 ▶ if (sa_at_load32_acq(&h->magic) != SA_RATE_MAGIC) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa_at_load32_acq(&h->magic) != SA_RATE_MAGIC) { 36 0 36
180 36 ▶ if (!nslots || !burst_u || !window_ms
Branch: 3 branches
BranchTrueFalseTotal
if (!nslots || !burst_u || !window_ms 36 0 36
if (!nslots || !burst_u || !window_ms 36 0 36
if (!nslots || !burst_u || !window_ms 36 0 36
181 36 ▶ || sa_rate_bytes(nslots) > e->len) {
Branch: 1 branch
BranchTrueFalseTotal
|| sa_rate_bytes(nslots) > e->len) { 0 36 36
182 0 sa_at_unlock(h->locks, hash);
183 0 ▶ if (err) *err = SA_E_FULL;
Branch: 1 branch
BranchTrueFalseTotal
if (err) *err = SA_E_FULL; 0 0 0
184 0 return NULL;
185 }
186 36 memset((void *)h, 0, (size_t)sa_rate_bytes(nslots));
187 36 h->nslots = nslots;
188 36 h->slots_off = sa_align_up((uint64_t)sizeof(sa_rate_hdr));
189 36 h->burst_u = burst_u;
190 36 h->window_ms = window_ms;
191 36 sa_at_store32_rel(&h->magic, SA_RATE_MAGIC);
192 }
193 36 sa_at_unlock(h->locks, hash);
194 }
195 36 ▶ if (!sa_wait_magic32(&h->magic, SA_RATE_MAGIC)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!sa_wait_magic32(&h->magic, SA_RATE_MAGIC)) { 0 36 36
196 0 ▶ if (err) *err = SA_E_MAGIC;
Branch: 1 branch
BranchTrueFalseTotal
if (err) *err = SA_E_MAGIC; 0 0 0
197 0 return NULL;
198 }
199 }
200  
201 /* A caller asking for a policy the limiter does not have would be counting
202 * against somebody else's numbers. Say no, as every other tenant does. */
203 37 ▶ if ((nslots && h->nslots != nslots)
Branch: 2 branches
BranchTrueFalseTotal
if ((nslots && h->nslots != nslots) 37 0 37
if ((nslots && h->nslots != nslots) 37 0 37
204 37 ▶ || (burst_u && h->burst_u != burst_u)
Branch: 2 branches
BranchTrueFalseTotal
|| (burst_u && h->burst_u != burst_u) 37 0 37
|| (burst_u && h->burst_u != burst_u) 36 1 37
205 36 ▶ || (window_ms && h->window_ms != window_ms)) {
Branch: 2 branches
BranchTrueFalseTotal
|| (window_ms && h->window_ms != window_ms)) { 36 0 36
|| (window_ms && h->window_ms != window_ms)) { 0 36 36
206 1 ▶ if (err) *err = SA_E_SHAPE;
Branch: 1 branch
BranchTrueFalseTotal
if (err) *err = SA_E_SHAPE; 1 0 1
207 1 return NULL;
208 }
209  
210 36 r = (sa_rate *)calloc(1, sizeof(sa_rate));
211 36 ▶ if (!r) { if (err) *err = SA_E_NOMEM; return NULL; }
Branch: 2 branches
BranchTrueFalseTotal
if (!r) { if (err) *err = SA_E_NOMEM; return NULL; } 0 36 36
if (!r) { if (err) *err = SA_E_NOMEM; return NULL; } 0 0 0
212 36 r->arena = arena;
213 36 r->hdr = h;
214 36 r->slots = (sa_rate_slot *)((char *)h + (size_t)h->slots_off);
215 36 r->nslots = h->nslots;
216 36 r->mask = h->nslots - 1;
217 36 r->burst_u = h->burst_u;
218 36 r->window_ms = h->window_ms;
219 36 return r;
220 #endif
221 }
222  
223 36 static void sa_rate_free(sa_rate *r) { free(r); }
224  
225 #if SA_HAVE_ATOMICS
226  
227 /* What the bucket holds NOW, given what it held when it was last touched.
228 *
229 * ELAPSED IS SIGNED, AND THAT IS THE WHOLE OF IT.
230 *
231 * A caller reads the clock once and then races for the slot. In between,
232 * another process can write a timestamp LATER than the one this caller is
233 * holding, so `now` is behind what the slot says. Unsigned subtraction turns
234 * that one millisecond into 4,294,967,295 of them, which clears any window, so
235 * the bucket comes back FULL and the limiter has stopped limiting.
236 *
237 * That is not a corner case. Measured with three processes on one key: 88
238 * backwards readings in 1.5M calls, and 88 refills to full, which is 88 million
239 * tokens handed to a bucket that holds one million. Every request was allowed
240 * and `denied` was zero.
241 *
242 * The difference is taken as int32_t instead, which is serial-number
243 * arithmetic: a reading slightly behind is a small negative and means no time
244 * has passed for this caller, while a genuine forward interval stays correct
245 * across the field's wrap. The cost is that the longest measurable idle drops
246 * from 49.7 days to 24.9, and beyond that a key measures short and refills
247 * slower than it should for one hit. That is the direction to be wrong in. */
248 39903 static uint64_t sa_rate_refill(const sa_rate *r, uint64_t state, uint32_t now) {
249 39903 uint64_t tokens = SA_RATE_TOKENS(state);
250 39903 int32_t ahead = (int32_t)(now - SA_RATE_WHEN(state));
251 uint32_t elapsed;
252  
253 39903 ▶ if (tokens >= r->burst_u) return r->burst_u;
Branch: 1 branch
BranchTrueFalseTotal
if (tokens >= r->burst_u) return r->burst_u; 2042 37861 39903
254 37861 ▶ if (ahead <= 0) return tokens;
Branch: 1 branch
BranchTrueFalseTotal
if (ahead <= 0) return tokens; 35398 2463 37861
255 2463 elapsed = (uint32_t)ahead;
256 /* Clamped before the multiply, not after: a key idle for a month would
257 * otherwise overflow the intermediate on its way to an answer that is
258 * simply "full". */
259 2463 ▶ if ((uint64_t)elapsed >= r->window_ms) return r->burst_u;
Branch: 1 branch
BranchTrueFalseTotal
if ((uint64_t)elapsed >= r->window_ms) return r->burst_u; 11 2452 2463
260 2452 tokens += ((uint64_t)elapsed * r->burst_u) / r->window_ms;
261 2452 return tokens > r->burst_u ? r->burst_u : tokens;
262 }
263  
264 /* The timestamp to store beside a token count.
265 *
266 * Never the caller's own reading when the slot already holds a later one:
267 * writing a stale `now` drags the bucket's clock backwards, throwing away time
268 * a competing process had already accounted for and making the next caller
269 * more likely to read backwards in turn. Keep whichever is further ahead. */
270 8495 static uint32_t sa_rate_stamp(uint64_t state, uint32_t now) {
271 8495 uint32_t when = SA_RATE_WHEN(state);
272 8495 ▶ return ((int32_t)(now - when) > 0) ? now : when;
Branch: 1 branch
BranchTrueFalseTotal
return ((int32_t)(now - when) > 0) ? now : when; 22 8473 8495
273 }
274  
275 /* The slot this key lives in, claiming or reclaiming one if it has none.
276 * Returns the index, or the home slot when the table is full of live buckets.
277 * `*took_over` is set when a bucket that was NOT full had to be evicted. */
278 8586 static uint64_t sa_rate_slot_for(sa_rate *r, uint64_t h, uint32_t now,
279 int *took_over)
280 {
281 8586 uint64_t home = h & r->mask;
282 uint64_t i;
283  
284 8586 ▶ if (took_over) *took_over = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (took_over) *took_over = 0; 8577 9 8586
285  
286 39912 ▶ for (i = 0; i < SA_RATE_PROBE; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < SA_RATE_PROBE; i++) { 37975 1937 39912
287 37975 uint64_t idx = (home + i) & r->mask;
288 37975 sa_rate_slot *s = &r->slots[idx];
289 37975 uint64_t have = sa_at_load64_acq(&s->keyhash);
290  
291 37975 ▶ if (have == h) return idx;
Branch: 1 branch
BranchTrueFalseTotal
if (have == h) return idx; 6547 31428 37975
292 31428 ▶ if (!have) {
Branch: 1 branch
BranchTrueFalseTotal
if (!have) { 102 31326 31428
293 /* An empty slot. Losing the race for it is not a problem: the
294 * winner is either us or somebody whose key we then probe past. */
295 102 ▶ if (sa_at_cas64(&s->keyhash, 0, h)) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa_at_cas64(&s->keyhash, 0, h)) { 102 0 102
296 102 sa_at_store64_rel(&s->state, SA_RATE_STATE(r->burst_u, now));
297 102 return idx;
298 }
299 0 ▶ if (sa_at_load64_acq(&s->keyhash) == h) return idx;
Branch: 1 branch
BranchTrueFalseTotal
if (sa_at_load64_acq(&s->keyhash) == h) return idx; 0 0 0
300 0 continue;
301 }
302 /* Somebody else's key. A FULL bucket is indistinguishable from a key
303 * that has never been seen, so taking it over loses nothing. */
304 31326 ▶ if (sa_rate_refill(r, sa_at_load64_acq(&s->state), now) >= r->burst_u) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa_rate_refill(r, sa_at_load64_acq(&s->state), now) >= r->burst_u) { 0 31326 31326
305 0 ▶ if (sa_at_cas64(&s->keyhash, have, h)) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa_at_cas64(&s->keyhash, have, h)) { 0 0 0
306 0 sa_at_store64_rel(&s->state, SA_RATE_STATE(r->burst_u, now));
307 0 return idx;
308 }
309 0 ▶ if (sa_at_load64_acq(&s->keyhash) == h) return idx;
Branch: 1 branch
BranchTrueFalseTotal
if (sa_at_load64_acq(&s->keyhash) == h) return idx; 0 0 0
310 }
311 }
312  
313 /* Every slot in reach holds a bucket somebody is still spending from. Take
314 * the home slot, which resets ONE live bucket: the victim gets more
315 * requests than it should, never fewer, so a table that is too small
316 * cannot turn into an outage. */
317 {
318 1937 sa_rate_slot *s = &r->slots[home];
319 1937 uint64_t have = sa_at_load64_acq(&s->keyhash);
320 1937 ▶ if (have != h) {
Branch: 1 branch
BranchTrueFalseTotal
if (have != h) { 1937 0 1937
321 1937 ▶ if (sa_at_cas64(&s->keyhash, have, h)) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa_at_cas64(&s->keyhash, have, h)) { 1937 0 1937
322 1937 sa_at_store64_rel(&s->state, SA_RATE_STATE(r->burst_u, now));
323 1937 ▶ if (took_over) *took_over = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (took_over) *took_over = 1; 1937 0 1937
324 }
325 }
326 }
327 1937 return home;
328 }
329  
330 /* Take `cost_u` from the key's bucket.
331 *
332 * Returns 1 when the request is allowed, 0 when it is not. `*left_u` is what
333 * remains afterwards and `*retry_ms` how long until the bucket holds enough,
334 * both filled whether the answer was yes or no, because the caller wants them
335 * for its headers either way.
336 *
337 * `peek` takes nothing and only reports, for a caller that wants to show a
338 * budget without spending one. */
339 8577 static int sa_rate_take(sa_rate *r, const char *key, uint32_t klen,
340 uint64_t cost_u, int peek,
341 uint64_t *left_u, uint64_t *retry_ms)
342 {
343 uint64_t h, idx, state, tokens;
344 uint32_t now;
345 sa_rate_slot *s;
346 8577 int took_over = 0, tries;
347  
348 8577 ▶ if (left_u) *left_u = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (left_u) *left_u = 0; 79 8498 8577
349 8577 ▶ if (retry_ms) *retry_ms = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (retry_ms) *retry_ms = 0; 24 8553 8577
350 8577 ▶ if (!r) return 1; /* no limiter: allowed */
Branch: 1 branch
BranchTrueFalseTotal
if (!r) return 1; /* no limiter: allowed */ 0 8577 8577
351  
352 8577 now = sa_rate_now_ms();
353 8577 h = sa_at_fnv(key, (size_t)klen);
354 8577 ▶ if (!h) h = 1; /* 0 marks an empty slot */
Branch: 1 branch
BranchTrueFalseTotal
if (!h) h = 1; /* 0 marks an empty slot */ 0 8577 8577
355  
356 8577 idx = sa_rate_slot_for(r, h, now, &took_over);
357 8577 ▶ if (took_over) sa_at_fetch_add64(&r->hdr->evicted, 1);
Branch: 1 branch
BranchTrueFalseTotal
if (took_over) sa_at_fetch_add64(&r->hdr->evicted, 1); 1937 6640 8577
358 8577 s = &r->slots[idx];
359  
360 8577 ▶ for (tries = 0; tries < SA_RATE_CAS_TRIES; tries++) {
Branch: 1 branch
BranchTrueFalseTotal
for (tries = 0; tries < SA_RATE_CAS_TRIES; tries++) { 8577 0 8577
361 8577 state = sa_at_load64_acq(&s->state);
362 8577 tokens = sa_rate_refill(r, state, now);
363  
364 8577 ▶ if (tokens < cost_u) {
Branch: 1 branch
BranchTrueFalseTotal
if (tokens < cost_u) { 2149 6428 8577
365 /* Denied. The refill is written back so the timestamp advances and
366 * the next caller does not recompute the same elapsed window from
367 * scratch; losing that CAS costs nothing, because whoever won
368 * wrote the same answer.
369 *
370 * NOT WHEN PEEKING. `remaining` is asked from a status page and
371 * from a header, and a read that writes is a read two processes
372 * can contend on for nothing. */
373 2149 ▶ if (!peek)
Branch: 1 branch
BranchTrueFalseTotal
if (!peek) 2131 18 2149
374 2131 (void)sa_at_cas64(&s->state, state,
375 2131 SA_RATE_STATE(tokens, sa_rate_stamp(state, now)));
376 2149 ▶ if (left_u) *left_u = tokens;
Branch: 1 branch
BranchTrueFalseTotal
if (left_u) *left_u = tokens; 12 2137 2149
377 2149 ▶ if (retry_ms && r->burst_u)
Branch: 2 branches
BranchTrueFalseTotal
if (retry_ms && r->burst_u) 10 2139 2149
if (retry_ms && r->burst_u) 10 0 10
378 10 *retry_ms = ((cost_u - tokens) * r->window_ms + r->burst_u - 1)
379 10 / r->burst_u;
380 2149 ▶ if (!peek) sa_at_fetch_add64(&r->hdr->denied, 1);
Branch: 1 branch
BranchTrueFalseTotal
if (!peek) sa_at_fetch_add64(&r->hdr->denied, 1); 2131 18 2149
381 2149 return 0;
382 }
383  
384 6428 ▶ if (peek) {
Branch: 1 branch
BranchTrueFalseTotal
if (peek) { 64 6364 6428
385 64 ▶ if (left_u) *left_u = tokens;
Branch: 1 branch
BranchTrueFalseTotal
if (left_u) *left_u = tokens; 59 5 64
386 64 return 1;
387 }
388 6364 ▶ if (sa_at_cas64(&s->state, state,
Branch: 1 branch
BranchTrueFalseTotal
if (sa_at_cas64(&s->state, state, 6364 0 6364
389 6364 SA_RATE_STATE(tokens - cost_u, sa_rate_stamp(state, now)))) {
390 6364 ▶ if (left_u) *left_u = tokens - cost_u;
Branch: 1 branch
BranchTrueFalseTotal
if (left_u) *left_u = tokens - cost_u; 8 6356 6364
391 6364 sa_at_fetch_add64(&r->hdr->allowed, 1);
392 6364 return 1;
393 }
394 /* Somebody else spent from this bucket first. Read it again. */
395 }
396  
397 /* FAILS OPEN, AND SAYS SO. Under contention this heavy the honest answer
398 * is that the limiter did not get to decide, and an operator needs to know
399 * that rather than reading a clean `denied` count and believing it. */
400 0 sa_at_fetch_add64(&r->hdr->contended, 1);
401 0 ▶ if (left_u) *left_u = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (left_u) *left_u = 0; 0 0 0
402 0 return 1;
403 }
404  
405 /* Refill one key to full, for an operator lifting a limit by hand. */
406 2 static void sa_rate_reset_key(sa_rate *r, const char *key, uint32_t klen) {
407 uint64_t h, idx;
408 uint32_t now;
409 2 ▶ if (!r) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!r) return; 0 2 2
410 2 now = sa_rate_now_ms();
411 2 h = sa_at_fnv(key, (size_t)klen);
412 2 ▶ if (!h) h = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (!h) h = 1; 0 2 2
413 2 idx = sa_rate_slot_for(r, h, now, NULL);
414 2 sa_at_store64_rel(&r->slots[idx].state, SA_RATE_STATE(r->burst_u, now));
415 }
416  
417 /* Give the key's slot back, so the table has room for somebody else. */
418 2 static void sa_rate_forget(sa_rate *r, const char *key, uint32_t klen) {
419 uint64_t h, home, i;
420 2 ▶ if (!r) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!r) return; 0 2 2
421 2 h = sa_at_fnv(key, (size_t)klen);
422 2 ▶ if (!h) h = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (!h) h = 1; 0 2 2
423 2 home = h & r->mask;
424 2 ▶ for (i = 0; i < SA_RATE_PROBE; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < SA_RATE_PROBE; i++) { 2 0 2
425 2 uint64_t idx = (home + i) & r->mask;
426 2 ▶ if (sa_at_load64_acq(&r->slots[idx].keyhash) == h) {
Branch: 1 branch
BranchTrueFalseTotal
if (sa_at_load64_acq(&r->slots[idx].keyhash) == h) { 2 0 2
427 2 sa_at_store64_rel(&r->slots[idx].state, 0);
428 2 sa_at_store64_rel(&r->slots[idx].keyhash, 0);
429 2 return;
430 }
431 }
432 }
433  
434 /* How many slots hold a key. Walks the table, so this is for a status page. */
435 5 static uint64_t sa_rate_used(sa_rate *r) {
436 5 uint64_t i, n = 0;
437 5 ▶ if (!r) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!r) return 0; 0 5 5
438 709 ▶ for (i = 0; i < r->nslots; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < r->nslots; i++) 704 5 709
439 704 ▶ if (sa_at_load64_acq(&r->slots[i].keyhash)) n++;
Branch: 1 branch
BranchTrueFalseTotal
if (sa_at_load64_acq(&r->slots[i].keyhash)) n++; 69 635 704
440 5 return n;
441 }
442  
443 #else /* !SA_HAVE_ATOMICS */
444  
445 /* No atomics, so no limiter: sa_rate_bind refuses. These FAIL OPEN, as the
446 * XSUBs do in that build and as a NULL limiter does everywhere: a limiter must
447 * never be the reason a good request is refused. */
448 static int sa_rate_take(sa_rate *r, const char *key, uint32_t klen,
449 uint64_t cost_u, int peek,
450 uint64_t *left_u, uint64_t *retry_ms)
451 {
452 (void)r; (void)key; (void)klen; (void)cost_u; (void)peek;
453 if (left_u) *left_u = 0;
454 if (retry_ms) *retry_ms = 0;
455 return 1;
456 }
457  
458 static void sa_rate_reset_key(sa_rate *r, const char *key, uint32_t klen) {
459 (void)r; (void)key; (void)klen;
460 }
461  
462 static void sa_rate_forget(sa_rate *r, const char *key, uint32_t klen) {
463 (void)r; (void)key; (void)klen;
464 }
465  
466 static uint64_t sa_rate_used(sa_rate *r) { (void)r; return 0; }
467  
468 #endif /* SA_HAVE_ATOMICS */
469  
470 #endif /* SA_RATE_H */
« include/sa/sa_hist.h ↑ Summary include/sa/sa_hash.h »