|
| 1 | +import functools |
| 2 | +import os |
| 3 | +import pickle |
| 4 | +import sqlite3 |
| 5 | +import asyncstdlib as a |
| 6 | + |
| 7 | +USE_CACHE = True if os.getenv("NO_CACHE") != "1" else False |
| 8 | +CACHE_LOCATION = ( |
| 9 | + os.path.expanduser( |
| 10 | + os.getenv("CACHE_LOCATION", "~/.cache/async-substrate-interface") |
| 11 | + ) |
| 12 | + if USE_CACHE |
| 13 | + else ":memory:" |
| 14 | +) |
| 15 | + |
| 16 | + |
| 17 | +def _get_table_name(func): |
| 18 | + """Convert "ClassName.method_name" to "ClassName_method_name""" |
| 19 | + return func.__qualname__.replace(".", "_") |
| 20 | + |
| 21 | + |
| 22 | +def _check_if_local(chain: str) -> bool: |
| 23 | + return any([x in chain for x in ["127.0.0.1", "localhost", "0.0.0.0"]]) |
| 24 | + |
| 25 | + |
| 26 | +def _create_table(c, conn, table_name): |
| 27 | + c.execute( |
| 28 | + f"""CREATE TABLE IF NOT EXISTS {table_name} |
| 29 | + ( |
| 30 | + rowid INTEGER PRIMARY KEY AUTOINCREMENT, |
| 31 | + key BLOB, |
| 32 | + value BLOB, |
| 33 | + chain TEXT, |
| 34 | + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP |
| 35 | + ); |
| 36 | + """ |
| 37 | + ) |
| 38 | + c.execute( |
| 39 | + f"""CREATE TRIGGER IF NOT EXISTS prune_rows_trigger AFTER INSERT ON {table_name} |
| 40 | + BEGIN |
| 41 | + DELETE FROM {table_name} |
| 42 | + WHERE rowid IN ( |
| 43 | + SELECT rowid FROM {table_name} |
| 44 | + ORDER BY created_at DESC |
| 45 | + LIMIT -1 OFFSET 500 |
| 46 | + ); |
| 47 | + END;""" |
| 48 | + ) |
| 49 | + conn.commit() |
| 50 | + |
| 51 | + |
| 52 | +def _retrieve_from_cache(c, table_name, key, chain): |
| 53 | + try: |
| 54 | + c.execute( |
| 55 | + f"SELECT value FROM {table_name} WHERE key=? AND chain=?", (key, chain) |
| 56 | + ) |
| 57 | + result = c.fetchone() |
| 58 | + if result is not None: |
| 59 | + return pickle.loads(result[0]) |
| 60 | + except (pickle.PickleError, sqlite3.Error) as e: |
| 61 | + print(f"Cache error: {str(e)}") |
| 62 | + pass |
| 63 | + |
| 64 | + |
| 65 | +def _insert_into_cache(c, conn, table_name, key, result, chain): |
| 66 | + try: |
| 67 | + c.execute( |
| 68 | + f"INSERT OR REPLACE INTO {table_name} (key, value, chain) VALUES (?,?,?)", |
| 69 | + (key, pickle.dumps(result), chain), |
| 70 | + ) |
| 71 | + conn.commit() |
| 72 | + except (pickle.PickleError, sqlite3.Error) as e: |
| 73 | + print(f"Cache error: {str(e)}") |
| 74 | + pass |
| 75 | + |
| 76 | + |
| 77 | +def sql_lru_cache(maxsize=None): |
| 78 | + def decorator(func): |
| 79 | + conn = sqlite3.connect(CACHE_LOCATION) |
| 80 | + c = conn.cursor() |
| 81 | + table_name = _get_table_name(func) |
| 82 | + _create_table(c, conn, table_name) |
| 83 | + |
| 84 | + @functools.lru_cache(maxsize=maxsize) |
| 85 | + def inner(self, *args, **kwargs): |
| 86 | + c = conn.cursor() |
| 87 | + key = pickle.dumps((args, kwargs)) |
| 88 | + chain = self.url |
| 89 | + if not (local_chain := _check_if_local(chain)) or not USE_CACHE: |
| 90 | + result = _retrieve_from_cache(c, table_name, key, chain) |
| 91 | + if result is not None: |
| 92 | + return result |
| 93 | + |
| 94 | + # If not in DB, call func and store in DB |
| 95 | + result = func(self, *args, **kwargs) |
| 96 | + |
| 97 | + if not local_chain or not USE_CACHE: |
| 98 | + _insert_into_cache(c, conn, table_name, key, result, chain) |
| 99 | + |
| 100 | + return result |
| 101 | + |
| 102 | + return inner |
| 103 | + |
| 104 | + return decorator |
| 105 | + |
| 106 | + |
| 107 | +def async_sql_lru_cache(maxsize=None): |
| 108 | + def decorator(func): |
| 109 | + conn = sqlite3.connect(CACHE_LOCATION) |
| 110 | + c = conn.cursor() |
| 111 | + table_name = _get_table_name(func) |
| 112 | + _create_table(c, conn, table_name) |
| 113 | + |
| 114 | + @a.lru_cache(maxsize=maxsize) |
| 115 | + async def inner(self, *args, **kwargs): |
| 116 | + c = conn.cursor() |
| 117 | + key = pickle.dumps((args, kwargs)) |
| 118 | + chain = self.url |
| 119 | + |
| 120 | + if not (local_chain := _check_if_local(chain)) or not USE_CACHE: |
| 121 | + result = _retrieve_from_cache(c, table_name, key, chain) |
| 122 | + if result is not None: |
| 123 | + return result |
| 124 | + |
| 125 | + # If not in DB, call func and store in DB |
| 126 | + result = await func(self, *args, **kwargs) |
| 127 | + if not local_chain or not USE_CACHE: |
| 128 | + _insert_into_cache(c, conn, table_name, key, result, chain) |
| 129 | + |
| 130 | + return result |
| 131 | + |
| 132 | + return inner |
| 133 | + |
| 134 | + return decorator |
0 commit comments