|
1 | 1 | """Caching functions."""
|
2 | 2 |
|
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import hashlib |
| 6 | +import os |
| 7 | + |
| 8 | +from flask import request |
3 | 9 | from flask_caching import Cache
|
| 10 | +from gramps.gen.errors import HandleError |
| 11 | + |
| 12 | +from gramps_webapi.api.auth import has_permissions |
| 13 | +from gramps_webapi.api.util import ( |
| 14 | + abort_with_message, |
| 15 | + get_db_handle, |
| 16 | + get_db_manager, |
| 17 | + get_tree_from_jwt, |
| 18 | + get_tree_from_jwt_or_fail, |
| 19 | +) |
| 20 | +from gramps_webapi.auth.const import PERM_VIEW_PRIVATE |
4 | 21 |
|
5 | 22 | thumbnail_cache = Cache()
|
| 23 | +request_cache = Cache() |
| 24 | + |
| 25 | + |
| 26 | +def get_db_last_change_timestamp(tree_id: str) -> int | float | None: |
| 27 | + """Get the last change timestamp of the database. |
| 28 | +
|
| 29 | + We do this by looking at the modification time of the meta db file. |
| 30 | + If the file does not exist, returns None. |
| 31 | + """ |
| 32 | + if not tree_id: |
| 33 | + raise ValueError("Tree ID must not be empty") |
| 34 | + dbmgr = get_db_manager(tree_id) |
| 35 | + meta_path = os.path.join(dbmgr.dbdir, dbmgr.dirname, "meta_data.db") |
| 36 | + try: |
| 37 | + return os.path.getmtime(meta_path) |
| 38 | + except FileNotFoundError: |
| 39 | + return None |
| 40 | + |
| 41 | + |
| 42 | +def _hash_request_args() -> str: |
| 43 | + """Hash the request arguments for use in cache keys.""" |
| 44 | + query_args = list((k, v) for (k, v) in request.args.items(multi=True) if k != "jwt") |
| 45 | + args_as_sorted_tuple = tuple(sorted(query_args)) |
| 46 | + args_as_bytes = str(args_as_sorted_tuple).encode() |
| 47 | + arg_hash = hashlib.md5(args_as_bytes) |
| 48 | + return str(arg_hash.hexdigest()) |
| 49 | + |
| 50 | + |
| 51 | +def make_cache_key_thumbnails(*args, **kwargs): |
| 52 | + """Make a cache key for thumbnails.""" |
| 53 | + # hash query args except jwt |
| 54 | + arg_hash = _hash_request_args() |
| 55 | + |
| 56 | + # get media checksum |
| 57 | + handle = kwargs["handle"] |
| 58 | + tree = get_tree_from_jwt() |
| 59 | + db_handle = get_db_handle() |
| 60 | + try: |
| 61 | + obj = db_handle.get_media_from_handle(handle) |
| 62 | + except HandleError: |
| 63 | + abort_with_message(404, f"Handle {handle} not found") |
| 64 | + # checksum in the DB |
| 65 | + checksum = obj.checksum |
| 66 | + |
| 67 | + dbmgr = get_db_manager(tree) |
| 68 | + |
| 69 | + cache_key = checksum + request.path + arg_hash + dbmgr.dirname |
| 70 | + |
| 71 | + return cache_key |
| 72 | + |
| 73 | + |
| 74 | +def make_cache_key_request(*args, **kwargs): |
| 75 | + """Make a cache key for a base request.""" |
| 76 | + # hash query args except jwt |
| 77 | + arg_hash = _hash_request_args() |
| 78 | + |
| 79 | + # the request result will depend on whether the user can view private records |
| 80 | + # this will be "1" if the user can view private records, "0" otherwise |
| 81 | + permission_hash = str(int(has_permissions({PERM_VIEW_PRIVATE}))) |
| 82 | + |
| 83 | + tree_id = get_tree_from_jwt_or_fail() |
| 84 | + db_timestamp = get_db_last_change_timestamp(tree_id) |
| 85 | + if db_timestamp is None: |
| 86 | + raise ValueError("Database last change timestamp is None") |
| 87 | + |
| 88 | + cache_key = tree_id + str(db_timestamp) + request.path + arg_hash + permission_hash |
| 89 | + |
| 90 | + return cache_key |
| 91 | + |
| 92 | + |
| 93 | +def skip_cache_condition_request(*args, **kwargs) -> bool: |
| 94 | + """Condition to skip caching for a request.""" |
| 95 | + # skip caching if the user is not authorized to view private records |
| 96 | + tree_id = get_tree_from_jwt_or_fail() |
| 97 | + db_timestamp = get_db_last_change_timestamp(tree_id) |
| 98 | + # if the database timestamp is None, we cannot determine if the db |
| 99 | + # was changed, so we skip caching! |
| 100 | + should_skip = db_timestamp is None |
| 101 | + return should_skip |
| 102 | + |
| 103 | + |
| 104 | +request_cache_decorator = request_cache.cached( |
| 105 | + make_cache_key=make_cache_key_request, unless=skip_cache_condition_request |
| 106 | +) |
| 107 | +thumbnail_cache_decorator = thumbnail_cache.cached( |
| 108 | + make_cache_key=make_cache_key_thumbnails |
| 109 | +) |
0 commit comments