2021-09-07 00:09:18 -07:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2022-06-11 18:53:08 -07:00
|
|
|
import re
|
2021-09-07 00:09:18 -07:00
|
|
|
import random
|
2021-09-07 19:40:34 -07:00
|
|
|
import asyncio
|
2021-09-07 00:09:18 -07:00
|
|
|
import contextvars
|
2021-09-07 19:40:34 -07:00
|
|
|
from aiohttp import web
|
2022-06-11 18:53:08 -07:00
|
|
|
from typing import Dict
|
2021-09-07 00:09:18 -07:00
|
|
|
|
|
|
|
class ContextVar:
|
|
|
|
"""
|
|
|
|
contextvars.ContextVar, but you can call the var to get its value, rather than calling var.get()
|
|
|
|
"""
|
|
|
|
__slots__ = frozenset({'_var'})
|
|
|
|
def __init__(self, *a, **kw): self._var = contextvars.ContextVar(*a, **kw)
|
|
|
|
def __call__(self, *args): return self._var.get(*args) # convenience
|
|
|
|
def get(self, *args): return self._var.get(*args)
|
|
|
|
def set(self, *args): return self._var.set(*args)
|
|
|
|
def reset(self, *args): return self._var.reset(*args)
|
|
|
|
|
2022-06-11 18:53:08 -07:00
|
|
|
class MultiReplacer:
|
|
|
|
__slots__ = frozenset({'replacements', '_pattern'})
|
|
|
|
|
|
|
|
def __init__(self, replacements: Dict[bytes, bytes]): # TODO support AnyStr
|
|
|
|
self.replacements = replacements
|
|
|
|
self._pattern = re.compile(b'(?:%b)' % b'|'.join(map(re.escape, self.replacements)))
|
|
|
|
|
|
|
|
def replace(self, s):
|
|
|
|
return self._pattern.sub(self._replacement, s)
|
|
|
|
|
|
|
|
def _replacement(self, match):
|
|
|
|
return self.replacements[match[0]]
|
|
|
|
|
2021-09-08 02:51:40 -07:00
|
|
|
def build_dprint_factory(debug: bool):
|
2021-09-07 00:09:18 -07:00
|
|
|
if debug:
|
2021-09-08 02:51:40 -07:00
|
|
|
def dprint_factory():
|
2021-09-07 00:09:18 -07:00
|
|
|
# 8 byte pseudo-random request tag
|
2021-09-08 02:51:40 -07:00
|
|
|
req_id = ''.join(random.choices('0123456789abcdef', k=8 * 2))
|
|
|
|
def dprint(*args, **kwargs): print(f'[{req_id}]', *args, **kwargs)
|
|
|
|
return dprint
|
2021-09-07 00:09:18 -07:00
|
|
|
else:
|
2021-09-08 02:51:40 -07:00
|
|
|
def dprint(*args, **kwargs): return None
|
|
|
|
def dprint_factory(): return dprint
|
2021-09-07 00:09:18 -07:00
|
|
|
|
2021-09-08 02:51:40 -07:00
|
|
|
return dprint_factory
|
2021-09-07 19:40:34 -07:00
|
|
|
|
|
|
|
def make_unlimited_request(*args):
|
|
|
|
return web.BaseRequest(*args, loop=asyncio.get_running_loop(), client_max_size=None)
|