File: ratelimit.c

package info (click to toggle)
tarantool 2.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 85,364 kB
  • sloc: ansic: 513,760; cpp: 69,489; sh: 25,650; python: 19,190; perl: 14,973; makefile: 4,173; yacc: 1,329; sql: 1,074; pascal: 620; ruby: 190; awk: 18; lisp: 7
file content (77 lines) | stat: -rw-r--r-- 1,642 bytes parent folder | download | duplicates (3)
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
#include <time.h>

#include "unit.h"
#include "ratelimit.h"

#define check(expected_emitted, expected_suppressed) do {		\
	is(emitted, expected_emitted, "emitted %d expected %d",		\
	   emitted, expected_emitted);					\
	is(suppressed, expected_suppressed, "suppressed %d expected %d",\
	   suppressed, expected_suppressed);				\
} while (0)

int
main()
{
	header();
	plan(10);

	srand(time(NULL));
	double now = rand();

	int burst = 10;
	double interval = 5;
	int count, emitted, suppressed;
	struct ratelimit rl = RATELIMIT_INITIALIZER(interval, burst);
	now += interval;

	count = burst;
	emitted = suppressed = 0;
	for (int i = 0; i < count; i++) {
		if (ratelimit_check(&rl, now, &suppressed))
			emitted++;
		now += interval / count / 2;
	}
	check(count, 0);

	emitted = suppressed = 0;
	for (int i = 0; i < count; i++) {
		if (ratelimit_check(&rl, now, &suppressed))
			emitted++;
		now += interval / count / 2;
	}
	check(0, 0);

	now += 1;
	emitted = suppressed = 0;
	if (ratelimit_check(&rl, now, &suppressed))
		emitted++;
	check(1, count);

	now += interval * 2;
	emitted = suppressed = 0;
	if (ratelimit_check(&rl, now, &suppressed))
		emitted++;
	check(1, 0);

	interval = 5;
	burst = 100;
	ratelimit_create(&rl, interval, burst);

	int interval_count = 10;
	count = burst * interval_count * 4;
	emitted = suppressed = 0;
	for (int i = 0; i < count; i++) {
		if (ratelimit_check(&rl, now, &suppressed))
			emitted++;
		now += interval_count * interval / count;
	}
	now += interval;
	ratelimit_check(&rl, now, &suppressed);
	check(interval_count * burst, count - interval_count * burst);

	check_plan();
	footer();

	return 0;
}