|
| 1 | +# Copyright 2025 Camptocamp SA |
| 2 | +# License LGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) |
| 3 | + |
| 4 | +import logging |
| 5 | +import typing |
| 6 | + |
| 7 | +from odoo.modules import registry |
| 8 | +from odoo.tools.lru import LRU |
| 9 | +from odoo.tools.misc import OrderedSet |
| 10 | + |
| 11 | +from .exceptions import ( |
| 12 | + CacheAlreadyExistsError, |
| 13 | + CacheInvalidConfigError, |
| 14 | + CacheInvalidDependencyError, |
| 15 | + CacheInvalidNameError, |
| 16 | +) |
| 17 | + |
| 18 | +_logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +def add_custom_cache( |
| 22 | + name: str, |
| 23 | + count: int, |
| 24 | + depends_on_caches: typing.Iterable[str] = None, |
| 25 | + allows_direct_invalidation: bool = True, |
| 26 | + ignore_exceptions: typing.Iterable[type] = (), |
| 27 | +): |
| 28 | + """Adds a custom cache into the Odoo registry |
| 29 | +
|
| 30 | + :param name: name of the custom cache to add |
| 31 | + :param count: max capability of the custom cache; set as 1 if a lower value is given |
| 32 | + :param allows_direct_invalidation: if ``True``, a DB sequence is assigned to the |
| 33 | + cache is assigned any sequence and (therefore dotted names for such caches are |
| 34 | + not allowed) and method ``Registry.clear_cache()`` can be called directly for it |
| 35 | + :param depends_on_caches: iterable of other cache names: if set, the current cache |
| 36 | + will be listed as dependent on those caches, and invalidating one of them will |
| 37 | + invalidate the custom cache as well |
| 38 | + :param ignore_exceptions: iterable of Exception types: if set, no error is raised, |
| 39 | + but the cache is not added to the registries anyway |
| 40 | + """ |
| 41 | + _logger.info(f"Adding cache '{name}' to registries...") |
| 42 | + |
| 43 | + # Backup ``registry`` module attributes that needs restoring if something goes wrong |
| 44 | + registry_caches_backup = dict(registry._REGISTRY_CACHES) |
| 45 | + caches_by_key_backup = dict(registry._CACHES_BY_KEY) |
| 46 | + |
| 47 | + try: |
| 48 | + # ``registry._REGISTRY_CACHES`` is used by ``registry.Registry.init()`` to |
| 49 | + # initialize registries' caches (attr ``__cache``) |
| 50 | + if name in registry._REGISTRY_CACHES: |
| 51 | + raise CacheAlreadyExistsError(f"Cache '{name}' already exists") |
| 52 | + normalized_count = max(count, 1) |
| 53 | + registry._REGISTRY_CACHES[name] = normalized_count |
| 54 | + |
| 55 | + # ``registry._CACHES_BY_KEY`` is used by a variety of ``registry.Registry`` |
| 56 | + # methods to handle caches dependencies and DB signaling (main reason why a |
| 57 | + # cache that allows direct invalidation cannot have a dotted name) |
| 58 | + if allows_direct_invalidation: |
| 59 | + if "." in name: |
| 60 | + raise CacheInvalidNameError(f"Invalid cache name '{name}'") |
| 61 | + registry._CACHES_BY_KEY[name] = (name,) |
| 62 | + elif not depends_on_caches: |
| 63 | + raise CacheInvalidConfigError( |
| 64 | + f"Cache '{name}' should either allow direct invalidation" |
| 65 | + f" or depend on another cache for indirect invalidation" |
| 66 | + ) |
| 67 | + |
| 68 | + # Setup invalidation dependencies |
| 69 | + # NB: use an ``OrderedSet`` to avoid duplicates while keeping the dependency |
| 70 | + # order, then convert to tuple for consistency w/ the standard |
| 71 | + # ``registry._CACHES_BY_KEY`` structure |
| 72 | + for parent in depends_on_caches or (): |
| 73 | + if parent not in registry._CACHES_BY_KEY: |
| 74 | + raise CacheInvalidDependencyError( |
| 75 | + f"Cache '{name}' cannot depend on cache '{parent}':" |
| 76 | + f" '{parent}' doesn't exist or doesn't allow direct invalidation" |
| 77 | + ) |
| 78 | + deps = OrderedSet(registry._CACHES_BY_KEY[parent]) |
| 79 | + deps.add(name) |
| 80 | + registry._CACHES_BY_KEY[parent] = tuple(deps) |
| 81 | + |
| 82 | + # Update existing registries by: |
| 83 | + # - adding the custom cache to the registry (name-mangle: no AttributeError) |
| 84 | + # - setting up the proper signaling workflow |
| 85 | + # NB: ``registry.Registry.registries`` is a class attribute that returns an |
| 86 | + # ``odoo.tools.lru.LRU`` object that maps DB names to ``registry.Registry`` |
| 87 | + # objects through variable ``d`` (which is a ``collections.OrderedDict`` object) |
| 88 | + for db_name, db_registry in registry.Registry.registries.d.items(): |
| 89 | + _logger.info(f"Adding cache '{name}' to '{db_name}' registry") |
| 90 | + db_registry._Registry__caches[name] = LRU(normalized_count) |
| 91 | + if allows_direct_invalidation: |
| 92 | + db_registry.setup_signaling() |
| 93 | + |
| 94 | + except Exception as exc: |
| 95 | + _logger.error(f"Could not add custom cache '{name}': {exc}") |
| 96 | + registry._REGISTRY_CACHES = registry_caches_backup |
| 97 | + registry._CACHES_BY_KEY = caches_by_key_backup |
| 98 | + ignore_exceptions = tuple(ignore_exceptions or ()) |
| 99 | + if not (ignore_exceptions and isinstance(exc, ignore_exceptions)): |
| 100 | + raise |
0 commit comments