history.py 4.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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-2019 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 binascii
  19. import contextlib
  20. import os
  21. import pickle
  22. from typing import BinaryIO, Optional, cast
  23. import radicale.item as radicale_item
  24. from radicale import pathutils
  25. from radicale.log import logger
  26. from radicale.storage import multifilesystem
  27. from radicale.storage.multifilesystem.base import CollectionBase
  28. class CollectionPartHistory(CollectionBase):
  29. _max_sync_token_age: int
  30. def __init__(self, storage_: "multifilesystem.Storage", path: str,
  31. filesystem_path: Optional[str] = None) -> None:
  32. super().__init__(storage_, path, filesystem_path)
  33. self._max_sync_token_age = storage_.configuration.get(
  34. "storage", "max_sync_token_age")
  35. def _update_history_etag(self, href, item):
  36. """Updates and retrieves the history etag from the history cache.
  37. The history cache contains a file for each current and deleted item
  38. of the collection. These files contain the etag of the item (empty
  39. string for deleted items) and a history etag, which is a hash over
  40. the previous history etag and the etag separated by "/".
  41. """
  42. history_folder = self._storage._get_collection_cache_subfolder(self._filesystem_path, ".Radicale.cache", "history")
  43. try:
  44. with open(os.path.join(history_folder, href), "rb") as f:
  45. cache_etag, history_etag = pickle.load(f)
  46. except (FileNotFoundError, pickle.UnpicklingError, ValueError) as e:
  47. if isinstance(e, (pickle.UnpicklingError, ValueError)):
  48. logger.warning(
  49. "Failed to load history cache entry %r in %r: %s",
  50. href, self.path, e, exc_info=True)
  51. cache_etag = ""
  52. # Initialize with random data to prevent collisions with cleaned
  53. # expired items.
  54. history_etag = binascii.hexlify(os.urandom(16)).decode("ascii")
  55. etag = item.etag if item else ""
  56. if etag != cache_etag:
  57. self._storage._makedirs_synced(history_folder)
  58. history_etag = radicale_item.get_etag(
  59. history_etag + "/" + etag).strip("\"")
  60. # Race: Other processes might have created and locked the file.
  61. with contextlib.suppress(PermissionError), self._atomic_write(
  62. os.path.join(history_folder, href), "wb") as fo:
  63. fb = cast(BinaryIO, fo)
  64. pickle.dump([etag, history_etag], fb)
  65. return history_etag
  66. def _get_deleted_history_hrefs(self):
  67. """Returns the hrefs of all deleted items that are still in the
  68. history cache."""
  69. history_folder = self._storage._get_collection_cache_subfolder(self._filesystem_path, ".Radicale.cache", "history")
  70. with contextlib.suppress(FileNotFoundError):
  71. for entry in os.scandir(history_folder):
  72. href = entry.name
  73. if not pathutils.is_safe_filesystem_path_component(href):
  74. continue
  75. if os.path.isfile(os.path.join(self._filesystem_path, href)):
  76. continue
  77. yield href
  78. def _clean_history(self):
  79. # Delete all expired history entries of deleted items.
  80. history_folder = self._storage._get_collection_cache_subfolder(self._filesystem_path, ".Radicale.cache", "history")
  81. self._clean_cache(history_folder, self._get_deleted_history_hrefs(),
  82. max_age=self._max_sync_token_age)