|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import concurrent.futures |
| 5 | +import contextlib |
| 6 | +import os |
| 7 | +from collections.abc import Callable, Set |
| 8 | +from functools import partial |
| 9 | +from typing import Never |
| 10 | + |
| 11 | +import aiohttp_client_cache |
| 12 | +import diskcache |
| 13 | + |
| 14 | +_http_cache_name = "_http_v1" |
| 15 | + |
| 16 | + |
| 17 | +@contextlib.asynccontextmanager |
| 18 | +async def make_cache(): |
| 19 | + with concurrent.futures.ThreadPoolExecutor(1, "_http_cache") as executor: |
| 20 | + loop = asyncio.get_running_loop() |
| 21 | + |
| 22 | + def run_in_thread2[**P, T](fn: Callable[P, T]): |
| 23 | + async def wrapper(*args: P.args, **kwargs: P.kwargs): |
| 24 | + return await loop.run_in_executor(executor, partial(fn, *args, **kwargs)) |
| 25 | + |
| 26 | + return wrapper |
| 27 | + |
| 28 | + # diskcache will only close the sqlite connection if it was initialised |
| 29 | + # in the same thread. |
| 30 | + cache = await run_in_thread2(diskcache.Cache)( |
| 31 | + os.path.join(os.getcwd(), _http_cache_name), size_limit=2**30 * 10 |
| 32 | + ) |
| 33 | + |
| 34 | + def make_cache_wrapper(prefix: str): |
| 35 | + class Cache(aiohttp_client_cache.BaseCache): |
| 36 | + @run_in_thread2 |
| 37 | + def bulk_delete(self, keys: Set[str]): |
| 38 | + for key in keys: |
| 39 | + cache.delete((prefix, key)) |
| 40 | + |
| 41 | + @run_in_thread2 |
| 42 | + def contains(self, key: str): |
| 43 | + return (prefix, key) in cache |
| 44 | + |
| 45 | + @run_in_thread2 |
| 46 | + def delete(self, key: str): |
| 47 | + cache.delete((prefix, key)) |
| 48 | + |
| 49 | + @run_in_thread2 |
| 50 | + def read(self, key: str): |
| 51 | + return cache.get((prefix, key)) |
| 52 | + |
| 53 | + @run_in_thread2 |
| 54 | + def write(self, key: str, item: aiohttp_client_cache.ResponseOrKey): |
| 55 | + cache[prefix, key] = item |
| 56 | + |
| 57 | + async def clear(self) -> Never: |
| 58 | + raise NotImplementedError |
| 59 | + |
| 60 | + async def keys(self): |
| 61 | + if False: # pragma: no cover |
| 62 | + yield |
| 63 | + raise NotImplementedError |
| 64 | + |
| 65 | + async def values(self): |
| 66 | + if False: # pragma: no cover |
| 67 | + yield |
| 68 | + raise NotImplementedError |
| 69 | + |
| 70 | + async def size(self) -> Never: |
| 71 | + raise NotImplementedError |
| 72 | + |
| 73 | + return Cache() |
| 74 | + |
| 75 | + try: |
| 76 | + yield make_cache_wrapper("responses"), make_cache_wrapper("redirects") |
| 77 | + finally: |
| 78 | + await run_in_thread2(cache.close)() |
0 commit comments