Debian Codegraph @

aws_xray_sdk/core/sampling/reservoir.py

raw
1 import time
2 import threading
3
4
5 class Reservoir(object):
6 """
7 Keeps track of the number of sampled segments within
8 a single second. This class is implemented to be
9 thread-safe to achieve accurate sampling.
10 """
11 def __init__(self, traces_per_sec=0):
12 """
13 :param int traces_per_sec: number of guranteed
14 sampled segments.
15 """
16 self._lock = threading.Lock()
17 self.traces_per_sec = traces_per_sec
18 self.used_this_sec = 0
19 self.this_sec = int(time.time())
20
21 def take(self):
22 """
23 Returns True if there are segments left within the
24 current second, otherwise return False.
25 """
26 with self._lock:
27 now = int(time.time())
28
29 if now != self.this_sec:
30 self.used_this_sec = 0
31 self.this_sec = now
32
33 if self.used_this_sec >= self.traces_per_sec:
34 return False
35
36 self.used_this_sec = self.used_this_sec + 1
37 return True