forked from hazelcast/hazelcast-python-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.py
More file actions
76 lines (65 loc) · 2.78 KB
/
manager.py
File metadata and controls
76 lines (65 loc) · 2.78 KB
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
import asyncio
import typing
from hazelcast.internal.asyncio_proxy.vector_collection import (
VectorCollection,
create_vector_collection_proxy,
)
from hazelcast.protocol.codec import client_create_proxy_codec, client_destroy_proxy_codec
from hazelcast.internal.asyncio_invocation import Invocation
from hazelcast.internal.asyncio_proxy.base import Proxy
from hazelcast.internal.asyncio_proxy.map import create_map_proxy
from hazelcast.util import to_list
MAP_SERVICE = "hz:impl:mapService"
VECTOR_SERVICE = "hz:service:vector"
_proxy_init: typing.Dict[
str,
typing.Callable[[str, str, typing.Any], typing.Coroutine[typing.Any, typing.Any, typing.Any]],
] = {
MAP_SERVICE: create_map_proxy,
VECTOR_SERVICE: create_vector_collection_proxy,
}
class ProxyManager:
def __init__(self, context):
self._context = context
self._proxies = {}
async def get_or_create(self, service_name, name, create_on_remote=True):
ns = (service_name, name)
proxy = self._proxies.get(ns)
if proxy is not None:
if isinstance(proxy, asyncio.Future):
return await proxy
return proxy
# allocate the proxy slot, so a task that tries to access the same proxy knows it's being created
fut = asyncio.get_running_loop().create_future()
self._proxies[ns] = fut
try:
proxy = await self._create_proxy(service_name, name, create_on_remote)
except BaseException as e:
self._proxies.pop(ns, None)
fut.set_exception(e)
raise
# replace the placeholder with the proxy
self._proxies[ns] = proxy
fut.set_result(proxy)
return proxy
async def _create_proxy(self, service_name, name, create_on_remote) -> Proxy:
if create_on_remote:
request = client_create_proxy_codec.encode_request(name, service_name)
invocation = Invocation(request)
invocation_service = self._context.invocation_service
await invocation_service.ainvoke(invocation)
return await _proxy_init[service_name](service_name, name, self._context)
async def destroy_proxy(self, service_name, name, destroy_on_remote=True):
ns = (service_name, name)
try:
self._proxies.pop(ns)
if destroy_on_remote:
request = client_destroy_proxy_codec.encode_request(name, service_name)
invocation = Invocation(request)
invocation_service = self._context.invocation_service
await invocation_service.ainvoke(invocation)
return True
except KeyError:
return False
def get_distributed_objects(self):
return to_list(v for v in self._proxies.values() if not isinstance(v, asyncio.Future))