2023-02-08 02:14:09 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2023-02-10 06:21:24 +00:00
|
|
|
import asyncio
|
2023-02-08 02:14:09 +00:00
|
|
|
import functools
|
|
|
|
import inspect
|
2023-02-10 06:21:24 +00:00
|
|
|
import threading
|
2023-02-08 02:14:09 +00:00
|
|
|
import time
|
|
|
|
from concurrent.futures import ThreadPoolExecutor
|
2023-06-16 02:35:05 +00:00
|
|
|
from functools import wraps
|
2023-02-08 02:14:09 +00:00
|
|
|
|
|
|
|
from django.db import transaction
|
|
|
|
|
2023-02-09 12:48:25 +00:00
|
|
|
from .utils import logger
|
|
|
|
|
2023-02-08 02:14:09 +00:00
|
|
|
|
|
|
|
def on_transaction_commit(func):
|
|
|
|
"""
|
|
|
|
如果不调用on_commit, 对象创建时添加多对多字段值失败
|
|
|
|
"""
|
|
|
|
|
|
|
|
def inner(*args, **kwargs):
|
|
|
|
transaction.on_commit(lambda: func(*args, **kwargs))
|
|
|
|
|
|
|
|
return inner
|
|
|
|
|
|
|
|
|
|
|
|
class Singleton(object):
|
|
|
|
""" 单例类 """
|
|
|
|
|
|
|
|
def __init__(self, cls):
|
|
|
|
self._cls = cls
|
|
|
|
self._instance = {}
|
|
|
|
|
|
|
|
def __call__(self):
|
|
|
|
if self._cls not in self._instance:
|
|
|
|
self._instance[self._cls] = self._cls()
|
|
|
|
return self._instance[self._cls]
|
|
|
|
|
|
|
|
|
2023-02-09 12:48:25 +00:00
|
|
|
def default_suffix_key(*args, **kwargs):
|
|
|
|
return 'default'
|
|
|
|
|
|
|
|
|
|
|
|
def key_by_org(*args, **kwargs):
|
2023-02-13 11:14:00 +00:00
|
|
|
values = list(kwargs.values())
|
|
|
|
if not values:
|
|
|
|
return 'default'
|
2023-02-14 01:52:23 +00:00
|
|
|
return values[0][0].org_id
|
2023-02-09 12:48:25 +00:00
|
|
|
|
|
|
|
|
2023-02-11 15:00:41 +00:00
|
|
|
class EventLoopThread(threading.Thread):
|
|
|
|
def __init__(self, *args, **kwargs):
|
2023-02-10 06:21:24 +00:00
|
|
|
super().__init__(*args, **kwargs)
|
2023-02-11 15:00:41 +00:00
|
|
|
self._loop = asyncio.new_event_loop()
|
2023-02-10 06:21:24 +00:00
|
|
|
|
|
|
|
def run(self) -> None:
|
2023-02-11 15:00:41 +00:00
|
|
|
asyncio.set_event_loop(self._loop)
|
|
|
|
try:
|
|
|
|
self._loop.run_forever()
|
|
|
|
except Exception as e:
|
|
|
|
logger.error("Event loop stopped with err: {} ".format(e))
|
|
|
|
|
|
|
|
def get_loop(self):
|
|
|
|
return self._loop
|
2023-02-10 06:21:24 +00:00
|
|
|
|
|
|
|
|
2023-02-11 15:00:41 +00:00
|
|
|
_loop_thread = EventLoopThread()
|
|
|
|
_loop_thread.setDaemon(True)
|
|
|
|
_loop_thread.start()
|
2023-07-31 09:39:30 +00:00
|
|
|
executor = ThreadPoolExecutor(
|
|
|
|
max_workers=10,
|
|
|
|
thread_name_prefix='debouncer'
|
|
|
|
)
|
2023-02-10 10:01:31 +00:00
|
|
|
_loop_debouncer_func_task_cache = {}
|
|
|
|
_loop_debouncer_func_args_cache = {}
|
|
|
|
|
|
|
|
|
2023-07-31 09:39:30 +00:00
|
|
|
def get_loop():
|
|
|
|
return _loop_thread.get_loop()
|
|
|
|
|
|
|
|
|
2023-02-10 10:01:31 +00:00
|
|
|
def cancel_or_remove_debouncer_task(cache_key):
|
|
|
|
task = _loop_debouncer_func_task_cache.get(cache_key, None)
|
|
|
|
if not task:
|
|
|
|
return
|
|
|
|
if task.done():
|
|
|
|
del _loop_debouncer_func_task_cache[cache_key]
|
|
|
|
else:
|
|
|
|
task.cancel()
|
2023-02-10 06:21:24 +00:00
|
|
|
|
|
|
|
|
2023-02-13 11:14:00 +00:00
|
|
|
def run_debouncer_func(cache_key, org, ttl, func, *args, **kwargs):
|
|
|
|
cancel_or_remove_debouncer_task(cache_key)
|
|
|
|
run_func_partial = functools.partial(_run_func_with_org, cache_key, org, func)
|
|
|
|
loop = _loop_thread.get_loop()
|
|
|
|
_debouncer = Debouncer(run_func_partial, lambda: True, ttl, loop=loop, executor=executor)
|
|
|
|
task = asyncio.run_coroutine_threadsafe(_debouncer(*args, **kwargs), loop=loop)
|
|
|
|
_loop_debouncer_func_task_cache[cache_key] = task
|
|
|
|
|
|
|
|
|
2023-02-10 06:21:24 +00:00
|
|
|
class Debouncer(object):
|
2023-02-10 10:01:31 +00:00
|
|
|
def __init__(self, callback, check, delay, loop=None, executor=None):
|
2023-02-10 06:21:24 +00:00
|
|
|
self.callback = callback
|
|
|
|
self.check = check
|
|
|
|
self.delay = delay
|
2023-02-10 10:01:31 +00:00
|
|
|
self.loop = loop
|
|
|
|
if not loop:
|
|
|
|
self.loop = asyncio.get_event_loop()
|
|
|
|
self.executor = executor
|
2023-02-10 06:21:24 +00:00
|
|
|
|
|
|
|
async def __call__(self, *args, **kwargs):
|
|
|
|
await asyncio.sleep(self.delay)
|
2023-02-11 15:00:41 +00:00
|
|
|
ok = await self._run_sync_to_async(self.check)
|
2023-02-10 06:21:24 +00:00
|
|
|
if ok:
|
2023-02-11 15:00:41 +00:00
|
|
|
callback_func = functools.partial(self.callback, *args, **kwargs)
|
|
|
|
return await self._run_sync_to_async(callback_func)
|
2023-02-10 06:21:24 +00:00
|
|
|
|
2023-02-11 15:00:41 +00:00
|
|
|
async def _run_sync_to_async(self, func):
|
|
|
|
if asyncio.iscoroutinefunction(func):
|
|
|
|
return await func()
|
|
|
|
return await self.loop.run_in_executor(self.executor, func)
|
2023-02-10 06:21:24 +00:00
|
|
|
|
|
|
|
|
2023-02-10 10:01:31 +00:00
|
|
|
def _run_func_with_org(key, org, func, *args, **kwargs):
|
2023-02-10 06:21:24 +00:00
|
|
|
from orgs.utils import set_current_org
|
|
|
|
try:
|
|
|
|
set_current_org(org)
|
|
|
|
func(*args, **kwargs)
|
|
|
|
except Exception as e:
|
|
|
|
logger.error('delay run error: %s' % e)
|
2023-02-10 10:01:31 +00:00
|
|
|
_loop_debouncer_func_task_cache.pop(key, None)
|
|
|
|
_loop_debouncer_func_args_cache.pop(key, None)
|
2023-02-08 02:14:09 +00:00
|
|
|
|
|
|
|
|
2023-02-13 11:14:00 +00:00
|
|
|
def delay_run(ttl=5, key=None):
|
2023-02-09 12:48:25 +00:00
|
|
|
"""
|
|
|
|
延迟执行函数, 在 ttl 秒内, 只执行最后一次
|
|
|
|
:param ttl:
|
|
|
|
:param key: 是否合并参数, 一个 callback
|
2023-02-08 02:14:09 +00:00
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
|
|
|
|
def inner(func):
|
2023-02-09 12:48:25 +00:00
|
|
|
suffix_key_func = key if key else default_suffix_key
|
|
|
|
|
2023-02-08 02:14:09 +00:00
|
|
|
@functools.wraps(func)
|
2023-02-13 11:14:00 +00:00
|
|
|
def wrapper(*args, **kwargs):
|
2023-02-10 10:01:31 +00:00
|
|
|
from orgs.utils import get_current_org
|
|
|
|
org = get_current_org()
|
2023-02-09 12:48:25 +00:00
|
|
|
func_name = f'{func.__module__}_{func.__name__}'
|
2023-02-10 10:01:31 +00:00
|
|
|
key_suffix = suffix_key_func(*args)
|
|
|
|
cache_key = f'DELAY_RUN_{func_name}_{key_suffix}'
|
2023-02-13 11:14:00 +00:00
|
|
|
run_debouncer_func(cache_key, org, ttl, func, *args, **kwargs)
|
2023-02-08 02:14:09 +00:00
|
|
|
|
|
|
|
return wrapper
|
|
|
|
|
|
|
|
return inner
|
|
|
|
|
|
|
|
|
2023-02-13 11:14:00 +00:00
|
|
|
def merge_delay_run(ttl=5, key=None):
|
|
|
|
"""
|
|
|
|
延迟执行函数, 在 ttl 秒内, 只执行最后一次, 并且合并参数
|
|
|
|
:param ttl:
|
|
|
|
:param key: 是否合并参数, 一个 callback
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
|
|
|
|
def inner(func):
|
|
|
|
sigs = inspect.signature(func)
|
|
|
|
if len(sigs.parameters) != 1:
|
|
|
|
raise ValueError('func must have one arguments: %s' % func.__name__)
|
|
|
|
param = list(sigs.parameters.values())[0]
|
|
|
|
if not isinstance(param.default, tuple):
|
|
|
|
raise ValueError('func default must be tuple: %s' % param.default)
|
|
|
|
suffix_key_func = key if key else default_suffix_key
|
|
|
|
|
|
|
|
@functools.wraps(func)
|
|
|
|
def wrapper(*args, **kwargs):
|
|
|
|
from orgs.utils import get_current_org
|
|
|
|
org = get_current_org()
|
|
|
|
func_name = f'{func.__module__}_{func.__name__}'
|
|
|
|
key_suffix = suffix_key_func(*args, **kwargs)
|
|
|
|
cache_key = f'MERGE_DELAY_RUN_{func_name}_{key_suffix}'
|
|
|
|
cache_kwargs = _loop_debouncer_func_args_cache.get(cache_key, {})
|
2023-02-13 12:04:17 +00:00
|
|
|
|
2023-02-13 11:14:00 +00:00
|
|
|
for k, v in kwargs.items():
|
2023-02-13 12:04:17 +00:00
|
|
|
if not isinstance(v, (tuple, list, set)):
|
|
|
|
raise ValueError('func kwargs value must be list or tuple: %s %s' % (func.__name__, v))
|
2023-02-13 11:14:00 +00:00
|
|
|
if k not in cache_kwargs:
|
|
|
|
cache_kwargs[k] = v
|
2023-02-13 12:04:17 +00:00
|
|
|
elif isinstance(v, set):
|
|
|
|
cache_kwargs[k] = cache_kwargs[k].union(v)
|
2023-02-13 11:14:00 +00:00
|
|
|
else:
|
2023-02-14 07:34:01 +00:00
|
|
|
cache_kwargs[k] = list(cache_kwargs[k]) + list(v)
|
2023-02-13 12:04:17 +00:00
|
|
|
_loop_debouncer_func_args_cache[cache_key] = cache_kwargs
|
2023-02-13 11:14:00 +00:00
|
|
|
run_debouncer_func(cache_key, org, ttl, func, *args, **cache_kwargs)
|
|
|
|
|
|
|
|
return wrapper
|
|
|
|
|
|
|
|
return inner
|
2023-02-08 02:14:09 +00:00
|
|
|
|
|
|
|
|
2023-02-10 10:01:31 +00:00
|
|
|
@delay_run(ttl=5)
|
2023-02-13 12:04:17 +00:00
|
|
|
def test_delay_run(username):
|
2023-02-10 10:01:31 +00:00
|
|
|
print("Hello, %s, now is %s" % (username, time.time()))
|
2023-02-10 07:08:33 +00:00
|
|
|
|
|
|
|
|
2023-02-13 12:04:17 +00:00
|
|
|
@merge_delay_run(ttl=5, key=lambda users=(): users[0][0])
|
2023-02-13 11:14:00 +00:00
|
|
|
def test_merge_delay_run(users=()):
|
2023-02-10 07:08:33 +00:00
|
|
|
name = ','.join(users)
|
|
|
|
time.sleep(2)
|
2023-02-08 02:14:09 +00:00
|
|
|
print("Hello, %s, now is %s" % (name, time.time()))
|
2023-02-09 12:48:25 +00:00
|
|
|
|
|
|
|
|
|
|
|
def do_test():
|
2023-02-10 07:08:33 +00:00
|
|
|
s = time.time()
|
|
|
|
print("start : %s" % time.time())
|
|
|
|
for i in range(100):
|
2023-02-09 12:48:25 +00:00
|
|
|
# test_delay_run('test', year=i)
|
2023-02-13 12:04:17 +00:00
|
|
|
test_merge_delay_run(users=['test %s' % i])
|
|
|
|
test_merge_delay_run(users=['best %s' % i])
|
2023-02-10 10:01:31 +00:00
|
|
|
test_delay_run('test run %s' % i)
|
2023-02-10 07:08:33 +00:00
|
|
|
|
|
|
|
end = time.time()
|
|
|
|
using = end - s
|
|
|
|
print("end : %s, using: %s" % (end, using))
|
2023-06-16 02:35:05 +00:00
|
|
|
|
|
|
|
|
|
|
|
def cached_method(ttl=20):
|
|
|
|
_cache = {}
|
|
|
|
|
|
|
|
def decorator(func):
|
|
|
|
@wraps(func)
|
|
|
|
def wrapper(*args, **kwargs):
|
|
|
|
key = (func, args, tuple(sorted(kwargs.items())))
|
|
|
|
# 检查缓存是否存在且未过期
|
|
|
|
if key in _cache and time.time() - _cache[key]['timestamp'] < ttl:
|
|
|
|
return _cache[key]['result']
|
|
|
|
|
|
|
|
# 缓存过期或不存在,执行方法并缓存结果
|
|
|
|
result = func(*args, **kwargs)
|
|
|
|
_cache[key] = {'result': result, 'timestamp': time.time()}
|
|
|
|
return result
|
|
|
|
|
|
|
|
return wrapper
|
|
|
|
|
|
|
|
return decorator
|