|
| 1 | +from datetime import datetime, timedelta, timezone |
1 | 2 | from enum import StrEnum
|
| 3 | +from functools import cached_property |
2 | 4 | from typing import Any
|
3 | 5 |
|
4 |
| -from google.auth.credentials import AnonymousCredentials |
5 |
| -from google.cloud import storage |
| 6 | +from google.cloud import storage as gcs, exceptions as gce |
6 | 7 |
|
7 | 8 | from nmdc_server.config import settings
|
| 9 | +from nmdc_server.schemas import SignedUrl |
8 | 10 |
|
9 | 11 |
|
10 |
| -class Bucket(StrEnum): |
| 12 | +class BucketName(StrEnum): |
11 | 13 | """Enum for GCS bucket names"""
|
12 | 14 |
|
13 | 15 | SUBMISSION_IMAGES = "nmdc-submission-images"
|
14 | 16 |
|
15 | 17 |
|
16 |
| -def _initialize_client() -> storage.Client: |
17 |
| - client_args: dict[str, Any] = { |
18 |
| - "project": settings.gcs_project_id, |
19 |
| - } |
| 18 | +class Storage: |
| 19 | + """A class to manage Google Cloud Storage interactions.""" |
20 | 20 |
|
21 |
| - if settings.use_fake_gcs_server: |
22 |
| - # https://github.com/fsouza/fake-gcs-server/blob/cd43b03fcfb8149c6f57c1a92e19d1a07e291a3c/examples/python/python.py |
23 |
| - client_args["credentials"] = AnonymousCredentials() |
24 |
| - client_args["client_options"] = {"api_endpoint": "http://storage:4443"} |
| 21 | + def __init__(self, project_id: str, use_fake_gcs_server: bool): |
| 22 | + self.project_id = project_id |
| 23 | + self.use_fake_gcs_server = use_fake_gcs_server |
25 | 24 |
|
26 |
| - return storage.Client(**client_args) |
| 25 | + @cached_property |
| 26 | + def _client(self): |
| 27 | + """Google Cloud Storage client.""" |
| 28 | + client_args: dict[str, Any] = { |
| 29 | + "project": self.project_id, |
| 30 | + } |
27 | 31 |
|
| 32 | + if self.use_fake_gcs_server: |
| 33 | + client_args["client_options"] = {"api_endpoint": "http://storage:4443"} |
28 | 34 |
|
29 |
| -client = _initialize_client() |
| 35 | + return gcs.Client(**client_args) |
| 36 | + |
| 37 | + def get_bucket(self, bucket_name: BucketName) -> gcs.Bucket: |
| 38 | + """Get a GCS bucket by name. |
| 39 | +
|
| 40 | + :param bucket_name: The name of the bucket to retrieve. |
| 41 | + """ |
| 42 | + return self._client.bucket(bucket_name) |
| 43 | + |
| 44 | + def get_object(self, bucket_name: BucketName, object_name: str) -> gcs.Blob: |
| 45 | + """Get an object from a GCS bucket. |
| 46 | +
|
| 47 | + :param bucket_name: The name of the bucket containing the object. |
| 48 | + :param object_name: The name of the object to retrieve. |
| 49 | + """ |
| 50 | + bucket = self.get_bucket(bucket_name) |
| 51 | + return bucket.blob(object_name) |
| 52 | + |
| 53 | + def delete_object( |
| 54 | + self, bucket_name: BucketName, object_name: str, *, raise_if_not_found: bool = False |
| 55 | + ) -> None: |
| 56 | + """Delete an object from a GCS bucket. |
| 57 | +
|
| 58 | + :param bucket_name: The name of the bucket containing the object. |
| 59 | + :param object_name: The name of the object to delete. |
| 60 | + :param raise_if_not_found: If True, raise an exception if the object is not found. Default |
| 61 | + is False. |
| 62 | + """ |
| 63 | + bucket = self.get_bucket(bucket_name) |
| 64 | + try: |
| 65 | + bucket.delete_blob(object_name) |
| 66 | + except gce.NotFound as e: |
| 67 | + if raise_if_not_found: |
| 68 | + raise e |
| 69 | + |
| 70 | + def get_signed_upload_url( |
| 71 | + self, |
| 72 | + bucket_name: BucketName, |
| 73 | + object_name: str, |
| 74 | + *, |
| 75 | + expiration: int = 15, |
| 76 | + content_type: str | None = None, |
| 77 | + ) -> SignedUrl: |
| 78 | + """Get a signed URL for uploading to an object to a GCS bucket. |
| 79 | +
|
| 80 | + :param bucket_name: The name of the bucket that will contain the object. |
| 81 | + :param object_name: The name of the object. |
| 82 | + :param expiration: The expiration time for the signed URL in minutes. Default is 15 minutes. |
| 83 | + :param content_type: The content type of the object being uploaded. |
| 84 | + """ |
| 85 | + blob = self.get_object(bucket_name, object_name) |
| 86 | + expiration_delta = timedelta(minutes=expiration) |
| 87 | + expiration_time = datetime.now(timezone.utc) + expiration_delta |
| 88 | + |
| 89 | + url = blob.generate_signed_url( |
| 90 | + version="v4", |
| 91 | + expiration=expiration_delta, |
| 92 | + method="PUT", |
| 93 | + content_type=content_type, |
| 94 | + ) |
| 95 | + |
| 96 | + if self.use_fake_gcs_server: |
| 97 | + # If using a fake GCS server, we need to adjust the URL to point localhost instead of |
| 98 | + # the docker-compose service name. |
| 99 | + url = url.replace("//storage:", "//localhost:") |
| 100 | + |
| 101 | + return SignedUrl(url=url, expiration=expiration_time, object_name=blob.name) |
| 102 | + |
| 103 | + def get_signed_download_url( |
| 104 | + self, bucket_name: BucketName, object_name: str, *, expiration: int = 15 |
| 105 | + ) -> SignedUrl: |
| 106 | + """Get a signed URL for downloading an object from a GCS bucket. |
| 107 | +
|
| 108 | + :param bucket_name: The name of the bucket containing the object. |
| 109 | + :param object_name: The name of the object to download. |
| 110 | + :param expiration: The expiration time for the signed URL in minutes. Default is 15 minutes. |
| 111 | + """ |
| 112 | + expiration_delta = timedelta(minutes=expiration) |
| 113 | + expiration_time = datetime.now(timezone.utc) + expiration_delta |
| 114 | + blob = self.get_object(bucket_name, object_name) |
| 115 | + url = blob.generate_signed_url( |
| 116 | + version="v4", |
| 117 | + expiration=expiration_delta, |
| 118 | + method="GET", |
| 119 | + ) |
| 120 | + |
| 121 | + if self.use_fake_gcs_server: |
| 122 | + # If using a fake GCS server, we need to adjust the URL to point localhost instead of |
| 123 | + # the docker-compose service name. |
| 124 | + url = url.replace("//storage:", "//localhost:") |
| 125 | + |
| 126 | + return SignedUrl( |
| 127 | + url=url, |
| 128 | + object_name=blob.name, |
| 129 | + expiration=expiration_time, |
| 130 | + ) |
| 131 | + |
| 132 | + |
| 133 | +storage = Storage( |
| 134 | + project_id=settings.gcs_project_id, |
| 135 | + use_fake_gcs_server=settings.use_fake_gcs_server, |
| 136 | +) |
0 commit comments