-
Notifications
You must be signed in to change notification settings - Fork 12
/
multiplexed_async_publisher_client.py
75 lines (62 loc) · 2.49 KB
/
multiplexed_async_publisher_client.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
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Callable, Union, Mapping
from google.api_core.exceptions import GoogleAPICallError
from google.cloud.pubsublite.cloudpubsub.internal.client_multiplexer import (
AsyncClientMultiplexer,
)
from google.cloud.pubsublite.cloudpubsub.internal.single_publisher import (
AsyncSinglePublisher,
)
from google.cloud.pubsublite.cloudpubsub.publisher_client_interface import (
AsyncPublisherClientInterface,
)
from google.cloud.pubsublite.types import TopicPath
from overrides import overrides
AsyncPublisherFactory = Callable[[TopicPath], AsyncSinglePublisher]
class MultiplexedAsyncPublisherClient(AsyncPublisherClientInterface):
_publisher_factory: AsyncPublisherFactory
_multiplexer: AsyncClientMultiplexer[TopicPath, AsyncSinglePublisher]
def __init__(self, publisher_factory: AsyncPublisherFactory):
self._publisher_factory = publisher_factory
self._multiplexer = AsyncClientMultiplexer()
@overrides
async def publish(
self,
topic: Union[TopicPath, str],
data: bytes,
ordering_key: str = "",
**attrs: Mapping[str, str]
) -> str:
if isinstance(topic, str):
topic = TopicPath.parse(topic)
async def create_and_open():
client = self._publisher_factory(topic)
await client.__aenter__()
return client
publisher = await self._multiplexer.get_or_create(topic, create_and_open)
try:
return await publisher.publish(
data=data, ordering_key=ordering_key, **attrs
)
except GoogleAPICallError as e:
await self._multiplexer.try_erase(topic, publisher)
raise e
@overrides
async def __aenter__(self):
await self._multiplexer.__aenter__()
return self
@overrides
async def __aexit__(self, exc_type, exc_value, traceback):
await self._multiplexer.__aexit__(exc_type, exc_value, traceback)