|
| 1 | +# poc_bidi_retry_final.py |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from unittest import mock |
| 5 | +from google.api_core import exceptions |
| 6 | +from google.api_core.retry_async import AsyncRetry |
| 7 | + |
| 8 | +# Assuming the retry components are in these locations |
| 9 | +# In a real scenario, these would be imported from the library |
| 10 | +from google.cloud.storage._experimental.asyncio.retry.bidi_stream_retry_manager import ( |
| 11 | + _BidiStreamRetryManager, |
| 12 | +) |
| 13 | +from google.cloud.storage._experimental.asyncio.retry.base_strategy import ( |
| 14 | + _BaseResumptionStrategy, |
| 15 | +) |
| 16 | + |
| 17 | + |
| 18 | +class ReadResumptionStrategy(_BaseResumptionStrategy): |
| 19 | + """ |
| 20 | + A concrete implementation of the strategy for bidi reads. |
| 21 | + This is a simplified version for the POC. |
| 22 | + """ |
| 23 | + |
| 24 | + def __init__(self): |
| 25 | + self.state = {"offset": 0, "remaining_bytes": float("inf")} |
| 26 | + |
| 27 | + def generate_requests(self, state): |
| 28 | + print(f"[Strategy] Generating request with state: {state}") |
| 29 | + # In a real scenario, this yields ReadObjectRequest protos |
| 30 | + yield {"read_offset": state["offset"]} |
| 31 | + |
| 32 | + def handle_response(self, response): |
| 33 | + # In a real scenario, this is a ReadObjectResponse proto |
| 34 | + chunk = response.get("chunk", b"") |
| 35 | + self.state["offset"] += len(chunk) |
| 36 | + print(f"[Strategy] Handled response, new state: {self.state}") |
| 37 | + return response |
| 38 | + |
| 39 | + async def recover_state_on_failure(self, error, state): |
| 40 | + print(f"[Strategy] Recovering state from error: {error}. Current state: {state}") |
| 41 | + # For reads, the offset is already updated, so we just return the current state |
| 42 | + return self.state |
| 43 | + |
| 44 | + |
| 45 | +# --- Simulation Setup --- |
| 46 | + |
| 47 | +# A mock stream that fails once mid-stream |
| 48 | +ATTEMPT_COUNT = 0 |
| 49 | +STREAM_CONTENT = [ |
| 50 | + [{"chunk": b"part_one"}, {"chunk": b"part_two"}, exceptions.ServiceUnavailable("Network error")], |
| 51 | + [{"chunk": b"part_three"}, {"chunk": b"part_four"}], |
| 52 | +] |
| 53 | + |
| 54 | + |
| 55 | +async def mock_stream_opener(requests, state): |
| 56 | + """ |
| 57 | + A mock stream opener that simulates a failing and then succeeding stream. |
| 58 | + """ |
| 59 | + global ATTEMPT_COUNT |
| 60 | + print(f"\n--- Stream Attempt {ATTEMPT_COUNT + 1} ---") |
| 61 | + # Consume the request iterator (in a real scenario, this sends requests to gRPC) |
| 62 | + _ = [req for req in requests] |
| 63 | + print(f"Mock stream opened with state: {state}") |
| 64 | + |
| 65 | + content_for_this_attempt = STREAM_CONTENT[ATTEMPT_COUNT] |
| 66 | + ATTEMPT_COUNT += 1 |
| 67 | + |
| 68 | + for item in content_for_this_attempt: |
| 69 | + await asyncio.sleep(0.01) # Simulate network latency |
| 70 | + if isinstance(item, Exception): |
| 71 | + print(f"!!! Stream yielding an error: {item} !!!") |
| 72 | + raise item |
| 73 | + else: |
| 74 | + print(f"Stream yielding chunk of size: {len(item.get('chunk', b''))}") |
| 75 | + yield item |
| 76 | + |
| 77 | + |
| 78 | +async def main(): |
| 79 | + """ |
| 80 | + Main function to run the POC. |
| 81 | + """ |
| 82 | + print("--- Starting Bidi Read Retry POC ---") |
| 83 | + |
| 84 | + # 1. Define a retry policy |
| 85 | + retry_policy = AsyncRetry( |
| 86 | + predicate=lambda e: isinstance(e, exceptions.ServiceUnavailable), |
| 87 | + deadline=30.0, |
| 88 | + initial=0.1, # Start with a short wait |
| 89 | + ) |
| 90 | + |
| 91 | + # 2. Instantiate the strategy and retry manager |
| 92 | + strategy = ReadResumptionStrategy() |
| 93 | + retry_manager = _BidiStreamRetryManager( |
| 94 | + strategy=strategy, stream_opener=mock_stream_opener |
| 95 | + ) |
| 96 | + |
| 97 | + # 3. Execute the operation |
| 98 | + print("\nExecuting the retry manager...") |
| 99 | + final_stream_iterator = await retry_manager.execute( |
| 100 | + initial_state={"offset": 0}, retry_policy=retry_policy |
| 101 | + ) |
| 102 | + |
| 103 | + # 4. Consume the final, successful stream |
| 104 | + all_content = b"" |
| 105 | + print("\n--- Consuming Final Stream ---") |
| 106 | + async for response in final_stream_iterator: |
| 107 | + chunk = response.get("chunk", b"") |
| 108 | + all_content += chunk |
| 109 | + print(f"Received chunk: {chunk.decode()}. Total size: {len(all_content)}") |
| 110 | + |
| 111 | + print("\n--- POC Finished ---") |
| 112 | + print(f"Final downloaded content: {all_content.decode()}") |
| 113 | + print(f"Total attempts made: {ATTEMPT_COUNT}") |
| 114 | + assert all_content == b"part_onepart_twopart_threepart_four" |
| 115 | + assert ATTEMPT_COUNT == 2 |
| 116 | + print("\nAssertion passed: Content correctly assembled across retries.") |
| 117 | + |
| 118 | + |
| 119 | +if __name__ == "__main__": |
| 120 | + asyncio.run(main()) |
0 commit comments