cache.py 4.8 KB

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