cache.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import json
  2. import os
  3. import os.path
  4. import threading
  5. import time
  6. from modules.paths import data_path, script_path
  7. cache_filename = os.environ.get('SD_WEBUI_CACHE_FILE', os.path.join(data_path, "cache.json"))
  8. cache_data = None
  9. cache_lock = threading.Lock()
  10. dump_cache_after = None
  11. dump_cache_thread = None
  12. def dump_cache():
  13. """
  14. Marks cache for writing to disk. 5 seconds after no one else flags the cache for writing, it is written.
  15. """
  16. global dump_cache_after
  17. global dump_cache_thread
  18. def thread_func():
  19. global dump_cache_after
  20. global dump_cache_thread
  21. while dump_cache_after is not None and time.time() < dump_cache_after:
  22. time.sleep(1)
  23. with cache_lock:
  24. cache_filename_tmp = cache_filename + "-"
  25. with open(cache_filename_tmp, "w", encoding="utf8") as file:
  26. json.dump(cache_data, file, indent=4, ensure_ascii=False)
  27. os.replace(cache_filename_tmp, cache_filename)
  28. dump_cache_after = None
  29. dump_cache_thread = None
  30. with cache_lock:
  31. dump_cache_after = time.time() + 5
  32. if dump_cache_thread is None:
  33. dump_cache_thread = threading.Thread(name='cache-writer', target=thread_func)
  34. dump_cache_thread.start()
  35. def cache(subsection):
  36. """
  37. Retrieves or initializes a cache for a specific subsection.
  38. Parameters:
  39. subsection (str): The subsection identifier for the cache.
  40. Returns:
  41. dict: The cache data for the specified subsection.
  42. """
  43. global cache_data
  44. if cache_data is None:
  45. with cache_lock:
  46. if cache_data is None:
  47. if not os.path.isfile(cache_filename):
  48. cache_data = {}
  49. else:
  50. try:
  51. with open(cache_filename, "r", encoding="utf8") as file:
  52. cache_data = json.load(file)
  53. except Exception:
  54. os.replace(cache_filename, os.path.join(script_path, "tmp", "cache.json"))
  55. print('[ERROR] issue occurred while trying to read cache.json, move current cache to tmp/cache.json and create new cache')
  56. cache_data = {}
  57. s = cache_data.get(subsection, {})
  58. cache_data[subsection] = s
  59. return s
  60. def cached_data_for_file(subsection, title, filename, func):
  61. """
  62. Retrieves or generates data for a specific file, using a caching mechanism.
  63. Parameters:
  64. subsection (str): The subsection of the cache to use.
  65. title (str): The title of the data entry in the subsection of the cache.
  66. filename (str): The path to the file to be checked for modifications.
  67. func (callable): A function that generates the data if it is not available in the cache.
  68. Returns:
  69. dict or None: The cached or generated data, or None if data generation fails.
  70. The `cached_data_for_file` function implements a caching mechanism for data stored in files.
  71. It checks if the data associated with the given `title` is present in the cache and compares the
  72. modification time of the file with the cached modification time. If the file has been modified,
  73. the cache is considered invalid and the data is regenerated using the provided `func`.
  74. Otherwise, the cached data is returned.
  75. If the data generation fails, None is returned to indicate the failure. Otherwise, the generated
  76. or cached data is returned as a dictionary.
  77. """
  78. existing_cache = cache(subsection)
  79. ondisk_mtime = os.path.getmtime(filename)
  80. entry = existing_cache.get(title)
  81. if entry:
  82. cached_mtime = entry.get("mtime", 0)
  83. if ondisk_mtime > cached_mtime:
  84. entry = None
  85. if not entry or 'value' not in entry:
  86. value = func()
  87. if value is None:
  88. return None
  89. entry = {'mtime': ondisk_mtime, 'value': value}
  90. existing_cache[title] = entry
  91. dump_cache()
  92. return entry['value']