_local_storage.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. """Saves modules to disk and fetches them if remote storage is not available."""
  2. # ©️ Dan Gazizullin, 2021-2023
  3. # This file is a part of Hikka Userbot
  4. # 🌐 https://github.com/hikariatama/Hikka
  5. # You can redistribute it and/or modify it under the terms of the GNU AGPLv3
  6. # 🔑 https://www.gnu.org/licenses/agpl-3.0.html
  7. import asyncio
  8. import contextlib
  9. import hashlib
  10. import logging
  11. import os
  12. import typing
  13. import requests
  14. from . import utils
  15. logger = logging.getLogger(__name__)
  16. MAX_FILESIZE = 1024 * 1024 * 5 # 5 MB
  17. MAX_TOTALSIZE = 1024 * 1024 * 100 # 100 MB
  18. class LocalStorage:
  19. """Saves modules to disk and fetches them if remote storage is not available."""
  20. def __init__(self):
  21. self._path = os.path.join(os.path.expanduser("~"), ".hikka", "modules_cache")
  22. self._ensure_dirs()
  23. @property
  24. def _total_size(self) -> int:
  25. return sum(os.path.getsize(f.path) for f in os.scandir(self._path))
  26. def _ensure_dirs(self):
  27. """Ensures that the local storage directory exists."""
  28. if not os.path.isdir(self._path):
  29. os.makedirs(self._path)
  30. def _get_path(self, repo: str, module_name: str) -> str:
  31. return os.path.join(
  32. self._path,
  33. hashlib.sha256(f"{repo}_{module_name}".encode("utf-8")).hexdigest() + ".py",
  34. )
  35. def save(self, repo: str, module_name: str, module_code: str):
  36. """Saves module to disk."""
  37. size = len(module_code)
  38. if size > MAX_FILESIZE:
  39. logger.warning(
  40. "Module %s from %s is too large (%s bytes) to save to local cache.",
  41. module_name,
  42. repo,
  43. size,
  44. )
  45. return
  46. if self._total_size + size > MAX_TOTALSIZE:
  47. logger.warning(
  48. "Local storage is full, cannot save module %s from %s.",
  49. module_name,
  50. repo,
  51. )
  52. return
  53. with open(self._get_path(repo, module_name), "w") as f:
  54. f.write(module_code)
  55. logger.debug("Saved module %s from %s to local cache.", module_name, repo)
  56. def fetch(self, repo: str, module_name: str) -> typing.Optional[str]:
  57. """Fetches module from disk."""
  58. path = self._get_path(repo, module_name)
  59. if os.path.isfile(path):
  60. with open(path, "r") as f:
  61. return f.read()
  62. return None
  63. class RemoteStorage:
  64. def __init__(self):
  65. self._local_storage = LocalStorage()
  66. async def preload(self, urls: typing.List[str]):
  67. """Preloads modules from remote storage."""
  68. logger.debug("Preloading modules from remote storage.")
  69. for url in urls:
  70. logger.debug("Preloading module %s", url)
  71. with contextlib.suppress(Exception):
  72. await self.fetch(url)
  73. await asyncio.sleep(5)
  74. async def preload_main_repo(self):
  75. """Preloads modules from the main repo."""
  76. mods_info = (
  77. await utils.run_sync(requests.get, "https://mods.hikariatama.ru/mods.json")
  78. ).json()
  79. for name, info in mods_info.items():
  80. _, repo, module_name = self._parse_url(info["link"])
  81. code = self._local_storage.fetch(repo, module_name)
  82. if code:
  83. sha = hashlib.sha256(code.encode("utf-8")).hexdigest()
  84. if sha != info["sha"]:
  85. logger.debug("Module %s from main repo is outdated.", name)
  86. code = None
  87. else:
  88. logger.debug("Module %s from main repo is up to date.", name)
  89. if not code:
  90. logger.debug("Preloading module %s from main repo.", name)
  91. with contextlib.suppress(Exception):
  92. await self.fetch(info["link"])
  93. await asyncio.sleep(5)
  94. continue
  95. @staticmethod
  96. def _parse_url(url: str) -> typing.Tuple[str, str, str]:
  97. """Parses a URL into a repository and module name."""
  98. domain_name = url.split("/")[2]
  99. if domain_name == "raw.githubusercontent.com":
  100. owner, repo, branch = url.split("/")[3:6]
  101. module_name = url.split("/")[-1].split(".")[0]
  102. repo = f"git+{owner}/{repo}:{branch}"
  103. elif domain_name == "github.com":
  104. owner, repo, _, branch = url.split("/")[3:7]
  105. module_name = url.split("/")[-1].split(".")[0]
  106. repo = f"git+{owner}/{repo}:{branch}"
  107. else:
  108. repo, module_name = url.rsplit("/", maxsplit=1)
  109. repo = repo.strip("/")
  110. return url, repo, module_name
  111. async def fetch(self, url: str) -> str:
  112. """
  113. Fetches the module from the remote storage.
  114. :param ref: The module reference. Can be url, or a reference to official repo module.
  115. """
  116. url, repo, module_name = self._parse_url(url)
  117. try:
  118. r = await utils.run_sync(requests.get, url)
  119. r.raise_for_status()
  120. except Exception:
  121. logger.debug(
  122. "Can't load module from remote storage. Trying local storage.",
  123. exc_info=True,
  124. )
  125. if module := self._local_storage.fetch(repo, module_name):
  126. logger.debug("Module source loaded from local storage.")
  127. return module
  128. raise
  129. self._local_storage.save(repo, module_name, r.text)
  130. return r.text