| 1 |
import datetime |
| 2 |
import json |
| 3 |
import logging |
| 4 |
from collections.abc import Iterable |
| 5 |
from typing import Any |
| 6 |
|
| 7 |
from flask import Flask |
| 8 |
|
| 9 |
from flask_caching.backends.base import BaseCache |
| 10 |
from flask_caching.utils import _Timeout |
| 11 |
|
| 12 |
logger = logging.getLogger(__name__) |
| 13 |
|
| 14 |
|
| 15 |
try: |
| 16 |
from google.auth.credentials import ( # pyright: ignore[reportMissingImports] |
| 17 |
AnonymousCredentials, |
| 18 |
) |
| 19 |
from google.cloud import exceptions # pyright: ignore[reportAttributeAccessIssue] |
| 20 |
from google.cloud import storage # pyright: ignore[reportAttributeAccessIssue] |
| 21 |
except ImportError as e: |
| 22 |
raise RuntimeError("no google-cloud-storage module found") from e |
| 23 |
|
| 24 |
|
| 25 |
class GoogleCloudStorageCache(BaseCache): |
| 26 |
"""Uses an Google Cloud Storage bucket as a cache backend. |
| 27 |
Note: User-contributed functionality. This project does not guarantee that |
| 28 |
this functionality will be maintained or functional at any given time. |
| 29 |
Note: Cache keys must meet GCS criteria for a valid object name (a sequence |
| 30 |
of Unicode characters whose UTF-8 encoding is at most 1024 bytes long). |
| 31 |
Note: Expired cache objects are not automatically purged. If |
| 32 |
delete_expired_objects_on_read=True, they will be deleted following an |
| 33 |
attempted read (which reduces performance). Otherwise, you have to delete |
| 34 |
stale objects yourself. Consider an GCS bucket lifecycle rule or other |
| 35 |
out-of-band process. For example you can use the following rule. |
| 36 |
{"rule": [{"action": {"type": "Delete"}, "condition": {"daysSinceCustomTime": 0}}]} |
| 37 |
https://cloud.google.com/storage/docs/lifecycle#dayssincecustomtime |
| 38 |
:param bucket: Required. Name of the bucket to use. It must already exist. |
| 39 |
:param key_prefix: A prefix that should be added to all keys. |
| 40 |
:param default_timeout: the default timeout that is used if no timeout is |
| 41 |
specified on :meth:`~BaseCache.set`. A timeout of |
| 42 |
0 indicates that the cache never expires. |
| 43 |
:param delete_expired_objects_on_read: If True, if a read finds a stale |
| 44 |
object, it will be deleted before |
| 45 |
a response is returned. Will slow |
| 46 |
down responses. |
| 47 |
:param anonymous: If true, use anonymous credentials. Useful for testing. |
| 48 |
Any additional keyword arguments will be passed to ``google.cloud.storage.Client``. |
| 49 |
""" |
| 50 |
|
| 51 |
def __init__( |
| 52 |
self, |
| 53 |
bucket: str, |
| 54 |
key_prefix: str | None = None, |
| 55 |
default_timeout: int = 300, |
| 56 |
delete_expired_objects_on_read: bool = False, |
| 57 |
anonymous: bool = False, |
| 58 |
**kwargs: Any, |
| 59 |
) -> None: |
| 60 |
super().__init__(default_timeout) |
| 61 |
if not isinstance(bucket, str): |
| 62 |
raise ValueError("GCSCache bucket parameter must be a string") |
| 63 |
if anonymous: |
| 64 |
self._client = storage.Client( |
| 65 |
credentials=AnonymousCredentials(), project="test", **kwargs |
| 66 |
) |
| 67 |
else: |
| 68 |
self._client = storage.Client(**kwargs) |
| 69 |
self.bucket = self._client.get_bucket(bucket) |
| 70 |
self.key_prefix = key_prefix or "" |
| 71 |
self.default_timeout = default_timeout |
| 72 |
self.delete_expired_objects_on_read = delete_expired_objects_on_read |
| 73 |
|
| 74 |
@classmethod |
| 75 |
def factory( |
| 76 |
cls, |
| 77 |
app: Flask, |
| 78 |
config: dict[str, Any], |
| 79 |
args: list[Any], |
| 80 |
kwargs: dict[str, Any], |
| 81 |
) -> "GoogleCloudStorageCache": |
| 82 |
args.insert(0, config["CACHE_GCS_BUCKET"]) |
| 83 |
key_prefix = config.get("CACHE_KEY_PREFIX") |
| 84 |
if key_prefix: |
| 85 |
kwargs["key_prefix"] = key_prefix |
| 86 |
return cls(*args, **kwargs) |
| 87 |
|
| 88 |
def get(self, key: str) -> Any: |
| 89 |
result = None |
| 90 |
expired = False |
| 91 |
hit_or_miss = "miss" |
| 92 |
full_key = self.key_prefix + key |
| 93 |
blob = self.bucket.get_blob(full_key) |
| 94 |
if blob is not None: |
| 95 |
expired = blob.custom_time and self._now() > blob.custom_time |
| 96 |
if expired: |
| 97 |
# Object is stale |
| 98 |
if self.delete_expired_objects_on_read: |
| 99 |
self._delete(full_key) |
| 100 |
else: |
| 101 |
try: |
| 102 |
result = blob.download_as_bytes() |
| 103 |
hit_or_miss = "hit" |
| 104 |
if blob.content_type == "application/json": |
| 105 |
result = json.loads(result) |
| 106 |
except exceptions.NotFound: |
| 107 |
pass |
| 108 |
expiredstr = "(expired)" if expired else "" |
| 109 |
logger.debug("get key %r -> %s %s", full_key, hit_or_miss, expiredstr) |
| 110 |
return result |
| 111 |
|
| 112 |
def set(self, key: str, value: Any, timeout: _Timeout | None = None) -> bool: |
| 113 |
result = False |
| 114 |
full_key = self.key_prefix + key |
| 115 |
content_type = "application/json" |
| 116 |
try: |
| 117 |
value = json.dumps(value) |
| 118 |
except (UnicodeDecodeError, TypeError): |
| 119 |
content_type = "application/octet-stream" |
| 120 |
blob = self.bucket.blob(full_key) |
| 121 |
seconds = self._normalize_timeout(timeout) |
| 122 |
if seconds != 0: |
| 123 |
# Use 'Custom-Time' for expiry |
| 124 |
# https://cloud.google.com/storage/docs/metadata#custom-time |
| 125 |
blob.custom_time = self._now(delta=seconds) |
| 126 |
try: |
| 127 |
blob.upload_from_string(value, content_type=content_type) |
| 128 |
result = True |
| 129 |
except exceptions.TooManyRequests: |
| 130 |
pass |
| 131 |
logger.debug("set key %r -> %s", full_key, result) |
| 132 |
return result |
| 133 |
|
| 134 |
def add(self, key: str, value: Any, timeout: _Timeout | None = None) -> bool: |
| 135 |
full_key = self.key_prefix + key |
| 136 |
if self._has(full_key): |
| 137 |
logger.debug("add key %r -> not added", full_key) |
| 138 |
return False |
| 139 |
else: |
| 140 |
return self.set(key, value, timeout) |
| 141 |
|
| 142 |
def delete(self, key: str) -> bool: |
| 143 |
full_key = self.key_prefix + key |
| 144 |
return self._delete(full_key) |
| 145 |
|
| 146 |
def delete_many(self, *keys: str) -> Any: |
| 147 |
return self._delete_many(self.key_prefix + key for key in keys) |
| 148 |
|
| 149 |
def has(self, key: str) -> bool: |
| 150 |
full_key = self.key_prefix + key |
| 151 |
return self._has(full_key) |
| 152 |
|
| 153 |
def clear(self) -> bool: |
| 154 |
return self._prune(clear_all=True) |
| 155 |
|
| 156 |
def _prune(self, clear_all: bool = False) -> bool: |
| 157 |
# Delete in batches of 100 which is much faster than individual deletes |
| 158 |
nremoved = 0 |
| 159 |
now = self._now() |
| 160 |
response_iterator = self._client.list_blobs( |
| 161 |
self.bucket, |
| 162 |
prefix=self.key_prefix, |
| 163 |
fields="items(name,customTime),nextPageToken", |
| 164 |
) |
| 165 |
to_delete = [] |
| 166 |
for blob in response_iterator: |
| 167 |
if clear_all or blob.custom_time and blob.custom_time < now: |
| 168 |
to_delete.append(blob.name) |
| 169 |
nremoved += 1 |
| 170 |
if len(to_delete) == 100: |
| 171 |
self._delete_many(to_delete) |
| 172 |
to_delete = [] |
| 173 |
# Delete the remainder |
| 174 |
if to_delete: |
| 175 |
self._delete_many(to_delete) |
| 176 |
logger.debug("evicted %d key(s)", nremoved) |
| 177 |
return True |
| 178 |
|
| 179 |
def _delete(self, key: str) -> bool: |
| 180 |
return self._delete_many([key]) |
| 181 |
|
| 182 |
def _delete_many(self, keys: Iterable[str]) -> bool: |
| 183 |
try: |
| 184 |
with self._client.batch(): |
| 185 |
for key in keys: |
| 186 |
self.bucket.delete_blob(key) |
| 187 |
except (exceptions.NotFound, exceptions.TooManyRequests): |
| 188 |
pass |
| 189 |
return True |
| 190 |
|
| 191 |
def _has(self, key: str) -> bool: |
| 192 |
result = False |
| 193 |
expired = False |
| 194 |
blob = self.bucket.get_blob(key) |
| 195 |
if blob is not None: |
| 196 |
expired = blob.custom_time and self._now() > blob.custom_time |
| 197 |
if expired: |
| 198 |
# Exists but is stale |
| 199 |
if self.delete_expired_objects_on_read: |
| 200 |
self._delete(key) |
| 201 |
else: |
| 202 |
result = True |
| 203 |
expiredstr = "(expired)" if expired else "" |
| 204 |
logger.debug("has key %r -> %s %s", key, result, expiredstr) |
| 205 |
return result |
| 206 |
|
| 207 |
def _now(self, delta: int = 0) -> datetime.datetime: |
| 208 |
return datetime.datetime.now(datetime.UTC) + datetime.timedelta(seconds=delta) |