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 @@ -441,6 +441,31 @@ def _on_open_error(self, exc):
self._created_generation = True
self.generation = redirect_proto.generation

async def _abort_stream(self) -> None:
"""Best-effort close of the current stream, then marks the writer closed."""
if self.write_obj_stream is not None and self.write_obj_stream.is_stream_open:
try:
await self.write_obj_stream.close()
except Exception as e:
logger.debug(f"Closing the write stream resulted in: {e}")
self._is_stream_open = False

def _raise_if_offset_lost(self, expected_offset: Optional[int]) -> None:
"""Raises DataLoss if a reconnect reports fewer bytes than were sent.

``DataLoss`` is not retryable, so ``close()`` and ``finalize()`` fail
fast instead of reopening the stream until the retry deadline.
"""
if (
self.offset is not None
and expected_offset is not None
and self.offset != expected_offset
):
raise exceptions.DataLoss(
f"Unrecoverable data loss during reconnect. "
f"Expected offset {expected_offset}, got {self.offset}."
)

def _merge_retry_policy(
self, retry_policy: Optional[AsyncRetry] = None
) -> AsyncRetry:
Expand Down Expand Up @@ -553,10 +578,13 @@ async def append(
calling `self.append` will append bytes at the end of the current size
ie. `self.offset` bytes relative to the begining of the object.

This method sends the provided `data` to the GCS server in chunks.
and persists data in GCS at every `_DEFAULT_FLUSH_INTERVAL_BYTES` bytes
or at the last chunk whichever is earlier. Persisting is done by setting
`flush=True` on request.
This method sends the provided `data` to the GCS server in chunks and
requests persistence (``flush=True``) each time ``flush_interval``
bytes have been sent since the last flush. Bytes after the last
``flush_interval`` boundary are only guaranteed durable after
``flush()`` or ``close()``. If the stream breaks before then and the
server lost them, a later ``append()`` raises
:class:`~google.api_core.exceptions.DataLoss`.

:type data: bytes
:param data: The bytes to append to the object.
Expand All @@ -571,6 +599,9 @@ async def append(
:param enable_checksum: (Optional) If True, calculates and checks checksums for each chunk. Defaults to True.

:raises ValueError: If the stream is not open.
:raises google.api_core.exceptions.DataLoss: If reconnecting after a
stream failure reveals that unpersisted bytes from an earlier
``append()`` call were lost.
Comment thread
Yonghui-Lee marked this conversation as resolved.
Resolved
"""
if not self._is_stream_open:
raise ValueError("Stream is not open. Call open() before append().")
Expand Down Expand Up @@ -618,15 +649,22 @@ async def generator():

self._is_stream_open = False
await self.open(metadata=current_metadata)
self.bytes_appended_since_last_flush = 0

if (self.persisted_size or 0) < write_state.initial_offset:
# Close the reopened stream so a later close() can't
# finalize the truncated object.
await self._abort_stream()
raise exceptions.DataLoss(
f"Unrecoverable data loss during reconnect. "
f"Expected persisted_size >= {write_state.initial_offset}, "
f"got {self.persisted_size}."
)
Comment thread
Yonghui-Lee marked this conversation as resolved.
Resolved
Comment thread
Yonghui-Lee marked this conversation as resolved.
Resolved

write_state.persisted_size = self.persisted_size
write_state.write_handle = self.write_handle
write_state.routing_token = None

write_state.user_buffer.seek(write_state.persisted_size)
write_state.bytes_sent = write_state.persisted_size
write_state.bytes_since_last_flush = 0
self.bytes_appended_since_last_flush = 0
write_state.reset_to_persisted()

requests = strategy.generate_requests(state)

Expand Down Expand Up @@ -662,15 +700,14 @@ async def generator():
buffer,
self.flush_interval,
enable_checksum=enable_checksum,
initial_offset=self.offset or 0,
)
write_state.write_handle = self.write_handle
write_state.persisted_size = self.persisted_size
# offset is set during `open()` call.
write_state.bytes_sent = self.offset or 0
write_state.bytes_since_last_flush = self.bytes_appended_since_last_flush

retry_manager = _BidiStreamRetryManager(
_WriteResumptionStrategy(),
strategy,
lambda r, s: send_and_recv_generator(r, s, metadata),
)
await retry_manager.execute({"write_state": write_state}, retry_policy)
Expand Down Expand Up @@ -753,10 +790,16 @@ async def close(
:type retry_policy: :class:`~google.api_core.retry_async.AsyncRetry`
:param retry_policy: (Optional) The retry policy to use for the operation.

rtype: Union[int, _storage_v2.Object]
returns: Updated `self.persisted_size` by default after closing the
bidi-gRPC stream. However, if `finalize_on_close=True` is passed,
returns the finalized object resource.
:rtype: Union[int, _storage_v2.Object]
:returns: By default, ``self.persisted_size``. This is the size the
server last confirmed as persisted, from the most recent
``flush()``, ``state_lookup()`` or flush inside ``append()``.
Closing persists any bytes appended after that, but this value is
not refreshed, so it can be smaller than the object size by up to
``flush_interval`` bytes. For the exact size, call ``flush()``
before ``close()``, or use ``self.offset``. If
``finalize_on_close=True`` is passed, returns the finalized object
resource, whose ``size`` is exact.

:raises ValueError: If the stream is not open (i.e., `open()` has not
been called).
Expand All @@ -765,6 +808,8 @@ async def close(
:raises google.api_core.exceptions.InvalidArgument: If the provided
full_object_checksum does not match the checksum computed by the
server.
:raises google.api_core.exceptions.DataLoss: If reconnecting after a
stream failure reveals that the server lost appended bytes.

"""
if not self._is_stream_open:
Expand Down Expand Up @@ -797,22 +842,16 @@ async def _do_close():
)
self._is_stream_open = False
await self.open()
if (
self.offset is not None
and expected_offset is not None
and self.offset != expected_offset
):
raise exceptions.InternalServerError(
f"Unrecoverable data loss during reconnect. Expected offset {expected_offset}, got {self.offset}"
)
self._raise_if_offset_lost(expected_offset)

await self.write_obj_stream.close()
Comment thread
Yonghui-Lee marked this conversation as resolved.
Resolved
return self.persisted_size

try:
return await retry_policy(_do_close)()
finally:
self._is_stream_open = False
# Closes a stream reopened by a retry that then failed.
await self._abort_stream()

async def finalize(
self,
Expand Down Expand Up @@ -854,6 +893,8 @@ async def finalize(
:raises google.api_core.exceptions.InvalidArgument: If the provided
full_object_checksum does not match the checksum computed by the
server.
:raises google.api_core.exceptions.DataLoss: If reconnecting after a
stream failure reveals that the server lost appended bytes.
"""
if not self._is_stream_open:
raise ValueError("Stream is not open. Call open() before finalize().")
Expand Down Expand Up @@ -890,14 +931,7 @@ async def _do_finalize():
)
self._is_stream_open = False
await self.open()
if (
self.offset is not None
and expected_offset is not None
and self.offset != expected_offset
):
raise exceptions.InternalServerError(
f"Unrecoverable data loss during reconnect. Expected offset {expected_offset}, got {self.offset}"
)
self._raise_if_offset_lost(expected_offset)

await self.write_obj_stream.send(finalize_req)
response = await self.write_obj_stream.recv()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ class _WriteState:

:type flush_interval: int
:param flush_interval: The flush interval at which the data is flushed.

:type enable_checksum: bool
:param enable_checksum: Whether to compute CRC32C checksums for chunks.

:type initial_offset: int
:param initial_offset: The object byte offset corresponding to position 0 of
``user_buffer``.
"""

def __init__(
Expand All @@ -45,23 +52,32 @@ def __init__(
user_buffer: IO[bytes],
flush_interval: int,
enable_checksum: bool = True,
initial_offset: int = 0,
):
self.chunk_size = chunk_size
self.user_buffer = user_buffer
self.initial_offset: int = initial_offset
self.persisted_size: int = 0
# Bytes sent to the server (it may be unpersisted),
# i.e. latest object size = persisted_size + some more bytes.
# Please note: these bytes are sent from client to server, server might have also received it.
# but might not have persisted it yet (may be in memory buffer on server side).
# This variable is same as `offset variable` in the instance of `AppendableObjectWriter`.
self.bytes_sent: int = 0
self.bytes_sent: int = initial_offset
self.bytes_since_last_flush: int = 0
self.flush_interval: int = flush_interval
self.write_handle: Union[bytes, storage_type.BidiWriteHandle, None] = None
self.routing_token: Optional[str] = None
self.is_finalized: bool = False
self.enable_checksum: bool = enable_checksum

def reset_to_persisted(self) -> None:
"""Rewinds user_buffer and byte counters to persisted_size."""
persisted_offset = max(self.persisted_size or 0, self.initial_offset)
self.user_buffer.seek(persisted_offset - self.initial_offset)
self.bytes_sent = persisted_offset
self.bytes_since_last_flush = 0


class _WriteResumptionStrategy(_BaseResumptionStrategy):
"""The concrete resumption strategy for bidi writes."""
Expand Down Expand Up @@ -150,6 +166,4 @@ async def recover_state_on_failure(

# We must assume any data sent beyond 'persisted_size' was lost.
# Reset the user buffer to the last known good byte confirmed by the server.
write_state.user_buffer.seek(write_state.persisted_size)
write_state.bytes_sent = write_state.persisted_size
write_state.bytes_since_last_flush = 0
write_state.reset_to_persisted()
Original file line number Diff line number Diff line change
Expand Up @@ -381,8 +381,63 @@ def test_write_state_initialization(self):
buffer = io.BytesIO(b"test")
ws = _WriteState(chunk_size=10, user_buffer=buffer, flush_interval=100)

assert ws.initial_offset == 0
assert ws.persisted_size == 0
assert ws.bytes_sent == 0
assert ws.bytes_since_last_flush == 0
assert ws.flush_interval == 100
assert not ws.is_finalized

@pytest.mark.parametrize(
"initial_offset, persisted_size, expected_tell, expected_bytes_sent, expected_chunks",
[
# Partial persistence inside current buffer: seek to persisted_size - initial_offset.
(20, 24, 4, 24, [(24, b"efgh"), (28, b"ij")]),
# Cached persisted_size below initial_offset before stream reopen: clamp to 0.
(20, 0, 0, 20, [(20, b"abcd"), (24, b"efgh"), (28, b"ij")]),
# persisted_size exactly at initial_offset: resend the whole buffer.
(20, 20, 0, 20, [(20, b"abcd"), (24, b"efgh"), (28, b"ij")]),
# Whole buffer persisted before the error: nothing left to send.
(20, 30, 10, 30, []),
# Stale cached persisted_size from an unaligned prior append: clamp to 0.
(20, 12, 0, 20, [(20, b"abcd"), (24, b"efgh"), (28, b"ij")]),
],
)
@pytest.mark.asyncio
async def test_recover_state_on_failure_with_initial_offset(
self,
strategy,
initial_offset,
persisted_size,
expected_tell,
expected_bytes_sent,
expected_chunks,
):
"""Verify recovery rewinds user_buffer relative to initial_offset."""
user_buffer = io.BytesIO(b"abcdefghij")
write_state = _WriteState(
chunk_size=4,
user_buffer=user_buffer,
flush_interval=100,
initial_offset=initial_offset,
)
assert write_state.bytes_sent == initial_offset

write_state.bytes_sent = initial_offset + 8
write_state.persisted_size = persisted_size
write_state.bytes_since_last_flush = 8
user_buffer.seek(8)

state = {"write_state": write_state}
await strategy.recover_state_on_failure(
exceptions.ServiceUnavailable("busy"), state
)

assert user_buffer.tell() == expected_tell
assert write_state.bytes_sent == expected_bytes_sent
assert write_state.bytes_since_last_flush == 0

requests = strategy.generate_requests(state)
assert [
(req.write_offset, req.checksummed_data.content) for req in requests
] == expected_chunks
Loading
Loading