Skip to content
Open
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 @@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
import logging
from typing import List, Optional, Tuple

import grpc
Expand All @@ -25,6 +27,8 @@
)
from google.cloud.storage.asyncio.async_grpc_client import AsyncGrpcClient

logger = logging.getLogger(__name__)


class _AsyncWriteObjectStream(_AsyncAbstractObjectStream):
"""Class representing a gRPC bidi-stream for writing data from a GCS
Expand Down Expand Up @@ -168,8 +172,14 @@ async def open(self, metadata: Optional[List[Tuple[str, str]]] = None) -> None:
metadata=final_metadata,
)

await self.socket_like_rpc.open() # this is actually 1 send
response = await self.socket_like_rpc.recv()
try:
await self.socket_like_rpc.open() # this is actually 1 send
response = await self.socket_like_rpc.recv()
except (asyncio.CancelledError, Exception):
# The open failed, for example on a redirect or a failed
# precondition. Close the RPC so its request task doesn't leak.
await self._close_socket_like_rpc()
raise
self._is_stream_open = True

if response.persisted_size:
Expand All @@ -187,6 +197,12 @@ async def open(self, metadata: Optional[List[Tuple[str, str]]] = None) -> None:
if response.write_handle:
self.write_handle = response.write_handle

async def _close_socket_like_rpc(self) -> None:
try:
await self.socket_like_rpc.close()
except Exception as exc:
logger.debug("Error while closing the write bidi-gRPC stream: %s", exc)

async def close(self) -> None:
"""Closes the bidi-gRPC connection."""
if not self._is_stream_open:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
import datetime
import unittest.mock as mock
from unittest.mock import AsyncMock, MagicMock

import grpc
import pytest
from google.api_core import exceptions

from google.cloud import _storage_v2
from google.cloud.storage import Blob, Bucket
Expand Down Expand Up @@ -294,6 +296,53 @@ async def test_open_already_open_raises(self, mock_client):
with pytest.raises(ValueError, match="already open"):
await stream.open()

@mock.patch("google.cloud.storage.asyncio.async_write_object_stream.AsyncBidiRpc")
@pytest.mark.asyncio
@pytest.mark.parametrize("failing_call", ["open", "recv"])
@pytest.mark.parametrize(
"error",
[
exceptions.Aborted("redirect"),
exceptions.FailedPrecondition("generation mismatch"),
asyncio.CancelledError(),
],
ids=["aborted", "failed_precondition", "cancelled"],
)
async def test_open_failure_closes_rpc(
self, mock_rpc_cls, mock_client, failing_call, error
):
mock_rpc = mock_rpc_cls.return_value
mock_rpc.open = AsyncMock()
mock_rpc.recv = AsyncMock()
mock_rpc.close = AsyncMock()
getattr(mock_rpc, failing_call).side_effect = error

stream = _AsyncWriteObjectStream(mock_client, BUCKET, OBJECT)
with pytest.raises(type(error)):
await stream.open()

mock_rpc.close.assert_awaited_once()
assert not stream.is_stream_open
if failing_call == "open":
mock_rpc.recv.assert_not_awaited()

@mock.patch("google.cloud.storage.asyncio.async_write_object_stream.AsyncBidiRpc")
@pytest.mark.asyncio
async def test_open_failure_keeps_error_when_close_fails(
self, mock_rpc_cls, mock_client
):
mock_rpc = mock_rpc_cls.return_value
mock_rpc.open = AsyncMock()
mock_rpc.recv = AsyncMock(side_effect=exceptions.Aborted("redirect"))
mock_rpc.close = AsyncMock(side_effect=RuntimeError("close failed"))

stream = _AsyncWriteObjectStream(mock_client, BUCKET, OBJECT)
with pytest.raises(exceptions.Aborted, match="redirect"):
await stream.open()

mock_rpc.close.assert_awaited_once()
assert not stream.is_stream_open

# -------------------------------------------------------------------------
# Send & Recv & Close Tests
# -------------------------------------------------------------------------
Expand Down
Loading