vayulib 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of vayulib might be problematic. Click here for more details.
- vayu/__init__.py +11 -0
- vayu/aio.py +64 -0
- vayu/cache.py +246 -0
- vayu/common.py +175 -0
- vayu/lock.py +151 -0
- vayu/log.py +40 -0
- vayu/pandas_utils.py +204 -0
- vayu/parallel.py +262 -0
- vayu/plotly_utils.py +138 -0
- vayu/statistics.py +22 -0
- vayu/time.py +270 -0
- vayulib-0.0.1.dist-info/METADATA +21 -0
- vayulib-0.0.1.dist-info/RECORD +14 -0
- vayulib-0.0.1.dist-info/WHEEL +4 -0
vayu/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
|
|
3
|
+
try:
|
|
4
|
+
import pandas as _pd
|
|
5
|
+
from vayu.pandas_utils import select_series, select_frame
|
|
6
|
+
if not hasattr(_pd.DataFrame, "select"):
|
|
7
|
+
_pd.DataFrame.select = select_frame
|
|
8
|
+
if not hasattr(pd.Series, "select"):
|
|
9
|
+
_pd.Series.select = select_series
|
|
10
|
+
except ImportError:
|
|
11
|
+
pass
|
vayu/aio.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from datetime import timedelta
|
|
3
|
+
from numbers import Number
|
|
4
|
+
from signal import SIGTERM, SIGINT
|
|
5
|
+
from typing import Union, Coroutine, Optional, List, Dict, Any
|
|
6
|
+
|
|
7
|
+
import aiohttp
|
|
8
|
+
from aiohttp import TCPConnector
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
async def get_first_and_cancel_rest(*tasks: Union[asyncio.Task, Coroutine]) -> asyncio.Task:
|
|
12
|
+
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
|
13
|
+
for task in pending:
|
|
14
|
+
task.cancel()
|
|
15
|
+
|
|
16
|
+
return done.pop()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def sleep_until_signal(duration: Union[timedelta, Number], signal: asyncio.Event) -> bool:
|
|
20
|
+
"""Sleep until duration unless signal fires. Returns True if signal fired first."""
|
|
21
|
+
if isinstance(duration, (int, float)):
|
|
22
|
+
duration = timedelta(seconds=duration)
|
|
23
|
+
|
|
24
|
+
sleep_task = asyncio.create_task(asyncio.sleep(duration.total_seconds()))
|
|
25
|
+
signal_task = asyncio.create_task(signal.wait())
|
|
26
|
+
done = await get_first_and_cancel_rest(sleep_task, signal_task)
|
|
27
|
+
return done is signal_task
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def attach_shutdown_signals(shutdown: asyncio.Event, signals: Optional[List] = None):
|
|
31
|
+
signals = signals or [SIGINT, SIGTERM]
|
|
32
|
+
loop = asyncio.get_running_loop()
|
|
33
|
+
|
|
34
|
+
def set_signal():
|
|
35
|
+
shutdown.set()
|
|
36
|
+
|
|
37
|
+
for signal in signals:
|
|
38
|
+
loop.add_signal_handler(signal, set_signal)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
async def grab_all_urls(key_url_map: Dict[Any, str], concurrency=100, timeout=15, print_progress=True) -> Dict[Any, Any]:
|
|
42
|
+
results = {}
|
|
43
|
+
tasks = []
|
|
44
|
+
semaphore = asyncio.Semaphore(concurrency)
|
|
45
|
+
|
|
46
|
+
async def fetch_url(session, url, key, results: Dict[Any, Any], timeout):
|
|
47
|
+
async with semaphore:
|
|
48
|
+
try:
|
|
49
|
+
async with session.get(url, timeout=timeout) as response:
|
|
50
|
+
results[key] = (response.status, await response.read())
|
|
51
|
+
except Exception as e:
|
|
52
|
+
results[key] = None, str(e)
|
|
53
|
+
|
|
54
|
+
async with aiohttp.ClientSession(connector=TCPConnector(ssl=False)) as session:
|
|
55
|
+
for key, url in key_url_map.items():
|
|
56
|
+
task = fetch_url(session, url, key, results, timeout)
|
|
57
|
+
tasks.append(task)
|
|
58
|
+
|
|
59
|
+
for i, task in enumerate(asyncio.as_completed(tasks)):
|
|
60
|
+
await task
|
|
61
|
+
if print_progress:
|
|
62
|
+
print(f'Progress: {i+1}/{len(tasks)}', end="\r")
|
|
63
|
+
|
|
64
|
+
return results
|
vayu/cache.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from datetime import timedelta
|
|
5
|
+
from functools import wraps
|
|
6
|
+
from hashlib import sha256
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from time import time
|
|
9
|
+
from typing import Callable, Any, Union, Dict, Tuple, Optional
|
|
10
|
+
import pickle
|
|
11
|
+
|
|
12
|
+
from vayu.log import L
|
|
13
|
+
from vayu.time import time_now, from_timestamp
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class _MethodDecoratorAdaptor(object):
|
|
17
|
+
def __init__(self, decorator, func):
|
|
18
|
+
self.decorator = decorator
|
|
19
|
+
self.func = func
|
|
20
|
+
|
|
21
|
+
def __call__(self, *args, **kwargs):
|
|
22
|
+
return self.decorator(self.func)(*args, **kwargs)
|
|
23
|
+
|
|
24
|
+
def __get__(self, instance, owner):
|
|
25
|
+
return self.decorator(self.func.__get__(instance, owner))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def auto_adapt_to_methods(decorator):
|
|
29
|
+
"""Allows you to use the same decorator on methods and functions,
|
|
30
|
+
hiding the self argument from the decorator."""
|
|
31
|
+
|
|
32
|
+
def adapt(func):
|
|
33
|
+
return _MethodDecoratorAdaptor(decorator, func)
|
|
34
|
+
|
|
35
|
+
return adapt
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Serializer(ABC):
|
|
39
|
+
@abstractmethod
|
|
40
|
+
def serialize(self, obj: Any) -> bytes:
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
def deserialize(self, bts: bytes) -> Any:
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class NoOpSerializer(Serializer):
|
|
49
|
+
def serialize(self, obj: Any) -> bytes:
|
|
50
|
+
return obj
|
|
51
|
+
|
|
52
|
+
def deserialize(self, bts: bytes) -> Any:
|
|
53
|
+
return bts
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Pickler(Serializer):
|
|
57
|
+
def serialize(self, obj: Any) -> bytes:
|
|
58
|
+
return pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
|
|
59
|
+
|
|
60
|
+
def deserialize(self, bts: bytes) -> Any:
|
|
61
|
+
return pickle.loads(bts)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Jsoner(Serializer):
|
|
65
|
+
def serialize(self, obj: Any) -> bytes:
|
|
66
|
+
return json.dumps(obj).encode()
|
|
67
|
+
|
|
68
|
+
def deserialize(self, bts: bytes) -> Any:
|
|
69
|
+
return json.loads(bts)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Cache(ABC):
|
|
73
|
+
def __init__(self, serializer: Serializer):
|
|
74
|
+
self._serializer = serializer
|
|
75
|
+
|
|
76
|
+
def cached(
|
|
77
|
+
self,
|
|
78
|
+
ttl: Union[timedelta, float] = None,
|
|
79
|
+
prefix: str = None,
|
|
80
|
+
key: Union[str, Callable] = None,
|
|
81
|
+
serializer: Serializer = None,
|
|
82
|
+
log: bool = True,
|
|
83
|
+
):
|
|
84
|
+
"""Used as decorator to cache function calls.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
ttl: cache expiry ttl
|
|
88
|
+
prefix: If set, gets prepended to the rest of the cache key, otherwise uses function,
|
|
89
|
+
class, and module name to create prefix.
|
|
90
|
+
key:
|
|
91
|
+
- None: Use SHA256 digest of *args & **kwargs to construct cache key
|
|
92
|
+
- str: Use the specified string and ignore function arguments
|
|
93
|
+
- Callable: Calls it with *args * **kwargs which returns a str key.
|
|
94
|
+
serializer: If not specified, default pickler serializer is used
|
|
95
|
+
log: If True, logs reports such as cache hit, miss etc.
|
|
96
|
+
|
|
97
|
+
"""
|
|
98
|
+
serializer = serializer or self._serializer
|
|
99
|
+
ttl = ttl or timedelta(days=365 * 10)
|
|
100
|
+
if not isinstance(ttl, timedelta):
|
|
101
|
+
ttl = timedelta(seconds=ttl)
|
|
102
|
+
if ttl.total_seconds() <= 0:
|
|
103
|
+
raise ValueError("ttl must be positive")
|
|
104
|
+
|
|
105
|
+
@auto_adapt_to_methods
|
|
106
|
+
def decorator(func):
|
|
107
|
+
f_name = func.__name__
|
|
108
|
+
|
|
109
|
+
@wraps(func)
|
|
110
|
+
def inner(*args, **kwargs):
|
|
111
|
+
t = time()
|
|
112
|
+
k = self._key(func, prefix=prefix, key=key, args=args, kwargs=kwargs)
|
|
113
|
+
t_del = time() - t
|
|
114
|
+
if 0.001 < t_del and log:
|
|
115
|
+
L.warn(f"Key construction for cached fn `{f_name}` took too long: {t_del:.6f}s")
|
|
116
|
+
|
|
117
|
+
got = self._read(k)
|
|
118
|
+
if got is not None:
|
|
119
|
+
return serializer.deserialize(got)
|
|
120
|
+
t = time()
|
|
121
|
+
result = func(*args, **kwargs)
|
|
122
|
+
t_del = time() - t
|
|
123
|
+
if log:
|
|
124
|
+
L.info(f"@cached({f_name}) - CACHE MISS | took: {t_del:.6}s")
|
|
125
|
+
self._write(k, serializer.serialize(result), ttl)
|
|
126
|
+
return result
|
|
127
|
+
|
|
128
|
+
@wraps(func)
|
|
129
|
+
def evict(*args, **kwargs):
|
|
130
|
+
k = self._key(func, prefix=prefix, key=key, args=args, kwargs=kwargs)
|
|
131
|
+
self._delete(k)
|
|
132
|
+
|
|
133
|
+
inner.evict = evict
|
|
134
|
+
|
|
135
|
+
return inner
|
|
136
|
+
|
|
137
|
+
return decorator
|
|
138
|
+
|
|
139
|
+
def read(self, key: str) -> Any:
|
|
140
|
+
got = self._read(key)
|
|
141
|
+
return None if got is None else self._serializer.deserialize(got)
|
|
142
|
+
|
|
143
|
+
def write(self, key: str, value: Any, ttl: timedelta):
|
|
144
|
+
return self._write(key, self._serializer.serialize(value), ttl)
|
|
145
|
+
|
|
146
|
+
@abstractmethod
|
|
147
|
+
def _read(self, key: str) -> Any:
|
|
148
|
+
raise NotImplementedError
|
|
149
|
+
|
|
150
|
+
@abstractmethod
|
|
151
|
+
def _write(self, key: str, value: Any, ttl: timedelta):
|
|
152
|
+
raise NotImplementedError
|
|
153
|
+
|
|
154
|
+
@abstractmethod
|
|
155
|
+
def _delete(self, key: str):
|
|
156
|
+
raise NotImplementedError
|
|
157
|
+
|
|
158
|
+
@staticmethod
|
|
159
|
+
def _key(
|
|
160
|
+
fn: Callable,
|
|
161
|
+
prefix: str = None,
|
|
162
|
+
key: Union[str, Callable] = None,
|
|
163
|
+
args: Tuple = None,
|
|
164
|
+
kwargs: Dict = None,
|
|
165
|
+
) -> str:
|
|
166
|
+
is_method = hasattr(fn, "__self__")
|
|
167
|
+
|
|
168
|
+
if isinstance(key, str):
|
|
169
|
+
return key
|
|
170
|
+
|
|
171
|
+
parts = []
|
|
172
|
+
if prefix:
|
|
173
|
+
parts.append(prefix)
|
|
174
|
+
else:
|
|
175
|
+
parts.append(fn.__module__)
|
|
176
|
+
parts.append(fn.__qualname__)
|
|
177
|
+
parts = [".".join(parts)]
|
|
178
|
+
if callable(key):
|
|
179
|
+
parts.append(key(*args, **kwargs))
|
|
180
|
+
else:
|
|
181
|
+
arg_key = ",".join([str(a) for a in args] + [f"{k}={v}" for k, v in kwargs.items()])
|
|
182
|
+
parts.append(sha256(arg_key.encode()).hexdigest())
|
|
183
|
+
return ":".join(parts)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class InMemCache(Cache):
|
|
187
|
+
def __init__(self, serializer: Serializer = None):
|
|
188
|
+
super().__init__(serializer or NoOpSerializer())
|
|
189
|
+
self._d = dict()
|
|
190
|
+
|
|
191
|
+
def _write(self, key: str, value: bytes, ttl: timedelta):
|
|
192
|
+
self._d[key] = (value, time_now(with_ms=True) + ttl)
|
|
193
|
+
|
|
194
|
+
def _read(self, key: str) -> Optional[bytes]:
|
|
195
|
+
got = self._d.get(key)
|
|
196
|
+
if got is None:
|
|
197
|
+
return None
|
|
198
|
+
value, expiry_time = got
|
|
199
|
+
if expiry_time < time_now(with_ms=True):
|
|
200
|
+
self._delete(key)
|
|
201
|
+
return None
|
|
202
|
+
return value
|
|
203
|
+
|
|
204
|
+
def _delete(self, key: str):
|
|
205
|
+
self._d.pop(key, None)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class FileCache(Cache):
|
|
209
|
+
def __init__(self, path: str, serializer: Serializer = None):
|
|
210
|
+
super().__init__(serializer or Pickler())
|
|
211
|
+
self._path = Path(path)
|
|
212
|
+
self._ttl_bytes_length = 8
|
|
213
|
+
|
|
214
|
+
def _write(self, key: str, value: bytes, ttl: timedelta):
|
|
215
|
+
expiry_time = time_now(with_ms=True) + ttl
|
|
216
|
+
ttl_bytes = int(expiry_time.timestamp() * 1e6).to_bytes(
|
|
217
|
+
length=self._ttl_bytes_length, byteorder="big"
|
|
218
|
+
)
|
|
219
|
+
bts = ttl_bytes + value
|
|
220
|
+
with open(self._path / key, "wb") as f:
|
|
221
|
+
f.write(bts)
|
|
222
|
+
|
|
223
|
+
def _read(self, key: str) -> Optional[bytes]:
|
|
224
|
+
try:
|
|
225
|
+
with open(self._path / key, "rb") as f:
|
|
226
|
+
ttl_bytes = f.read(self._ttl_bytes_length)
|
|
227
|
+
ttl = from_timestamp(int.from_bytes(ttl_bytes, "big") / 1e6)
|
|
228
|
+
if ttl < time_now(with_ms=True):
|
|
229
|
+
bts = None
|
|
230
|
+
else:
|
|
231
|
+
bts = f.read()
|
|
232
|
+
except FileNotFoundError:
|
|
233
|
+
return None
|
|
234
|
+
|
|
235
|
+
if bts is None:
|
|
236
|
+
self._delete(key)
|
|
237
|
+
return bts
|
|
238
|
+
|
|
239
|
+
def _delete(self, key: str):
|
|
240
|
+
os.remove(self._path / key)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
# file_cache = FileCache(Config.CACHE_DIR, serializer=Pickler())
|
|
244
|
+
# file_cached = file_cache.cached
|
|
245
|
+
# in_mem_cache = InMemCache(serializer=NoOpSerializer())
|
|
246
|
+
# in_mem_cached = in_mem_cache.cached
|
vayu/common.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import datetime as dt
|
|
3
|
+
import os
|
|
4
|
+
from dataclasses import dataclass, replace
|
|
5
|
+
from logging import Logger
|
|
6
|
+
from typing import Dict, Callable, Tuple, List, Union, Type, Sequence, Iterable
|
|
7
|
+
import time
|
|
8
|
+
from functools import wraps
|
|
9
|
+
from operator import attrgetter
|
|
10
|
+
import random
|
|
11
|
+
from zoneinfo import ZoneInfo
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
MIN_FLOAT = float("-inf")
|
|
15
|
+
MAX_FLOAT = float("inf")
|
|
16
|
+
TZ = ZoneInfo(os.getenv("TZ")) if os.getenv("TZ") else dt.datetime.now().astimezone().tzinfo
|
|
17
|
+
TypeException = Type[Exception]
|
|
18
|
+
|
|
19
|
+
TaskType = Tuple[Callable, List, Dict]
|
|
20
|
+
Comparable = Union[None, dt.date, dt.datetime, int, float]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def camel_or_space_to_snake(s):
|
|
24
|
+
s = s.replace(" ", "_")
|
|
25
|
+
return "".join(["_" + c.lower() if c.isupper() else c for c in s]).lstrip("_")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Interval:
|
|
30
|
+
start: Comparable
|
|
31
|
+
end: Comparable
|
|
32
|
+
|
|
33
|
+
def intersects(self, other: "Interval") -> bool:
|
|
34
|
+
return self.start <= other.end and other.start <= self.end
|
|
35
|
+
|
|
36
|
+
def intersection(self, other: "Interval") -> "Interval":
|
|
37
|
+
if not self.intersects(other):
|
|
38
|
+
raise ValueError("No intersection possible")
|
|
39
|
+
|
|
40
|
+
return replace(self, start=max(self.start, other.start), end=min(self.end, other.end))
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def union(cls, intervals: Sequence["Interval"], allow_gaps: bool = False) -> "Interval":
|
|
44
|
+
# TODO: Fix this: should have a signature same as intersection.
|
|
45
|
+
if len(intervals) == 0:
|
|
46
|
+
raise AssertionError("Length of intervals should at least be 1")
|
|
47
|
+
if len(intervals) == 1:
|
|
48
|
+
return intervals[0]
|
|
49
|
+
|
|
50
|
+
intervals = sorted(intervals, key=attrgetter("start"))
|
|
51
|
+
if not allow_gaps:
|
|
52
|
+
for i in range(len(intervals) - 1):
|
|
53
|
+
first = intervals[i]
|
|
54
|
+
second = intervals[i + 1]
|
|
55
|
+
if first.end < second.start:
|
|
56
|
+
raise ValueError(f"Gaps not supported in interval union")
|
|
57
|
+
|
|
58
|
+
return cls(start=intervals[0].start, end=intervals[-1].end)
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def range(self) -> Comparable:
|
|
62
|
+
return self.end - self.start
|
|
63
|
+
|
|
64
|
+
def _validate(self):
|
|
65
|
+
assert self.start < self.end, "start value should be less than equal to end"
|
|
66
|
+
|
|
67
|
+
def __post_init__(self):
|
|
68
|
+
self._validate()
|
|
69
|
+
|
|
70
|
+
def __or__(self, other) -> "Interval":
|
|
71
|
+
return self.__class__.union([self, other])
|
|
72
|
+
|
|
73
|
+
def __and__(self, other) -> "Interval":
|
|
74
|
+
return self.intersection(other)
|
|
75
|
+
|
|
76
|
+
def __sub__(self, other: Comparable) -> "Interval":
|
|
77
|
+
return self.__class__(start=self.start - other, end=self.end - other)
|
|
78
|
+
|
|
79
|
+
def __add__(self, other: Comparable) -> "Interval":
|
|
80
|
+
return self.__class__(start=self.start + other, end=self.end + other)
|
|
81
|
+
|
|
82
|
+
def __contains__(self, item: Union[Comparable, "Interval"]):
|
|
83
|
+
if isinstance(item, Interval):
|
|
84
|
+
return item.start in self and item.end in self
|
|
85
|
+
return self.start <= item <= self.end
|
|
86
|
+
|
|
87
|
+
def __str__(self):
|
|
88
|
+
return f"[{self.start} — {self.end}]"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class retry: # noqa
|
|
92
|
+
"""Retry calling the decorated function using an exponential backoff. Asyncio compatible."""
|
|
93
|
+
|
|
94
|
+
def __init__(
|
|
95
|
+
self,
|
|
96
|
+
exception_to_check: Union[TypeException, Tuple[TypeException]],
|
|
97
|
+
tries: int = 4,
|
|
98
|
+
delay: float = 1,
|
|
99
|
+
backoff: float = 2,
|
|
100
|
+
logger: Logger = None,
|
|
101
|
+
):
|
|
102
|
+
"""
|
|
103
|
+
Args:
|
|
104
|
+
exception_to_check: the exception to check. Maybe a tuple of exceptions to check.
|
|
105
|
+
tries: number of times to try (not retry) before giving up
|
|
106
|
+
delay: initial delay between retries in seconds
|
|
107
|
+
backoff: backoff multiplier e.g. value of 2 will double the delay for each retry
|
|
108
|
+
logger: logger to use. If None, print.
|
|
109
|
+
"""
|
|
110
|
+
self._tries = tries
|
|
111
|
+
self._delay = delay
|
|
112
|
+
self._backoff = backoff
|
|
113
|
+
self._ignore_exc_types = exception_to_check
|
|
114
|
+
self._log_fn = logger.warning if logger else print
|
|
115
|
+
|
|
116
|
+
def __call__(self, fn):
|
|
117
|
+
is_async = asyncio.iscoroutinefunction(fn)
|
|
118
|
+
if not is_async:
|
|
119
|
+
|
|
120
|
+
@wraps(fn)
|
|
121
|
+
def decorated(*a, **k):
|
|
122
|
+
last_exception = None
|
|
123
|
+
delay = self._delay
|
|
124
|
+
for attempt in range(self._tries):
|
|
125
|
+
try: # noqa
|
|
126
|
+
return fn(*a, **k)
|
|
127
|
+
except self._ignore_exc_types as e:
|
|
128
|
+
last_exception = e
|
|
129
|
+
msg = f"Error {e.__class__.__name__}: retrying {fn.__name__} - in {delay}s - attempt {attempt + 1}/{self._tries}"
|
|
130
|
+
self._log_fn(msg)
|
|
131
|
+
time.sleep(delay)
|
|
132
|
+
delay *= self._backoff
|
|
133
|
+
if last_exception is not None:
|
|
134
|
+
raise last_exception
|
|
135
|
+
|
|
136
|
+
return decorated
|
|
137
|
+
|
|
138
|
+
else:
|
|
139
|
+
|
|
140
|
+
@wraps(fn)
|
|
141
|
+
async def decorated(*a, **k):
|
|
142
|
+
last_exception = None
|
|
143
|
+
delay = self._delay
|
|
144
|
+
for attempt in range(self._tries):
|
|
145
|
+
try: # noqa
|
|
146
|
+
return await fn(*a, **k)
|
|
147
|
+
except self._ignore_exc_types as e:
|
|
148
|
+
last_exception = e
|
|
149
|
+
msg = f"{str(e.__class__.__name__)}: retrying {fn.__name__} - in {delay}s - attempt {attempt + 1}/{self._tries}"
|
|
150
|
+
self._log_fn(msg)
|
|
151
|
+
await asyncio.sleep(delay)
|
|
152
|
+
delay *= self._backoff
|
|
153
|
+
if last_exception is not None:
|
|
154
|
+
raise last_exception
|
|
155
|
+
|
|
156
|
+
return decorated
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
JitterT = Union[float, int, dt.timedelta]
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def add_jitter(n: JitterT, jitter_percentage: int = 20) -> JitterT:
|
|
163
|
+
"""Add jitter to seconds."""
|
|
164
|
+
return n * (1 + random.randint(-jitter_percentage, jitter_percentage) / 100)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def group(iterable: Iterable, key: Callable) -> Dict:
|
|
168
|
+
"""Group elements of an iterable by a key function."""
|
|
169
|
+
groups = {}
|
|
170
|
+
for item in iterable:
|
|
171
|
+
k = key(item)
|
|
172
|
+
if k not in groups:
|
|
173
|
+
groups[k] = []
|
|
174
|
+
groups[k].append(item)
|
|
175
|
+
return groups
|
vayu/lock.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import time
|
|
3
|
+
import uuid
|
|
4
|
+
from contextlib import asynccontextmanager
|
|
5
|
+
from datetime import timedelta
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
from redis.asyncio.lock import Lock
|
|
10
|
+
from redis.asyncio import Redis
|
|
11
|
+
except ImportError:
|
|
12
|
+
Lock = None
|
|
13
|
+
Redis = None
|
|
14
|
+
|
|
15
|
+
from vayu.aio import sleep_until_signal
|
|
16
|
+
from vayu.common import add_jitter
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _validate_import():
|
|
20
|
+
if Lock is None or Redis is None:
|
|
21
|
+
raise ImportError("redis.asyncio.lock and redis.asyncio are not available.")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class LongLivedLock(Lock):
|
|
25
|
+
"""A long-lived distributed lock that extends its expiration time periodically until released."""
|
|
26
|
+
def __init__(self, shutdown: Optional[asyncio.Event] = None, **kwargs):
|
|
27
|
+
super(LongLivedLock, self).__init__(**kwargs)
|
|
28
|
+
self._shutdown = shutdown
|
|
29
|
+
|
|
30
|
+
async def acquire(self, **kwargs):
|
|
31
|
+
if not self._shutdown:
|
|
32
|
+
self._shutdown = asyncio.Event()
|
|
33
|
+
|
|
34
|
+
result = await super(LongLivedLock, self).acquire(**kwargs)
|
|
35
|
+
asyncio.create_task(self._extend_lock_periodically())
|
|
36
|
+
return result
|
|
37
|
+
|
|
38
|
+
async def _extend_lock_periodically(self):
|
|
39
|
+
first_loop = True
|
|
40
|
+
while not self._shutdown.is_set():
|
|
41
|
+
if self.local.token is None:
|
|
42
|
+
return
|
|
43
|
+
if first_loop:
|
|
44
|
+
first_loop = False
|
|
45
|
+
else:
|
|
46
|
+
await self.extend(additional_time=self.timeout, replace_ttl=True)
|
|
47
|
+
sleep_for = self.timeout / 4
|
|
48
|
+
# Add jitter upto 20% of sleep_for.
|
|
49
|
+
sleep_for = add_jitter(sleep_for, 20)
|
|
50
|
+
await sleep_until_signal(duration=timedelta(seconds=sleep_for), signal=self._shutdown)
|
|
51
|
+
|
|
52
|
+
@staticmethod
|
|
53
|
+
def make_lock(
|
|
54
|
+
redis: "Redis",
|
|
55
|
+
name,
|
|
56
|
+
timeout: timedelta = None,
|
|
57
|
+
sleep: timedelta = None,
|
|
58
|
+
blocking_timeout: timedelta = None,
|
|
59
|
+
shutdown: Optional[asyncio.Event] = None,
|
|
60
|
+
) -> "LongLivedLock":
|
|
61
|
+
return LongLivedLock(
|
|
62
|
+
# TODO: See if we can get away with using a single redis connection.
|
|
63
|
+
redis=redis,
|
|
64
|
+
name=f"lock.{name}",
|
|
65
|
+
timeout=timeout.total_seconds() if timeout else 60,
|
|
66
|
+
sleep=sleep.total_seconds() if sleep else 5,
|
|
67
|
+
blocking_timeout=blocking_timeout.total_seconds() if blocking_timeout else None,
|
|
68
|
+
shutdown=shutdown,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class RedisSemaphore:
|
|
73
|
+
def __init__(self, redis_client: Redis, key: str, limit: int, ttl: timedelta = None, retry_every: timedelta = None, keep_renewing: bool = False):
|
|
74
|
+
"""A distributed semaphore using redis sorted sets.
|
|
75
|
+
|
|
76
|
+
Caveats:
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
redis_client:
|
|
80
|
+
key: Key to use for the semaphore.
|
|
81
|
+
limit: Maximum number of concurrent users.
|
|
82
|
+
ttl: Time to live for each user's lock.
|
|
83
|
+
retry_every:
|
|
84
|
+
keep_renewing:
|
|
85
|
+
"""
|
|
86
|
+
self._client = redis_client
|
|
87
|
+
self._key = key
|
|
88
|
+
self._limit = limit
|
|
89
|
+
self._ttl = ttl or timedelta(seconds=60)
|
|
90
|
+
self._retry_every = retry_every or timedelta(seconds=5)
|
|
91
|
+
self._keep_renewing = keep_renewing
|
|
92
|
+
|
|
93
|
+
# Lua script to add to sorted set if it is not full.
|
|
94
|
+
lua_script = """
|
|
95
|
+
local key = KEYS[1]
|
|
96
|
+
local member = ARGV[1]
|
|
97
|
+
local score = ARGV[2]
|
|
98
|
+
local min_score = ARGV[3]
|
|
99
|
+
local n = tonumber(ARGV[4])
|
|
100
|
+
redis.call('ZREMRANGEBYSCORE', key, '-inf', min_score)
|
|
101
|
+
if redis.call('ZCARD', key) < n then
|
|
102
|
+
return redis.call('ZADD', key, score, member)
|
|
103
|
+
else
|
|
104
|
+
return nil
|
|
105
|
+
end
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
self._lua_script = self._client.register_script(lua_script)
|
|
109
|
+
|
|
110
|
+
async def _add_to_sorted_set(self, member: str, score: int, min_score: int):
|
|
111
|
+
result = await self._lua_script(keys=[self._key], args=[member, str(score), str(min_score), self._limit])
|
|
112
|
+
return result is not None
|
|
113
|
+
|
|
114
|
+
async def acquire(self, identifier: str, shutdown: Optional[asyncio.Event] = None):
|
|
115
|
+
while True:
|
|
116
|
+
score = round(time.time())
|
|
117
|
+
min_score = score - self._ttl.total_seconds()
|
|
118
|
+
if await self._add_to_sorted_set(member=identifier, score=int(score), min_score=int(min_score)):
|
|
119
|
+
return True
|
|
120
|
+
# Retry after some time with some jitter.
|
|
121
|
+
if await sleep_until_signal(duration=add_jitter(self._retry_every), signal=shutdown or asyncio.Event()):
|
|
122
|
+
# Shutdown signal received.
|
|
123
|
+
return False
|
|
124
|
+
|
|
125
|
+
async def release(self, identifier: str):
|
|
126
|
+
await self._client.zrem(self._key, identifier)
|
|
127
|
+
|
|
128
|
+
@asynccontextmanager
|
|
129
|
+
async def lock(self, identifier: str = None, shutdown: Optional[asyncio.Event] = None):
|
|
130
|
+
identifier = identifier or uuid.uuid4().bytes
|
|
131
|
+
acquired = False
|
|
132
|
+
sig_renew = asyncio.Event()
|
|
133
|
+
task_renew = None
|
|
134
|
+
|
|
135
|
+
try:
|
|
136
|
+
acquired = await self.acquire(identifier, shutdown=shutdown)
|
|
137
|
+
if acquired and self._keep_renewing:
|
|
138
|
+
task_renew = asyncio.create_task(self._renew_periodically(identifier, shutdown=sig_renew))
|
|
139
|
+
yield
|
|
140
|
+
finally:
|
|
141
|
+
if acquired:
|
|
142
|
+
await self.release(identifier)
|
|
143
|
+
if task_renew:
|
|
144
|
+
sig_renew.set()
|
|
145
|
+
await task_renew
|
|
146
|
+
|
|
147
|
+
async def _renew_periodically(self, identifier: str, shutdown: asyncio.Event):
|
|
148
|
+
while not shutdown.is_set():
|
|
149
|
+
# Renew lock every quarter of ttl only if it is still in the set.
|
|
150
|
+
await self._client.zadd(self._key, {identifier: int(round(time.time()))}, xx=True)
|
|
151
|
+
await sleep_until_signal(duration=add_jitter(self._ttl/4), signal=shutdown)
|
vayu/log.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
import datetime
|
|
5
|
+
from pytz import timezone
|
|
6
|
+
|
|
7
|
+
LOGGING_TZ = timezone(os.getenv("TZ", "UTC"))
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _format_time(self, record, _=None):
|
|
11
|
+
return (
|
|
12
|
+
datetime.datetime.fromtimestamp(record.created, datetime.timezone.utc)
|
|
13
|
+
.replace(microsecond=0)
|
|
14
|
+
.astimezone(LOGGING_TZ)
|
|
15
|
+
.isoformat(sep="T")
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
formatter = logging.Formatter("[%(asctime)s] %(levelname)s> %(message)s")
|
|
20
|
+
logging.Formatter.formatTime = _format_time
|
|
21
|
+
|
|
22
|
+
_asyncio_logger = logging.getLogger("asyncio")
|
|
23
|
+
L = logging.getLogger()
|
|
24
|
+
|
|
25
|
+
_asyncio_logger.setLevel(logging.WARNING)
|
|
26
|
+
L.setLevel(os.getenv("LOG_LEVEL", "INFO").upper())
|
|
27
|
+
|
|
28
|
+
_handler = logging.StreamHandler(sys.stdout)
|
|
29
|
+
_handler.setLevel(logging.INFO)
|
|
30
|
+
_handler.setFormatter(formatter)
|
|
31
|
+
L.addHandler(_handler)
|
|
32
|
+
_asyncio_logger.addHandler(_handler)
|
|
33
|
+
|
|
34
|
+
L.i = L.info
|
|
35
|
+
L.d = L.debug
|
|
36
|
+
L.e = L.error
|
|
37
|
+
L.w = L.warning
|
|
38
|
+
L.c = L.critical
|
|
39
|
+
|
|
40
|
+
__all___ = [L]
|