comparison libervia/backend/tools/common/async_utils.py @ 4071:4b842c1fb686

refactoring: renamed `sat` package to `libervia.backend`
author Goffi <goffi@goffi.org>
date Fri, 02 Jun 2023 11:49:51 +0200
parents sat/tools/common/async_utils.py@ebe45ea2df3b
children 0d7bb4df2343
comparison
equal deleted inserted replaced
4070:d10748475025 4071:4b842c1fb686
1 #!/usr/bin/env python3
2
3
4 # Libervia: an XMPP client
5 # Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
6
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 """tools to launch process in a async way (using Twisted)"""
21
22 from collections import OrderedDict
23 from typing import Optional, Callable, Awaitable
24 from libervia.backend.core.log import getLogger
25
26
27 log = getLogger(__name__)
28
29
30 def async_lru(maxsize: Optional[int] = 50) -> Callable:
31 """Decorator to cache async function results using LRU algorithm
32
33 @param maxsize: maximum number of items to keep in cache.
34 None to have no limit
35
36 """
37 def decorator(func: Callable) -> Callable:
38 cache = OrderedDict()
39 async def wrapper(*args) -> Awaitable:
40 if args in cache:
41 log.debug(f"using result in cache for {args}")
42 cache.move_to_end(args)
43 result = cache[args]
44 return result
45 log.debug(f"caching result for {args}")
46 result = await func(*args)
47 cache[args] = result
48 if maxsize is not None and len(cache) > maxsize:
49 value = cache.popitem(False)
50 log.debug(f"Removing LRU value: {value}")
51 return result
52 return wrapper
53 return decorator