-
Notifications
You must be signed in to change notification settings - Fork 12
/
gapic_connection.py
82 lines (63 loc) · 2.61 KB
/
gapic_connection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from typing import AsyncIterator, TypeVar, Optional, Callable, AsyncIterable, Awaitable
import asyncio
from google.api_core.exceptions import GoogleAPICallError, FailedPrecondition
from google.cloud.pubsublite.internal.wire.connection import (
Connection,
Request,
Response,
ConnectionFactory,
)
from google.cloud.pubsublite.internal.wire.work_item import WorkItem
from google.cloud.pubsublite.internal.wire.permanent_failable import PermanentFailable
T = TypeVar("T")
class GapicConnection(
Connection[Request, Response], AsyncIterator[Request], PermanentFailable
):
"""A Connection wrapping a gapic AsyncIterator[Request/Response] pair."""
_write_queue: "asyncio.Queue[WorkItem[Request]]"
_response_it: Optional[AsyncIterator[Response]]
def __init__(self):
super().__init__()
self._write_queue = asyncio.Queue(maxsize=1)
def set_response_it(self, response_it: AsyncIterator[Response]):
self._response_it = response_it
async def write(self, request: Request) -> None:
item = WorkItem(request)
await self.await_unless_failed(self._write_queue.put(item))
await self.await_unless_failed(item.response_future)
async def read(self) -> Response:
try:
return await self.await_unless_failed(self._response_it.__anext__())
except StopAsyncIteration:
self.fail(FailedPrecondition("Server sent unprompted half close."))
except GoogleAPICallError as e:
self.fail(e)
raise self.error()
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_value, traceback) -> None:
pass
async def __anext__(self) -> Request:
item: WorkItem[Request] = await self.await_unless_failed(
self._write_queue.get()
)
item.response_future.set_result(None)
return item.request
def __aiter__(self) -> AsyncIterator[Response]:
return self
class GapicConnectionFactory(ConnectionFactory[Request, Response]):
"""A ConnectionFactory that produces GapicConnections."""
_producer = Callable[[AsyncIterator[Request]], Awaitable[AsyncIterable[Response]]]
def __init__(
self,
producer: Callable[
[AsyncIterator[Request]], Awaitable[AsyncIterable[Response]]
],
):
self._producer = producer
async def new(self) -> Connection[Request, Response]:
conn = GapicConnection[Request, Response]()
response_fut = self._producer(conn)
response_iterable = await response_fut
conn.set_response_it(response_iterable.__aiter__())
return conn