Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions hazelcast/cp.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from hazelcast.proxy.cp.atomic_long import AtomicLong
from hazelcast.proxy.cp.atomic_reference import AtomicReference
from hazelcast.proxy.cp.count_down_latch import CountDownLatch
from hazelcast.proxy.cp.cp_map import CPMap
from hazelcast.proxy.cp.fenced_lock import FencedLock
from hazelcast.proxy.cp.semaphore import SessionAwareSemaphore, SessionlessSemaphore, Semaphore
from hazelcast.util import check_true, AtomicInteger, thread_id
Expand Down Expand Up @@ -151,6 +152,25 @@ def get_semaphore(self, name: str) -> Semaphore:
"""
return self._proxy_manager.get_or_create(SEMAPHORE_SERVICE, name)

def get_map(self, name: str) -> CPMap:
"""Returns the distributed CP Map instance with given name.

The instance is created on CP Subsystem.

If no group name is given within the ``name`` argument, then the
CP Map instance will be created on the DEFAULT CP group.
If a group name is given, like ``.get_map("myMap@group1")``, the given
group will be initialized first, if not initialized already, and then
the instance will be created on this group.

Args:
name: Name of the CP Map.

Returns:
The CP Map proxy for the given name.
"""
return self._proxy_manager.get_or_create(CP_MAP_SERVICE, name)


_DEFAULT_GROUP_NAME = "default"
_METADATA_CP_GROUP_NAME = "metadata"
Expand Down Expand Up @@ -190,6 +210,7 @@ def _get_object_name_for_proxy(name):
COUNT_DOWN_LATCH_SERVICE = "hz:raft:countDownLatchService"
LOCK_SERVICE = "hz:raft:lockService"
SEMAPHORE_SERVICE = "hz:raft:semaphoreService"
CP_MAP_SERVICE = "hz:raft:mapService"


class CPProxyManager:
Expand All @@ -213,6 +234,8 @@ def get_or_create(self, service_name, proxy_name):
return self._create_fenced_lock(group_id, proxy_name, object_name)
elif service_name == SEMAPHORE_SERVICE:
return self._create_semaphore(group_id, proxy_name, object_name)
elif service_name == CP_MAP_SERVICE:
return CPMap(self._context, group_id, service_name, proxy_name, object_name)
else:
raise ValueError("Unknown service name: %s" % service_name)

Expand Down
23 changes: 23 additions & 0 deletions hazelcast/internal/asyncio_proxy/cp_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
COUNT_DOWN_LATCH_SERVICE,
SEMAPHORE_SERVICE,
LOCK_SERVICE,
CP_MAP_SERVICE,
)
from hazelcast.internal.asyncio_invocation import Invocation
from hazelcast.internal.asyncio_proxy.atomic_long import AtomicLong
from hazelcast.internal.asyncio_proxy.atomic_reference import AtomicReference
from hazelcast.internal.asyncio_proxy.countdown_latch import CountDownLatch
from hazelcast.internal.asyncio_proxy.cp_map import CPMap
from hazelcast.internal.asyncio_proxy.fenced_lock import FencedLock
from hazelcast.internal.asyncio_proxy.semaphore import (
Semaphore,
Expand Down Expand Up @@ -151,6 +153,25 @@ async def get_semaphore(self, name: str) -> Semaphore:
"""
return await self._proxy_manager.get_or_create(SEMAPHORE_SERVICE, name)

async def get_map(self, name: str) -> CPMap:
"""Returns the distributed CP Map instance with given name.

The instance is created on CP Subsystem.

If no group name is given within the ``name`` argument, then the
CP Map instance will be created on the DEFAULT CP group.
If a group name is given, like ``.get_map("myMap@group1")``, the given
group will be initialized first, if not initialized already, and then
the instance will be created on this group.

Args:
name: Name of the CP Map.

Returns:
The CP Map proxy for the given name.
"""
return await self._proxy_manager.get_or_create(CP_MAP_SERVICE, name)


class CPProxyManager:
def __init__(self, context):
Expand All @@ -173,6 +194,8 @@ async def get_or_create(self, service_name, proxy_name):
return await self._create_fenced_lock(group_id, proxy_name, object_name)
elif service_name == SEMAPHORE_SERVICE:
return await self._create_semaphore(group_id, proxy_name, object_name)
elif service_name == CP_MAP_SERVICE:
return CPMap(self._context, group_id, service_name, proxy_name, object_name)

raise ValueError("Unknown service name: %s" % service_name)

Expand Down
196 changes: 196 additions & 0 deletions hazelcast/internal/asyncio_proxy/cp_map.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
import typing

from hazelcast.internal.asyncio_proxy.cp import BaseCPProxy
from hazelcast.protocol.codec import (
cp_map_get_codec,
cp_map_put_codec,
cp_map_put_if_absent_codec,
cp_map_set_codec,
cp_map_remove_codec,
cp_map_delete_codec,
cp_map_compare_and_set_codec,
)
from hazelcast.serialization.compact import SchemaNotReplicatedError
from hazelcast.types import ElementType, KeyType
from hazelcast.util import check_not_none


class CPMap(BaseCPProxy, typing.Generic[KeyType, ElementType]):
"""A distributed, strongly-consistent key/value map.

The CP Map is part of the Hazelcast CP Subsystem and is backed by the Raft
consensus algorithm, so it provides linearizability (strong consistency)
during crash failures and network partitions. It is CP with respect to the
CAP principle: if a network partition occurs, it remains available on at
most one side of the partition.

Both keys and values must be non-``None``; passing ``None`` as a key or a
value raises an ``AssertionError`` on the client side.
"""

async def set(self, key: KeyType, value: ElementType) -> None:
"""Sets the given value for the given key.

Args:
key: The key.
value: The value to be associated with the key.
"""
check_not_none(key, "Key cannot be None")
check_not_none(value, "Value cannot be None")
try:
key_data = self._to_data(key)
value_data = self._to_data(value)
except SchemaNotReplicatedError as e:
return await self._send_schema_and_retry(e, self.set, key, value)

codec = cp_map_set_codec
request = codec.encode_request(self._group_id, self._object_name, key_data, value_data)
return await self._ainvoke(request)

async def get(self, key: KeyType) -> typing.Optional[ElementType]:
"""Gets the value associated with the given key.

Args:
key: The key.

Returns:
The value associated with the key, or ``None`` if there is no such
mapping.
"""
check_not_none(key, "Key cannot be None")
try:
key_data = self._to_data(key)
except SchemaNotReplicatedError as e:
return await self._send_schema_and_retry(e, self.get, key)

codec = cp_map_get_codec
request = codec.encode_request(self._group_id, self._object_name, key_data)

def handler(response):
return self._to_object(codec.decode_response(response))

return await self._ainvoke(request, handler)

async def put(self, key: KeyType, value: ElementType) -> typing.Optional[ElementType]:
"""Associates the given value with the given key and returns the old
value.

Args:
key: The key.
value: The value to be associated with the key.

Returns:
The value previously associated with the key, or ``None`` if there
was no mapping for the key.
"""
check_not_none(key, "Key cannot be None")
check_not_none(value, "Value cannot be None")
try:
key_data = self._to_data(key)
value_data = self._to_data(value)
except SchemaNotReplicatedError as e:
return await self._send_schema_and_retry(e, self.put, key, value)

codec = cp_map_put_codec
request = codec.encode_request(self._group_id, self._object_name, key_data, value_data)

def handler(response):
return self._to_object(codec.decode_response(response))

return await self._ainvoke(request, handler)

async def put_if_absent(self, key: KeyType, value: ElementType) -> typing.Optional[ElementType]:
"""Associates the given value with the given key if it's not already present and returns the old
value.

Args:
key: The key.
value: The value to be associated with the key.

Returns:
The value previously associated with the key, or ``None`` if there
was no mapping for the key.
"""
check_not_none(key, "Key cannot be None")
check_not_none(value, "Value cannot be None")
try:
key_data = self._to_data(key)
value_data = self._to_data(value)
except SchemaNotReplicatedError as e:
return await self._send_schema_and_retry(e, self.put, key, value)

codec = cp_map_put_if_absent_codec
request = codec.encode_request(self._group_id, self._object_name, key_data, value_data)

def handler(response):
return self._to_object(codec.decode_response(response))

return await self._ainvoke(request, handler)

async def remove(self, key: KeyType) -> typing.Optional[ElementType]:
"""Removes the mapping for the given key and returns the removed value.

Args:
key: The key.

Returns:
The value that was associated with the key, or ``None`` if there
was no mapping for the key.
"""
check_not_none(key, "Key cannot be None")
try:
key_data = self._to_data(key)
except SchemaNotReplicatedError as e:
return await self._send_schema_and_retry(e, self.remove, key)

codec = cp_map_remove_codec
request = codec.encode_request(self._group_id, self._object_name, key_data)

def handler(response):
return self._to_object(codec.decode_response(response))

return await self._ainvoke(request, handler)

async def delete(self, key: KeyType) -> None:
"""Removes the mapping for the given key.

Args:
key: The key.
"""
check_not_none(key, "Key cannot be None")
try:
key_data = self._to_data(key)
except SchemaNotReplicatedError as e:
return await self._send_schema_and_retry(e, self.delete, key)

codec = cp_map_delete_codec
request = codec.encode_request(self._group_id, self._object_name, key_data)
return await self._ainvoke(request)

async def compare_and_set(self, key: KeyType, expect: ElementType, update: ElementType) -> bool:
"""Atomically sets the value for the given key to ``update`` only if the
current value is equal to ``expect``.

Args:
key: The key.
expect: The expected current value.
update: The new value.

Returns:
``True`` if the value was changed, ``False`` otherwise.
"""
check_not_none(key, "Key cannot be None")
check_not_none(expect, "Expected value cannot be None")
check_not_none(update, "New value cannot be None")
try:
key_data = self._to_data(key)
expected_data = self._to_data(expect)
new_data = self._to_data(update)
except SchemaNotReplicatedError as e:
return await self._send_schema_and_retry(e, self.compare_and_set, key, expect, update)

codec = cp_map_compare_and_set_codec
request = codec.encode_request(
self._group_id, self._object_name, key_data, expected_data, new_data
)
return await self._ainvoke(request, codec.decode_response)
28 changes: 28 additions & 0 deletions hazelcast/protocol/codec/cp_map_compare_and_set_codec.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE
from hazelcast.protocol.codec.custom.raft_group_id_codec import RaftGroupIdCodec
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import DataCodec

# hex: 0x230600
_REQUEST_MESSAGE_TYPE = 2295296
# hex: 0x230601
_RESPONSE_MESSAGE_TYPE = 2295297

_REQUEST_INITIAL_FRAME_SIZE = REQUEST_HEADER_SIZE
_RESPONSE_RESPONSE_OFFSET = RESPONSE_HEADER_SIZE


def encode_request(group_id, name, key, expected_value, new_value):
buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE)
RaftGroupIdCodec.encode(buf, group_id)
StringCodec.encode(buf, name)
DataCodec.encode(buf, key)
DataCodec.encode(buf, expected_value)
DataCodec.encode(buf, new_value, True)
return OutboundMessage(buf, False, True)


def decode_response(msg):
initial_frame = msg.next_frame()
return FixSizedTypesCodec.decode_boolean(initial_frame.buf, _RESPONSE_RESPONSE_OFFSET)
25 changes: 25 additions & 0 deletions hazelcast/protocol/codec/cp_map_delete_codec.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer
from hazelcast.protocol.codec.custom.raft_group_id_codec import RaftGroupIdCodec
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import DataCodec
from hazelcast.protocol.builtin import CodecUtil

# hex: 0x230500
_REQUEST_MESSAGE_TYPE = 2295040
# hex: 0x230501
_RESPONSE_MESSAGE_TYPE = 2295041

_REQUEST_INITIAL_FRAME_SIZE = REQUEST_HEADER_SIZE


def encode_request(group_id, name, key):
buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE)
RaftGroupIdCodec.encode(buf, group_id)
StringCodec.encode(buf, name)
DataCodec.encode(buf, key, True)
return OutboundMessage(buf, False, True)


def decode_response(msg):
msg.next_frame()
return CodecUtil.decode_nullable(msg, DataCodec.decode)
25 changes: 25 additions & 0 deletions hazelcast/protocol/codec/cp_map_get_codec.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer
from hazelcast.protocol.codec.custom.raft_group_id_codec import RaftGroupIdCodec
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import DataCodec
from hazelcast.protocol.builtin import CodecUtil

# hex: 0x230100
_REQUEST_MESSAGE_TYPE = 2294016
# hex: 0x230101
_RESPONSE_MESSAGE_TYPE = 2294017

_REQUEST_INITIAL_FRAME_SIZE = REQUEST_HEADER_SIZE


def encode_request(group_id, name, key):
buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE)
RaftGroupIdCodec.encode(buf, group_id)
StringCodec.encode(buf, name)
DataCodec.encode(buf, key, True)
return OutboundMessage(buf, False, True)


def decode_response(msg):
msg.next_frame()
return CodecUtil.decode_nullable(msg, DataCodec.decode)
Loading