-
Notifications
You must be signed in to change notification settings - Fork 1
feat(ISV-7020): add chunking capabilities and cluster-error handling #17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
32ffcfe
feat(ISV-7020): add chunking capabilities
BorekZnovustvoritel 6922de3
feat(ISV-7020): enhance chunking capabilities
BorekZnovustvoritel 9437a14
fix: prepare chunks with separate function to avoid code duplication
bclindner 3015405
fix(ISV-7020): fix formatting and address a review comment
BorekZnovustvoritel e52da65
feat(ISV-7020): add cluster-error handling
BorekZnovustvoritel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| """Module for tracking chunked messages""" | ||
|
|
||
| import logging | ||
| import sys | ||
| import uuid | ||
| from collections import defaultdict | ||
|
|
||
| from confluent_kafka import Message | ||
|
|
||
| from retriable_kafka_client.headers import ( | ||
| CHUNK_GROUP_HEADER, | ||
| NUMBER_OF_CHUNKS_HEADER, | ||
| CHUNK_ID_HEADER, | ||
| deserialize_number_from_bytes, | ||
| get_header_value, | ||
| ) | ||
| from retriable_kafka_client.kafka_utils import MessageGroup | ||
|
|
||
| LOGGER = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def generate_group_id() -> bytes: | ||
| """Generate a random group id.""" | ||
| return uuid.uuid4().bytes | ||
|
|
||
|
|
||
| def calculate_header_size( | ||
| headers: dict[str, str | bytes] | list[tuple[str, str | bytes]] | None, | ||
| ) -> int: | ||
| """Approximate the space needed for headers within a message.""" | ||
| if not headers: | ||
| return 0 | ||
| result = 0 | ||
| if not isinstance(headers, dict): | ||
| headers = dict(headers) | ||
| for header_key, header_value in headers.items(): | ||
| result += len(header_key) + sys.getsizeof(header_value) + 8 | ||
| # Two 32-bit numbers specifying lengths of fields are also | ||
| # present, therefore adding 8 | ||
| return result | ||
|
|
||
|
|
||
| class ChunkingCache: | ||
| # pylint: disable=too-few-public-methods | ||
| """Class for storing information about received message fragments.""" | ||
|
|
||
| def __init__(self): | ||
| # The tuple holds group ID, topic and partition | ||
| # in case of group ID collision (that could mean an attack attempt). | ||
| # If the same consumer was used for different topics, an adversary | ||
| # may want to override split messages to execute different operations. | ||
| # By using group id as well as topic and partition, this attack is | ||
| # made impossible. | ||
| self._message_chunks: dict[tuple[bytes, str, int], dict[int, Message]] = ( | ||
| defaultdict(dict) | ||
| ) | ||
|
|
||
| def receive(self, message: Message) -> MessageGroup | None: | ||
| """ | ||
| Receive a message. If the message is whole, or it is | ||
| the last fragment, returns the whole message group | ||
| and flushes cache of this group. Otherwise, returns None | ||
| and the message fragment shall not be processed. | ||
| """ | ||
| topic: str = message.topic() # type: ignore[assignment] | ||
| partition: int = message.partition() # type: ignore[assignment] | ||
| if ( | ||
| (group_id := get_header_value(message, CHUNK_GROUP_HEADER)) is not None | ||
| and ( | ||
| number_of_chunks_raw := get_header_value( | ||
| message, NUMBER_OF_CHUNKS_HEADER | ||
| ) | ||
| ) | ||
| is not None | ||
| and (chunk_id_raw := get_header_value(message, CHUNK_ID_HEADER)) is not None | ||
| ): | ||
| number_of_chunks = deserialize_number_from_bytes(number_of_chunks_raw) | ||
| chunk_id = deserialize_number_from_bytes(chunk_id_raw) | ||
| identifier = (group_id, topic, partition) | ||
| stored_message_ids_from_group = set( | ||
| self._message_chunks.get(identifier, {}).keys() | ||
| ) | ||
| stored_message_ids_from_group.add(chunk_id) | ||
| if not all( | ||
| i in stored_message_ids_from_group for i in range(number_of_chunks) | ||
| ): | ||
| LOGGER.debug( | ||
| "Received a message chunk, waiting for the other chunks..." | ||
| ) | ||
| self._message_chunks[identifier][chunk_id] = message | ||
| return None | ||
| LOGGER.debug( | ||
| "Received all message chunks, assembling group %s composed of %s messages.", | ||
| group_id.hex(), | ||
| number_of_chunks, | ||
| ) | ||
| # Clear cache and reassemble, cache can be empty if | ||
| # this is just one-message-sized value | ||
| messages = self._message_chunks.pop(identifier, {}) | ||
| messages[chunk_id] = message | ||
| return MessageGroup(topic, partition, messages, group_id) | ||
| return MessageGroup(topic, partition, {0: message}, None) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.