From da30a40fd6d26e881efbec5655b1053a60488e45 Mon Sep 17 00:00:00 2001 From: j Date: Sat, 8 Jun 2024 15:51:30 +0100 Subject: [PATCH] cache can_connect for 3 seconds --- oml/localnodes.py | 8 +++++--- oml/utils.py | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/oml/localnodes.py b/oml/localnodes.py index 4f8b8e1..87e5003 100644 --- a/oml/localnodes.py +++ b/oml/localnodes.py @@ -7,18 +7,20 @@ import netifaces from zeroconf import ( ServiceBrowser, ServiceInfo, ServiceStateChange ) -from zeroconf.asyncio import AsyncZeroconf +from zeroconf.asyncio import AsyncZeroconf from tornado.ioloop import PeriodicCallback import settings import state from tor_request import get_opener +from utils import time_cache import logging logger = logging.getLogger(__name__) -def can_connect(data): +@time_cache(3) +def can_connect(**data): try: opener = get_opener(data['id']) headers = { @@ -171,6 +173,6 @@ class LocalNodes(dict): def get_data(self, user_id): data = self.get(user_id) - if data and can_connect(data): + if data and can_connect(**data): return data return None diff --git a/oml/utils.py b/oml/utils.py index 7d07ca6..80c82dc 100644 --- a/oml/utils.py +++ b/oml/utils.py @@ -5,6 +5,7 @@ from datetime import datetime from io import StringIO, BytesIO from PIL import Image, ImageFile import base64 +import functools import hashlib import json import os @@ -581,3 +582,17 @@ def iexists(path): def same_path(f1, f2): return unicodedata.normalize('NFC', f1) == unicodedata.normalize('NFC', f2) + +def time_cache(max_age, maxsize=128, typed=False): + def _decorator(fn): + @functools.lru_cache(maxsize=maxsize, typed=typed) + def _new(*args, __time_salt, **kwargs): + return fn(*args, **kwargs) + + @functools.wraps(fn) + def _wrapped(*args, **kwargs): + return _new(*args, **kwargs, __time_salt=int(time.time() / max_age)) + + return _wrapped + + return _decorator