cache.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2014 Jean-Marc Martins
  3. # Copyright © 2012-2017 Guillaume Ayoub
  4. # Copyright © 2017-2021 Unrud <unrud@outlook.com>
  5. # Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
  6. #
  7. # This library is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  19. import contextlib
  20. import os
  21. import pickle
  22. import time
  23. from hashlib import sha256
  24. from typing import BinaryIO, Iterable, NamedTuple, Optional, cast
  25. import radicale.item as radicale_item
  26. from radicale import pathutils, storage
  27. from radicale.log import logger
  28. from radicale.storage.multifilesystem.base import CollectionBase
  29. CacheContent = NamedTuple("CacheContent", [
  30. ("uid", str), ("etag", str), ("text", str), ("name", str), ("tag", str),
  31. ("start", int), ("end", int)])
  32. class CollectionPartCache(CollectionBase):
  33. def _clean_cache(self, folder: str, names: Iterable[str],
  34. max_age: int = 0) -> None:
  35. """Delete all ``names`` in ``folder`` that are older than ``max_age``.
  36. """
  37. age_limit: Optional[float] = None
  38. if max_age is not None and max_age > 0:
  39. age_limit = time.time() - max_age
  40. modified = False
  41. for name in names:
  42. if not pathutils.is_safe_filesystem_path_component(name):
  43. continue
  44. if age_limit is not None:
  45. try:
  46. # Race: Another process might have deleted the file.
  47. mtime = os.path.getmtime(os.path.join(folder, name))
  48. except FileNotFoundError:
  49. continue
  50. if mtime > age_limit:
  51. continue
  52. logger.debug("Found expired item in cache: %r", name)
  53. # Race: Another process might have deleted or locked the
  54. # file.
  55. try:
  56. os.remove(os.path.join(folder, name))
  57. except (FileNotFoundError, PermissionError):
  58. continue
  59. modified = True
  60. if modified:
  61. self._storage._sync_directory(folder)
  62. @staticmethod
  63. def _item_cache_hash(raw_text: bytes) -> str:
  64. _hash = sha256()
  65. _hash.update(storage.CACHE_VERSION)
  66. _hash.update(raw_text)
  67. return _hash.hexdigest()
  68. def _item_cache_content(self, item: radicale_item.Item) -> CacheContent:
  69. return CacheContent(item.uid, item.etag, item.serialize(), item.name,
  70. item.component_name, *item.time_range)
  71. def _store_item_cache(self, href: str, item: radicale_item.Item,
  72. cache_hash: str = "") -> CacheContent:
  73. if not cache_hash:
  74. cache_hash = self._item_cache_hash(
  75. item.serialize().encode(self._encoding))
  76. cache_folder = self._storage._get_collection_cache_subfolder(self._filesystem_path, ".Radicale.cache", "item")
  77. content = self._item_cache_content(item)
  78. self._storage._makedirs_synced(cache_folder)
  79. # Race: Other processes might have created and locked the file.
  80. # TODO: better fix for "mypy"
  81. with contextlib.suppress(PermissionError), self._atomic_write( # type: ignore
  82. os.path.join(cache_folder, href), "wb") as fo:
  83. fb = cast(BinaryIO, fo)
  84. pickle.dump((cache_hash, *content), fb)
  85. return content
  86. def _load_item_cache(self, href: str, cache_hash: str
  87. ) -> Optional[CacheContent]:
  88. cache_folder = self._storage._get_collection_cache_subfolder(self._filesystem_path, ".Radicale.cache", "item")
  89. try:
  90. with open(os.path.join(cache_folder, href), "rb") as f:
  91. hash_, *remainder = pickle.load(f)
  92. if hash_ and hash_ == cache_hash:
  93. return CacheContent(*remainder)
  94. except FileNotFoundError:
  95. pass
  96. except (pickle.UnpicklingError, ValueError) as e:
  97. logger.warning("Failed to load item cache entry %r in %r: %s",
  98. href, self.path, e, exc_info=True)
  99. return None
  100. def _clean_item_cache(self) -> None:
  101. cache_folder = self._storage._get_collection_cache_subfolder(self._filesystem_path, ".Radicale.cache", "item")
  102. self._clean_cache(cache_folder, (
  103. e.name for e in os.scandir(cache_folder) if not
  104. os.path.isfile(os.path.join(self._filesystem_path, e.name))))