|
| 1 | +# Copyright (c) "Neo4j" |
| 2 | +# Neo4j Sweden AB [https://neo4j.com] |
| 3 | +# |
| 4 | +# This file is part of Neo4j. |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | + |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import math |
| 22 | +import typing as t |
| 23 | +from time import monotonic |
| 24 | + |
| 25 | +from .._async_compat.concurrency import AsyncCooperativeLock |
| 26 | + |
| 27 | + |
| 28 | +if t.TYPE_CHECKING: |
| 29 | + import typing_extensions as te |
| 30 | + |
| 31 | + TKey: te.TypeAlias = t.Union[ |
| 32 | + str, |
| 33 | + t.Tuple[t.Tuple[str, t.Hashable], ...], |
| 34 | + t.Tuple[None], |
| 35 | + ] |
| 36 | + TVal: te.TypeAlias = t.Tuple[float, str] |
| 37 | + |
| 38 | + |
| 39 | +class AsyncHomeDbCache: |
| 40 | + _ttl: float |
| 41 | + _enabled: bool |
| 42 | + _max_size: int | None |
| 43 | + |
| 44 | + def __init__( |
| 45 | + self, |
| 46 | + enabled: bool = True, |
| 47 | + ttl: float = float("inf"), |
| 48 | + max_size: int | None = None, |
| 49 | + ) -> None: |
| 50 | + if math.isnan(ttl) or ttl <= 0: |
| 51 | + raise ValueError(f"home db cache ttl must be greater 0, got {ttl}") |
| 52 | + self._enabled = enabled |
| 53 | + self._ttl = ttl |
| 54 | + self._cache: dict[TKey, TVal] = {} |
| 55 | + self._lock = AsyncCooperativeLock() |
| 56 | + self._oldest_entry = monotonic() |
| 57 | + if max_size is not None and max_size <= 0: |
| 58 | + raise ValueError( |
| 59 | + f"home db cache max_size must be greater 0 or None, " |
| 60 | + f"got {max_size}" |
| 61 | + ) |
| 62 | + self._max_size = max_size |
| 63 | + self._truncate_size = ( |
| 64 | + min(max_size, int(0.01 * max_size * math.log(max_size))) |
| 65 | + if max_size is not None |
| 66 | + else None |
| 67 | + ) |
| 68 | + |
| 69 | + def compute_key( |
| 70 | + self, |
| 71 | + imp_user: str | None, |
| 72 | + auth: dict | None, |
| 73 | + ) -> TKey: |
| 74 | + if not self._enabled: |
| 75 | + return (None,) |
| 76 | + if imp_user is not None: |
| 77 | + return imp_user |
| 78 | + if auth is not None: |
| 79 | + return _consolidate_auth_token(auth) |
| 80 | + return (None,) |
| 81 | + |
| 82 | + def get(self, key: TKey) -> str | None: |
| 83 | + if not self._enabled: |
| 84 | + return None |
| 85 | + with self._lock: |
| 86 | + self._clean(monotonic()) |
| 87 | + val = self._cache.get(key) |
| 88 | + if val is None: |
| 89 | + return None |
| 90 | + return val[1] |
| 91 | + |
| 92 | + def set(self, key: TKey, value: str | None) -> None: |
| 93 | + if not self._enabled: |
| 94 | + return |
| 95 | + with self._lock: |
| 96 | + now = monotonic() |
| 97 | + self._clean(now) |
| 98 | + if value is None: |
| 99 | + self._cache.pop(key, None) |
| 100 | + else: |
| 101 | + self._cache[key] = (now, value) |
| 102 | + |
| 103 | + def clear(self) -> None: |
| 104 | + if not self._enabled: |
| 105 | + return |
| 106 | + with self._lock: |
| 107 | + self._cache = {} |
| 108 | + self._oldest_entry = monotonic() |
| 109 | + |
| 110 | + def _clean(self, now: float | None = None) -> None: |
| 111 | + now = monotonic() if now is None else now |
| 112 | + if now - self._oldest_entry > self._ttl: |
| 113 | + self._cache = { |
| 114 | + k: v |
| 115 | + for k, v in self._cache.items() |
| 116 | + if now - v[0] < self._ttl * 0.9 |
| 117 | + } |
| 118 | + self._oldest_entry = min( |
| 119 | + (v[0] for v in self._cache.values()), default=now |
| 120 | + ) |
| 121 | + if self._max_size and len(self._cache) > self._max_size: |
| 122 | + self._cache = dict( |
| 123 | + sorted( |
| 124 | + self._cache.items(), |
| 125 | + key=lambda item: item[1][0], |
| 126 | + reverse=True, |
| 127 | + )[: self._truncate_size] |
| 128 | + ) |
| 129 | + |
| 130 | + def __len__(self) -> int: |
| 131 | + return len(self._cache) |
| 132 | + |
| 133 | + @property |
| 134 | + def enabled(self) -> bool: |
| 135 | + return self._enabled |
| 136 | + |
| 137 | + |
| 138 | +def _consolidate_auth_token(auth: dict) -> tuple | str: |
| 139 | + if auth.get("scheme") == "basic" and isinstance( |
| 140 | + auth.get("principal"), str |
| 141 | + ): |
| 142 | + return auth["principal"] |
| 143 | + return _hashable_dict(auth) |
| 144 | + |
| 145 | + |
| 146 | +def _hashable_dict(d: dict) -> tuple: |
| 147 | + return tuple( |
| 148 | + (k, _hashable_dict(v) if isinstance(v, dict) else v) |
| 149 | + for k, v in sorted(d.items()) |
| 150 | + ) |
0 commit comments