|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from typing import Any, Dict, IO, Iterable, Optional, Union |
| 16 | + |
| 17 | +import google_crc32c |
| 18 | +from google.cloud._storage_v2.types import storage as storage_type |
| 19 | +from google.cloud._storage_v2.types.storage import BidiWriteObjectRedirectedError |
| 20 | +from google.cloud.storage._experimental.asyncio.retry.base_strategy import ( |
| 21 | + _BaseResumptionStrategy, |
| 22 | +) |
| 23 | + |
| 24 | + |
| 25 | +class _WriteState: |
| 26 | + """A helper class to track the state of a single upload operation. |
| 27 | +
|
| 28 | + Attributes: |
| 29 | + spec (AppendObjectSpec): The specification for the object to write. |
| 30 | + chunk_size (int): The size of chunks to read from the buffer. |
| 31 | + user_buffer (IO[bytes]): The data source. |
| 32 | + persisted_size (int): The amount of data confirmed as persisted by the server. |
| 33 | + bytes_sent (int): The amount of data currently sent in the active stream. |
| 34 | + write_handle (bytes | BidiWriteHandle | None): The handle for the append session. |
| 35 | + routing_token (str | None): Token for routing to the correct backend. |
| 36 | + is_complete (bool): Whether the upload has finished. |
| 37 | + """ |
| 38 | + |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + spec: storage_type.AppendObjectSpec, |
| 42 | + chunk_size: int, |
| 43 | + user_buffer: IO[bytes], |
| 44 | + ): |
| 45 | + self.spec = spec |
| 46 | + self.chunk_size = chunk_size |
| 47 | + self.user_buffer = user_buffer |
| 48 | + self.persisted_size: int = 0 |
| 49 | + self.bytes_sent: int = 0 |
| 50 | + self.write_handle: Union[bytes, Any, None] = None |
| 51 | + self.routing_token: Optional[str] = None |
| 52 | + self.is_complete: bool = False |
| 53 | + |
| 54 | + |
| 55 | +class _WriteResumptionStrategy(_BaseResumptionStrategy): |
| 56 | + """The concrete resumption strategy for bidi writes.""" |
| 57 | + |
| 58 | + def generate_requests( |
| 59 | + self, state: Dict[str, Any] |
| 60 | + ) -> Iterable[storage_type.BidiWriteObjectRequest]: |
| 61 | + """Generates BidiWriteObjectRequests to resume or continue the upload. |
| 62 | +
|
| 63 | + For Appendable Objects, every stream opening should send an |
| 64 | + AppendObjectSpec. If resuming, the `write_handle` is added to that spec. |
| 65 | + """ |
| 66 | + write_state: _WriteState = state["write_state"] |
| 67 | + |
| 68 | + # Mark that we have generated the first request for this stream attempt |
| 69 | + state["first_request"] = False |
| 70 | + |
| 71 | + if write_state.write_handle: |
| 72 | + write_state.spec.write_handle = write_state.write_handle |
| 73 | + |
| 74 | + if write_state.routing_token: |
| 75 | + write_state.spec.routing_token = write_state.routing_token |
| 76 | + |
| 77 | + do_state_lookup = write_state.write_handle is not None |
| 78 | + yield storage_type.BidiWriteObjectRequest( |
| 79 | + append_object_spec=write_state.spec, state_lookup=do_state_lookup |
| 80 | + ) |
| 81 | + |
| 82 | + # The buffer should already be seeked to the correct position (persisted_size) |
| 83 | + # by the `recover_state_on_failure` method before this is called. |
| 84 | + while not write_state.is_complete: |
| 85 | + chunk = write_state.user_buffer.read(write_state.chunk_size) |
| 86 | + |
| 87 | + # End of File detection |
| 88 | + if not chunk: |
| 89 | + write_state.is_complete = True |
| 90 | + yield storage_type.BidiWriteObjectRequest( |
| 91 | + write_offset=write_state.bytes_sent, |
| 92 | + finish_write=True, |
| 93 | + ) |
| 94 | + return |
| 95 | + |
| 96 | + checksummed_data = storage_type.ChecksummedData(content=chunk) |
| 97 | + checksum = google_crc32c.Checksum(chunk) |
| 98 | + checksummed_data.crc32c = int.from_bytes(checksum.digest(), "big") |
| 99 | + |
| 100 | + request = storage_type.BidiWriteObjectRequest( |
| 101 | + write_offset=write_state.bytes_sent, |
| 102 | + checksummed_data=checksummed_data, |
| 103 | + ) |
| 104 | + write_state.bytes_sent += len(chunk) |
| 105 | + |
| 106 | + yield request |
| 107 | + |
| 108 | + def update_state_from_response( |
| 109 | + self, response: storage_type.BidiWriteObjectResponse, state: Dict[str, Any] |
| 110 | + ) -> None: |
| 111 | + """Processes a server response and updates the write state.""" |
| 112 | + write_state: _WriteState = state["write_state"] |
| 113 | + |
| 114 | + if response.persisted_size is not None: |
| 115 | + if response.persisted_size > write_state.persisted_size: |
| 116 | + write_state.persisted_size = response.persisted_size |
| 117 | + |
| 118 | + if response.write_handle: |
| 119 | + write_state.write_handle = response.write_handle |
| 120 | + |
| 121 | + if response.resource: |
| 122 | + write_state.is_complete = True |
| 123 | + write_state.persisted_size = response.resource.size |
| 124 | + |
| 125 | + async def recover_state_on_failure( |
| 126 | + self, error: Exception, state: Dict[str, Any] |
| 127 | + ) -> None: |
| 128 | + """Handles errors, specifically BidiWriteObjectRedirectedError, and rewinds state.""" |
| 129 | + write_state: _WriteState = state["write_state"] |
| 130 | + cause = getattr(error, "cause", error) |
| 131 | + |
| 132 | + # Extract routing token and potentially a new write handle. |
| 133 | + if isinstance(cause, BidiWriteObjectRedirectedError): |
| 134 | + if cause.routing_token: |
| 135 | + write_state.routing_token = cause.routing_token |
| 136 | + |
| 137 | + if hasattr(cause, "write_handle") and cause.write_handle: |
| 138 | + write_state.write_handle = cause.write_handle |
| 139 | + |
| 140 | + # We must assume any data sent beyond 'persisted_size' was lost. |
| 141 | + # Reset the user buffer to the last known good byte. |
| 142 | + write_state.user_buffer.seek(write_state.persisted_size) |
| 143 | + write_state.bytes_sent = write_state.persisted_size |
| 144 | + |
| 145 | + # Mark next pass as a retry (not the absolute first request) |
| 146 | + state["first_request"] = False |
0 commit comments