history.py 4.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 = os.path.join(self._filesystem_path,
  43. ".Radicale.cache", "history")
  44. try:
  45. with open(os.path.join(history_folder, href), "rb") as f:
  46. cache_etag, history_etag = pickle.load(f)
  47. except (FileNotFoundError, pickle.UnpicklingError, ValueError) as e:
  48. if isinstance(e, (pickle.UnpicklingError, ValueError)):
  49. logger.warning(
  50. "Failed to load history cache entry %r in %r: %s",
  51. href, self.path, e, exc_info=True)
  52. cache_etag = ""
  53. # Initialize with random data to prevent collisions with cleaned
  54. # expired items.
  55. history_etag = binascii.hexlify(os.urandom(16)).decode("ascii")
  56. etag = item.etag if item else ""
  57. if etag != cache_etag:
  58. self._storage._makedirs_synced(history_folder)
  59. history_etag = radicale_item.get_etag(
  60. history_etag + "/" + etag).strip("\"")
  61. # Race: Other processes might have created and locked the file.
  62. with contextlib.suppress(PermissionError), self._atomic_write(
  63. os.path.join(history_folder, href), "wb") as fo:
  64. fb = cast(BinaryIO, fo)
  65. pickle.dump([etag, history_etag], fb)
  66. return history_etag
  67. def _get_deleted_history_hrefs(self):
  68. """Returns the hrefs of all deleted items that are still in the
  69. history cache."""
  70. history_folder = os.path.join(self._filesystem_path,
  71. ".Radicale.cache", "history")
  72. with contextlib.suppress(FileNotFoundError):
  73. for entry in os.scandir(history_folder):
  74. href = entry.name
  75. if not pathutils.is_safe_filesystem_path_component(href):
  76. continue
  77. if os.path.isfile(os.path.join(self._filesystem_path, href)):
  78. continue
  79. yield href
  80. def _clean_history(self):
  81. # Delete all expired history entries of deleted items.
  82. history_folder = os.path.join(self._filesystem_path,
  83. ".Radicale.cache", "history")
  84. self._clean_cache(history_folder, self._get_deleted_history_hrefs(),
  85. max_age=self._max_sync_token_age)