Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ replacements:
# this dependency.
"google-resumable-media >= 2.7.2, < 3.0.0",
"requests >= 2.22.0, < 3.0.0",
"google-crc32c >= 1.9.0, < 2.0.0",
"google-crc32c >= 1.6.0, < 2.0.0",
]
extras = {
# TODO: Make these extra dependencies as mandatory once gRPC out of
Expand Down Expand Up @@ -659,7 +659,7 @@ replacements:
grpc-google-iam-v1==0.14.2
opentelemetry-api==1.1.0
requests==2.22.0
google-crc32c==1.9.0
google-crc32c==1.6.0
count: 1
- paths: [
packages/google-cloud-storage/testing/constraints-3.11.txt,
Expand Down Expand Up @@ -819,3 +819,18 @@ replacements:
*session.posargs,
)
count: 1
- paths: [
packages/google-cloud-storage/noxfile.py,
]
before: |
# Install all test dependencies, then install this package in-place.\n
constraints_path = str\(
after: |
# Install all test dependencies, then install this package in-place.

if session.python == "3.15":
session.skip(
"Skipping 3.15 until compatible wheels are available for google-crc32c"
)
constraints_path = str(
count: 1
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@

"""In-memory LRU cache for bucket metadata supporting App-centric Observability (ACO)."""

import asyncio
import contextvars
import logging
import threading

Expand All @@ -39,20 +37,6 @@ def __init__(self, client, max_size=10000):
self._lock = threading.Lock()
self._inflight_fetches = set()
self._inflight_checks = set()
self._background_tasks = set()

def _spawn_async_task(self, coro, inflight_set, bucket_name):
try:
loop = asyncio.get_running_loop()
except RuntimeError:
coro.close()
with self._lock:
inflight_set.discard(bucket_name)
return
# Detach from the caller's tracing context.
task = contextvars.Context().run(loop.create_task, coro)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)

def get(self, bucket_name):
"""Thread-safely retrieve cached metadata without queueing fetch."""
Expand All @@ -65,29 +49,21 @@ def get_or_queue_fetch(self, bucket_name):
Returns None immediately on cache miss so caller does not block.
"""
with self._lock:
cached = self._cache.get(bucket_name)
if cached is not None:
return cached
if bucket_name in self._inflight_fetches:
if bucket_name in self._cache:
return self._cache.get(bucket_name)
elif bucket_name in self._inflight_fetches:
# This handles a thundering herd where 'n' threads
# simultaneously experience a cache miss while 1 is already
# fetching metadata. The remaining n - 1 threads should
# bypass starting duplicate fetches.
return None
# fire a background fetch and get bucket metadata.
self._inflight_fetches.add(bucket_name)

if getattr(self._client, "_is_async_grpc_client", False) is True:
self._spawn_async_task(
self._fetch_background_async(bucket_name),
self._inflight_fetches,
bucket_name,
)
else:
threading.Thread(
target=self._fetch_background, args=(bucket_name,), daemon=True
).start()
return None
else:
# fire a background thread and get bucket metadata.
self._inflight_fetches.add(bucket_name)
threading.Thread(
target=self._fetch_background, args=(bucket_name,), daemon=True
).start()
return None

def check_and_evict(self, bucket_name):
"""Asynchronously verify if a bucket exists on 404 and evict if deleted."""
Expand All @@ -97,14 +73,6 @@ def check_and_evict(self, bucket_name):
if bucket_name in self._inflight_checks:
return
self._inflight_checks.add(bucket_name)

if getattr(self._client, "_is_async_grpc_client", False) is True:
self._spawn_async_task(
self._verify_existence_background_async(bucket_name),
self._inflight_checks,
bucket_name,
)
else:
threading.Thread(
target=self._verify_existence_background,
args=(bucket_name,),
Expand All @@ -124,27 +92,6 @@ def _verify_existence_background(self, bucket_name):
with self._lock:
self._inflight_checks.discard(bucket_name)

async def _verify_existence_background_async(self, bucket_name):
try:
from google.cloud import _storage_v2 as storage_v2

request = storage_v2.GetBucketRequest(
name=f"projects/_/buckets/{bucket_name}"
)
bucket = await self._client.grpc_client.get_bucket(
request=request, timeout=10.0
)
self.update_from_bucket(bucket, bucket_name=bucket_name)
except (NotFound, api_exceptions.NotFound):
self.evict(bucket_name)
except Exception as e:
logger.debug(
f"Async background verification for bucket existence failed for {bucket_name}: {e}"
)
finally:
with self._lock:
self._inflight_checks.discard(bucket_name)

def _fetch_background(self, bucket_name):
"""Asynchronously fetch bucket metadata and update the cache."""
try:
Expand All @@ -167,76 +114,28 @@ def _fetch_background(self, bucket_name):
with self._lock:
self._inflight_fetches.discard(bucket_name)

async def _fetch_background_async(self, bucket_name):
"""Asynchronously fetch bucket metadata via gRPC and update the cache."""
try:
from google.cloud import _storage_v2 as storage_v2

request = storage_v2.GetBucketRequest(
name=f"projects/_/buckets/{bucket_name}"
)
bucket = await self._client.grpc_client.get_bucket(
request=request, timeout=10.0
)
self.update_from_bucket(bucket, bucket_name=bucket_name)
except (NotFound, api_exceptions.NotFound):
self.evict(bucket_name)
except api_exceptions.Forbidden:
self.update_cache(
bucket_name,
f"//storage.googleapis.com/projects/_/buckets/{bucket_name}",
"global",
)
except Exception as e:
logger.debug(
f"Async background fetch for bucket metadata failed for {bucket_name}: {e}"
)
finally:
with self._lock:
self._inflight_fetches.discard(bucket_name)

def update_from_bucket(self, bucket, bucket_name=None):
"""Update cache from a Bucket instance or storage_v2.Bucket proto."""
if not bucket:
return
name = bucket_name or getattr(bucket, "name", None)
if not name or not isinstance(name, str):
def update_from_bucket(self, bucket):
"""Update cache from a Bucket instance."""
if not bucket or not bucket.name:
return
if name.startswith("projects/") and "/buckets/" in name:
name = name.split("/buckets/", 1)[1]

project_number = getattr(bucket, "project_number", None)
if not project_number:
proj_attr = getattr(bucket, "project", None)
if isinstance(proj_attr, (str, int)):
proj_str = str(proj_attr)
if proj_str.startswith("projects/"):
project_number = proj_str.split("projects/", 1)[1]
elif proj_str:
project_number = proj_str

loc_attr = getattr(bucket, "location", None)
location = (
loc_attr.lower() if isinstance(loc_attr, str) and loc_attr else "global"
)
loc_type_attr = getattr(bucket, "location_type", None)
location_type = (
loc_type_attr.lower()
if isinstance(loc_type_attr, str) and loc_type_attr
else "region"
)
location = getattr(bucket, "location", None) or "global"
location = location.lower()
location_type = getattr(bucket, "location_type", None) or "region"
location_type = location_type.lower()

if location_type in ("multi-region", "dual-region"):
location = "global"

if project_number and str(project_number) != "_":
if project_number:
destination_id = f"//storage.googleapis.com/projects/{project_number}/buckets/{bucket.name}"
else:
destination_id = (
f"//storage.googleapis.com/projects/{project_number}/buckets/{name}"
f"//storage.googleapis.com/projects/_/buckets/{bucket.name}"
)
else:
destination_id = f"//storage.googleapis.com/projects/_/buckets/{name}"

self.update_cache(name, destination_id, location)
self.update_cache(bucket.name, destination_id, location)

def update_cache(self, bucket_name, destination_id, location):
"""Thread-safely update or insert a cache entry with bounded size."""
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import re

from google.protobuf import timestamp_pb2

from google.cloud import _storage_v2
Expand All @@ -32,10 +30,6 @@
"storage_class": "storage_class",
}

# A Blob fetched from a CMEK object reports the key version it was encrypted
# with, which GCS rejects when creating an object.
_KMS_KEY_VERSION_SUFFIX = re.compile(r"/cryptoKeyVersions/[^/]+$")


def blob_to_proto(blob):
"""Converts a Blob instance to a GCS V2 Object proto message."""
Expand All @@ -50,9 +44,6 @@ def blob_to_proto(blob):
for attr_name, proto_field in _BLOB_ATTR_TO_PROTO_FIELD.items():
value = getattr(blob, attr_name, None)
if value is not None:
if proto_field == "kms_key":
# Write the new generation under the same key.
value = _KMS_KEY_VERSION_SUFFIX.sub("", value)
resource_params[proto_field] = value

custom_time = getattr(blob, "custom_time", None)
Expand Down
Loading
Loading