|
| 1 | +import asyncio |
| 2 | +from typing import Optional, List, Iterable |
| 3 | + |
| 4 | +from absl import logging |
| 5 | + |
| 6 | +from google.cloud.pubsublite.internal.wire.committer import Committer |
| 7 | +from google.cloud.pubsublite.internal.wire.retrying_connection import RetryingConnection, ConnectionFactory |
| 8 | +from google.api_core.exceptions import FailedPrecondition, GoogleAPICallError |
| 9 | +from google.cloud.pubsublite.internal.wire.connection_reinitializer import ConnectionReinitializer |
| 10 | +from google.cloud.pubsublite.internal.wire.connection import Connection |
| 11 | +from google.cloud.pubsublite.internal.wire.serial_batcher import SerialBatcher, BatchTester |
| 12 | +from google.cloud.pubsublite_v1 import Cursor |
| 13 | +from google.cloud.pubsublite_v1.types import StreamingCommitCursorRequest, StreamingCommitCursorResponse, InitialCommitCursorRequest |
| 14 | +from google.cloud.pubsublite.internal.wire.work_item import WorkItem |
| 15 | + |
| 16 | + |
| 17 | +class CommitterImpl(Committer, ConnectionReinitializer[StreamingCommitCursorRequest, StreamingCommitCursorResponse], BatchTester[Cursor]): |
| 18 | + _initial: InitialCommitCursorRequest |
| 19 | + _flush_seconds: float |
| 20 | + _connection: RetryingConnection[StreamingCommitCursorRequest, StreamingCommitCursorResponse] |
| 21 | + |
| 22 | + _batcher: SerialBatcher[Cursor, None] |
| 23 | + |
| 24 | + _outstanding_commits: List[List[WorkItem[Cursor, None]]] |
| 25 | + |
| 26 | + _receiver: Optional[asyncio.Future] |
| 27 | + _flusher: Optional[asyncio.Future] |
| 28 | + |
| 29 | + def __init__(self, initial: InitialCommitCursorRequest, flush_seconds: float, |
| 30 | + factory: ConnectionFactory[StreamingCommitCursorRequest, StreamingCommitCursorResponse]): |
| 31 | + self._initial = initial |
| 32 | + self._flush_seconds = flush_seconds |
| 33 | + self._connection = RetryingConnection(factory, self) |
| 34 | + self._batcher = SerialBatcher(self) |
| 35 | + self._outstanding_commits = [] |
| 36 | + self._receiver = None |
| 37 | + self._flusher = None |
| 38 | + |
| 39 | + async def __aenter__(self): |
| 40 | + await self._connection.__aenter__() |
| 41 | + |
| 42 | + def _start_loopers(self): |
| 43 | + assert self._receiver is None |
| 44 | + assert self._flusher is None |
| 45 | + self._receiver = asyncio.ensure_future(self._receive_loop()) |
| 46 | + self._flusher = asyncio.ensure_future(self._flush_loop()) |
| 47 | + |
| 48 | + async def _stop_loopers(self): |
| 49 | + if self._receiver: |
| 50 | + self._receiver.cancel() |
| 51 | + await self._receiver |
| 52 | + self._receiver = None |
| 53 | + if self._flusher: |
| 54 | + self._flusher.cancel() |
| 55 | + await self._flusher |
| 56 | + self._flusher = None |
| 57 | + |
| 58 | + def _handle_response(self, response: StreamingCommitCursorResponse): |
| 59 | + if "commit" not in response: |
| 60 | + self._connection.fail(FailedPrecondition("Received an invalid subsequent response on the commit stream.")) |
| 61 | + if response.commit.acknowledged_commits > len(self._outstanding_commits): |
| 62 | + self._connection.fail( |
| 63 | + FailedPrecondition("Received a commit response on the stream with no outstanding commits.")) |
| 64 | + for _ in range(response.commit.acknowledged_commits): |
| 65 | + batch = self._outstanding_commits.pop(0) |
| 66 | + for item in batch: |
| 67 | + item.response_future.set_result(None) |
| 68 | + |
| 69 | + async def _receive_loop(self): |
| 70 | + try: |
| 71 | + while True: |
| 72 | + response = await self._connection.read() |
| 73 | + self._handle_response(response) |
| 74 | + except asyncio.CancelledError: |
| 75 | + return |
| 76 | + |
| 77 | + async def _flush_loop(self): |
| 78 | + try: |
| 79 | + while True: |
| 80 | + await asyncio.sleep(self._flush_seconds) |
| 81 | + await self._flush() |
| 82 | + except asyncio.CancelledError: |
| 83 | + return |
| 84 | + |
| 85 | + async def __aexit__(self, exc_type, exc_val, exc_tb): |
| 86 | + if self._connection.error(): |
| 87 | + self._fail_if_retrying_failed() |
| 88 | + else: |
| 89 | + await self._flush() |
| 90 | + await self._connection.__aexit__(exc_type, exc_val, exc_tb) |
| 91 | + |
| 92 | + def _fail_if_retrying_failed(self): |
| 93 | + if self._connection.error(): |
| 94 | + for batch in self._outstanding_commits: |
| 95 | + for item in batch: |
| 96 | + item.response_future.set_exception(self._connection.error()) |
| 97 | + |
| 98 | + async def _flush(self): |
| 99 | + batch = self._batcher.flush() |
| 100 | + if not batch: |
| 101 | + return |
| 102 | + self._outstanding_commits.append(batch) |
| 103 | + req = StreamingCommitCursorRequest() |
| 104 | + req.commit.cursor = batch[-1].request |
| 105 | + try: |
| 106 | + await self._connection.write(req) |
| 107 | + except GoogleAPICallError as e: |
| 108 | + logging.debug(f"Failed commit on stream: {e}") |
| 109 | + self._fail_if_retrying_failed() |
| 110 | + |
| 111 | + async def commit(self, cursor: Cursor) -> None: |
| 112 | + future = self._batcher.add(cursor) |
| 113 | + if self._batcher.should_flush(): |
| 114 | + # always returns false currently, here in case this changes in the future. |
| 115 | + await self._flush() |
| 116 | + await future |
| 117 | + |
| 118 | + async def reinitialize(self, connection: Connection[StreamingCommitCursorRequest, StreamingCommitCursorResponse]): |
| 119 | + await self._stop_loopers() |
| 120 | + await connection.write(StreamingCommitCursorRequest(initial=self._initial)) |
| 121 | + response = await connection.read() |
| 122 | + if "initial" not in response: |
| 123 | + self._connection.fail(FailedPrecondition("Received an invalid initial response on the publish stream.")) |
| 124 | + if self._outstanding_commits: |
| 125 | + # Roll up outstanding commits |
| 126 | + rollup: List[WorkItem[Cursor, None]] = [] |
| 127 | + for batch in self._outstanding_commits: |
| 128 | + for item in batch: |
| 129 | + rollup.append(item) |
| 130 | + self._outstanding_commits = [rollup] |
| 131 | + req = StreamingCommitCursorRequest() |
| 132 | + req.commit.cursor = rollup[-1].request |
| 133 | + await connection.write(req) |
| 134 | + self._start_loopers() |
| 135 | + |
| 136 | + def test(self, requests: Iterable[Cursor]) -> bool: |
| 137 | + # There is no bound on the number of outstanding cursors. |
| 138 | + return False |
0 commit comments