You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by hg...@apache.org on 2025/04/06 17:20:43 UTC
(iggy) 01/01: feat(server): implement zero-copy message handling
This is an automated email from the ASF dual-hosted git repository.
hgruszecki pushed a commit to branch zero-copy-no-batching-rebase-3
in repository https://gitbox.apache.org/repos/asf/iggy.git
commit dcf30331016110f6993191f4c6a02c268681cc64
Author: Hubert Gruszecki <h....@gmail.com>
AuthorDate: Wed Apr 2 14:27:39 2025 +0200
feat(server): implement zero-copy message handling
This commit introduces significant refactoring across the SDK
and server to enable zero-copy operations for message polling
and sending within the append-only log streaming framework.
The primary goal is to improve performance by reducing memory
allocations and copies, especially for message payloads, leading
to lower latency and higher throughput.
Changes:
- Refactored Message Structures: introduced `IggyMessage` and
`IggyMessagesBatchMut` / `IggyMessagesBatchSet` to handle
message data with minimal copying, which replaced previous
`PolledMessages` and `Message` structures in many contexts
- Serialization/Deserialization: Updated the `BytesSerializable`
trait and implementations to support more efficient serialization
and direct buffer manipulation, avoiding intermediate copies
where possible
- Command Handling: Modified `PollMessages`, `SendMessages`, and
corresponding server-side handlers (`poll_messages_handler`,
`send_messages_handler`) to work with the new zero-copy structures
and mechanisms
- Client/SDK: Updated `MessageClient` trait, `IggyClient`,
`IggyConsumer`, and CLI commands (`poll-messages`, `send-messages`)
to align with the new message handling logic
---
.config/nextest.toml | 5 +-
Cargo.lock | 170 ++++-
Cargo.toml | 2 +-
bench/src/actors/consumer.rs | 11 +-
bench/src/actors/producer.rs | 28 +-
bench/src/actors/producing_consumer.rs | 12 +-
bench/src/actors/utils.rs | 16 +-
bench/src/benchmarks/benchmark.rs | 2 +-
bench/src/benchmarks/consumer_benchmark.rs | 2 +-
bench/src/benchmarks/consumer_group_benchmark.rs | 2 +-
.../benchmarks/producer_and_consumer_benchmark.rs | 2 +-
.../producer_and_consumer_group_benchmark.rs | 6 +-
.../src/benchmarks/producing_consumer_benchmark.rs | 2 +-
.../producing_consumer_group_benchmark.rs | 2 +-
cli/Cargo.toml | 8 +-
cli/src/args/message.rs | 9 +-
configs/server.toml | 32 +-
examples/Cargo.toml | 27 +-
examples/src/basic/consumer/main.rs | 10 +-
examples/src/basic/producer/main.rs | 8 +-
examples/src/getting-started/consumer/main.rs | 12 +-
examples/src/getting-started/producer/main.rs | 12 +-
examples/src/message-envelope/consumer/main.rs | 10 +-
examples/src/message-envelope/producer/main.rs | 8 +-
examples/src/message-headers/consumer/main.rs | 20 +-
examples/src/message-headers/producer/main.rs | 13 +-
examples/src/multi-tenant/consumer/main.rs | 13 +-
examples/src/multi-tenant/producer/main.rs | 16 +-
examples/src/new-sdk/consumer/main.rs | 14 +-
examples/src/new-sdk/producer/main.rs | 12 +-
examples/src/shared/system.rs | 12 +-
examples/src/stream-builder/stream-basic/main.rs | 17 +-
.../stream-builder/stream-consumer-config/main.rs | 10 +-
.../src/stream-builder/stream-consumer/main.rs | 5 +-
.../stream-builder/stream-producer-config/main.rs | 11 +-
.../src/stream-builder/stream-producer/main.rs | 17 +-
integration/Cargo.toml | 10 +-
.../test_consumer_offset_get_command.rs | 9 +-
.../test_consumer_offset_set_command.rs | 9 +-
.../tests/cli/message/test_message_poll_command.rs | 9 +-
.../message/test_message_poll_to_file_command.rs | 10 +-
.../cli/message/test_message_reply_via_file.rs | 3 +-
.../tests/cli/message/test_message_send_command.rs | 13 +-
.../message/test_message_send_from_file_command.rs | 25 +-
.../tests/cli/stream/test_stream_purge_command.rs | 7 +-
.../tests/cli/topic/test_topic_purge_command.rs | 7 +-
integration/tests/examples/mod.rs | 17 +-
integration/tests/mod.rs | 12 +-
...h_multiple_clients_polling_messages_scenario.rs | 18 +-
...with_single_client_polling_messages_scenario.rs | 25 +-
.../server/scenarios/create_message_payload.rs | 21 +-
.../server/scenarios/message_headers_scenario.rs | 22 +-
.../server/scenarios/message_size_scenario.rs | 60 +-
integration/tests/server/scenarios/mod.rs | 2 +-
.../scenarios/stream_size_validation_scenario.rs | 19 +-
.../tests/server/scenarios/system_scenario.rs | 43 +-
integration/tests/state/file.rs | 8 +-
integration/tests/state/mod.rs | 9 +-
integration/tests/state/system.rs | 18 +-
integration/tests/streaming/get_by_offset.rs | 358 +++++----
integration/tests/streaming/get_by_timestamp.rs | 336 +++++----
integration/tests/streaming/messages.rs | 203 ++---
integration/tests/streaming/mod.rs | 17 +-
integration/tests/streaming/partition.rs | 32 +-
integration/tests/streaming/segment.rs | 445 +++++------
integration/tests/streaming/snapshot.rs | 2 +-
integration/tests/streaming/stream.rs | 33 +-
integration/tests/streaming/topic.rs | 29 +-
integration/tests/streaming/topic_messages.rs | 125 +---
sdk/Cargo.toml | 14 +-
sdk/src/binary/mapper.rs | 102 ---
sdk/src/binary/messages.rs | 18 +-
sdk/src/bytes_serializable.rs | 13 +-
sdk/src/cli/message/poll_messages.rs | 71 +-
sdk/src/cli/message/send_messages.rs | 29 +-
sdk/src/cli/segments/mod.rs | 18 +
sdk/src/client.rs | 8 +-
sdk/src/clients/client.rs | 13 +-
sdk/src/clients/consumer.rs | 54 +-
sdk/src/clients/producer.rs | 25 +-
sdk/src/consumer_ext/consumer_message_ext.rs | 2 +-
sdk/src/consumer_ext/mod.rs | 3 +-
sdk/src/error.rs | 20 +-
sdk/src/http/messages.rs | 12 +-
sdk/src/identifier.rs | 28 +
sdk/src/lib.rs | 1 +
sdk/src/messages/flush_unsaved_buffer.rs | 8 +-
sdk/src/messages/mod.rs | 22 +-
sdk/src/messages/partitioning.rs | 220 ++++++
sdk/src/messages/partitioning_kind.rs | 74 ++
sdk/src/messages/poll_messages.rs | 300 ++------
sdk/src/messages/polled_messages.rs | 129 ++++
sdk/src/messages/polling_kind.rs | 90 +++
sdk/src/messages/polling_strategy.rs | 147 ++++
sdk/src/messages/send_messages.rs | 789 ++++++--------------
sdk/src/models/messages.rs | 200 -----
.../mod.rs => sdk/src/models/messaging/index.rs | 9 +-
sdk/src/models/messaging/index_view.rs | 80 ++
sdk/src/models/messaging/indexes.rs | 203 +++++
sdk/src/models/messaging/message.rs | 591 +++++++++++++++
sdk/src/models/messaging/message_header.rs | 172 +++++
sdk/src/models/messaging/message_header_view.rs | 117 +++
sdk/src/models/messaging/message_view.rs | 196 +++++
sdk/src/models/messaging/messages_batch.rs | 587 +++++++++++++++
sdk/src/models/messaging/mod.rs | 45 ++
.../{header.rs => messaging/user_headers.rs} | 7 +-
sdk/src/models/mod.rs | 3 +-
sdk/src/partitioner.rs | 4 +-
sdk/src/prelude.rs | 84 +++
.../stream_builder/config/config_iggy_consumer.rs | 5 +-
.../stream_builder/config/config_iggy_producer.rs | 5 +-
sdk/src/tcp/client.rs | 3 +-
sdk/src/topics/create_topic.rs | 2 +-
sdk/src/topics/update_topic.rs | 2 +-
sdk/src/utils/byte_size.rs | 5 +
sdk/src/utils/duration.rs | 11 +-
sdk/src/utils/timestamp.rs | 30 +-
server/Cargo.toml | 33 +-
server/src/binary/command.rs | 587 ++++++++++-----
.../create_consumer_group_handler.rs | 106 +--
.../delete_consumer_group_handler.rs | 96 ++-
.../consumer_groups/get_consumer_group_handler.rs | 69 +-
.../consumer_groups/get_consumer_groups_handler.rs | 59 +-
.../consumer_groups/join_consumer_group_handler.rs | 68 +-
.../leave_consumer_group_handler.rs | 69 +-
.../delete_consumer_offset_handler.rs | 66 +-
.../get_consumer_offset_handler.rs | 77 +-
.../store_consumer_offset_handler.rs | 66 +-
.../messages/flush_unsaved_buffer_handler.rs | 74 +-
.../handlers/messages/poll_messages_handler.rs | 126 +++-
.../handlers/messages/send_messages_handler.rs | 125 +++-
server/src/binary/handlers/mod.rs | 1 +
.../partitions/create_partitions_handler.rs | 68 +-
.../partitions/delete_partitions_handler.rs | 64 +-
.../create_personal_access_token_handler.rs | 94 ++-
.../delete_personal_access_token_handler.rs | 76 +-
.../get_personal_access_tokens_handler.rs | 57 +-
.../login_with_personal_access_token_handler.rs | 65 +-
.../handlers/segments/delete_segments_handler.rs | 2 +-
.../handlers/streams/create_stream_handler.rs | 86 ++-
.../handlers/streams/delete_stream_handler.rs | 67 +-
.../binary/handlers/streams/get_stream_handler.rs | 60 +-
.../binary/handlers/streams/get_streams_handler.rs | 50 +-
.../handlers/streams/purge_stream_handler.rs | 72 +-
.../handlers/streams/update_stream_handler.rs | 67 +-
.../binary/handlers/system/get_client_handler.rs | 48 +-
.../binary/handlers/system/get_clients_handler.rs | 57 +-
.../src/binary/handlers/system/get_me_handler.rs | 45 +-
server/src/binary/handlers/system/get_snapshot.rs | 50 +-
.../binary/handlers/system/get_stats_handler.rs | 51 +-
server/src/binary/handlers/system/ping_handler.rs | 53 +-
.../binary/handlers/topics/create_topic_handler.rs | 112 +--
.../binary/handlers/topics/delete_topic_handler.rs | 68 +-
.../binary/handlers/topics/get_topic_handler.rs | 59 +-
.../binary/handlers/topics/get_topics_handler.rs | 59 +-
.../binary/handlers/topics/purge_topic_handler.rs | 81 +-
.../binary/handlers/topics/update_topic_handler.rs | 97 ++-
.../handlers/users/change_password_handler.rs | 96 ++-
.../binary/handlers/users/create_user_handler.rs | 106 +--
.../binary/handlers/users/delete_user_handler.rs | 72 +-
.../src/binary/handlers/users/get_user_handler.rs | 59 +-
.../src/binary/handlers/users/get_users_handler.rs | 55 +-
.../binary/handlers/users/login_user_handler.rs | 63 +-
.../binary/handlers/users/logout_user_handler.rs | 57 +-
.../handlers/users/update_permissions_handler.rs | 70 +-
.../binary/handlers/users/update_user_handler.rs | 85 ++-
.../handlers/utils.rs} | 28 +-
server/src/binary/macros.rs | 114 +++
server/src/binary/mapper.rs | 21 -
server/src/binary/mod.rs | 7 +-
server/src/binary/sender.rs | 7 +
server/src/channels/commands/archive_state.rs | 8 +-
.../commands/clean_personal_access_tokens.rs | 6 +-
server/src/channels/commands/maintain_messages.rs | 22 +-
server/src/channels/commands/print_sysinfo.rs | 19 +-
server/src/channels/commands/save_messages.rs | 4 +-
server/src/channels/commands/verify_heartbeats.rs | 4 +-
server/src/channels/handler.rs | 8 +-
server/src/channels/server_command.rs | 5 +-
server/src/command.rs | 701 ------------------
.../src/compat/index_rebuilding/index_rebuilder.rs | 70 +-
server/src/configs/cache_indexes.rs | 91 +++
server/src/configs/config_provider.rs | 5 +-
server/src/configs/defaults.rs | 24 +-
server/src/configs/displays.rs | 13 +-
server/src/configs/mod.rs | 1 +
server/src/configs/system.rs | 14 +-
server/src/configs/validators.rs | 49 +-
server/src/http/consumer_groups.rs | 4 +-
server/src/http/messages.rs | 36 +-
server/src/http/partitions.rs | 4 +-
server/src/http/personal_access_tokens.rs | 4 +-
server/src/http/streams.rs | 8 +-
server/src/http/system.rs | 2 +-
server/src/http/topics.rs | 8 +-
server/src/http/users.rs | 10 +-
server/src/lib.rs | 1 -
server/src/main.rs | 4 +-
server/src/quic/listener.rs | 91 ++-
server/src/quic/quic_sender.rs | 62 +-
server/src/state/file.rs | 2 +-
server/src/state/mod.rs | 4 +-
server/src/streaming/batching/batch_accumulator.rs | 138 ----
server/src/streaming/batching/batch_filter.rs | 26 -
server/src/streaming/batching/iterator.rs | 82 --
server/src/streaming/batching/message_batch.rs | 104 ---
server/src/streaming/batching/mod.rs | 23 -
server/src/streaming/cache/buffer.rs | 195 -----
server/src/streaming/cache/memory_tracker.rs | 119 ---
server/src/streaming/cache/mod.rs | 21 -
.../deduplication/message_deduplicator.rs | 22 +-
server/src/streaming/mod.rs | 3 -
server/src/streaming/models/messages.rs | 223 ------
server/src/streaming/partitions/messages.rs | 824 ++++++++++++---------
server/src/streaming/partitions/mod.rs | 20 -
server/src/streaming/partitions/partition.rs | 109 +--
server/src/streaming/partitions/persistence.rs | 4 +-
server/src/streaming/partitions/segments.rs | 19 +-
server/src/streaming/partitions/storage.rs | 87 ++-
server/src/streaming/segments/indexes/index.rs | 217 ------
.../src/streaming/segments/indexes/index_reader.rs | 511 +++++++++----
.../src/streaming/segments/indexes/index_writer.rs | 81 +-
.../src/streaming/segments/indexes/indexes_mut.rs | 365 +++++++++
server/src/streaming/segments/indexes/mod.rs | 12 +-
server/src/streaming/segments/logs/log_reader.rs | 358 ---------
server/src/streaming/segments/logs/mod.rs | 25 -
.../streaming/segments/messages/messages_reader.rs | 272 +++++++
.../log_writer.rs => messages/messages_writer.rs} | 138 ++--
server/src/streaming/segments/messages/mod.rs | 59 ++
.../segments/{logs => messages}/persister_task.rs | 119 +--
.../src/streaming/segments/messages_accumulator.rs | 199 +++++
server/src/streaming/segments/mod.rs | 11 +-
server/src/streaming/segments/reading_messages.rs | 573 +++++++-------
server/src/streaming/segments/segment.rs | 277 +++----
.../segments/types/message_header_view_mut.rs | 103 +++
.../streaming/segments/types/message_view_mut.rs | 121 +++
.../streaming/segments/types/messages_batch_mut.rs | 668 +++++++++++++++++
.../streaming/segments/types/messages_batch_set.rs | 383 ++++++++++
.../{binary => streaming/segments/types}/mod.rs | 13 +-
server/src/streaming/segments/writing_messages.rs | 202 ++---
server/src/streaming/streams/topics.rs | 2 +-
server/src/streaming/systems/messages.rs | 203 ++---
server/src/streaming/systems/segments.rs | 12 +-
server/src/streaming/systems/snapshot/mod.rs | 6 +-
server/src/streaming/systems/stats.rs | 19 +-
server/src/streaming/systems/system.rs | 27 +-
server/src/streaming/systems/users.rs | 2 +-
server/src/streaming/topics/messages.rs | 211 ++----
server/src/streaming/topics/storage.rs | 6 -
server/src/streaming/utils/file.rs | 30 +-
server/src/tcp/connection_handler.rs | 57 +-
server/src/tcp/sender.rs | 46 +-
server/src/tcp/tcp_sender.rs | 8 +
server/src/tcp/tcp_tls_sender.rs | 8 +
tools/Cargo.toml | 8 +-
tools/src/data-seeder/seeder.rs | 85 ++-
256 files changed, 11771 insertions(+), 8124 deletions(-)
diff --git a/.config/nextest.toml b/.config/nextest.toml
index 97d38cd1..bb29d965 100644
--- a/.config/nextest.toml
+++ b/.config/nextest.toml
@@ -17,6 +17,9 @@
[[profile.default.overrides]]
# This is a solution (or actually a workaround) for the problem that nextest does not support
-# #[serial] macro which shall enfroce sequential execution of the test case.
+# #[serial] macro which shall enforce sequential execution of the test case.
filter = 'package(integration) and test(cli::system::test_cli_session_scenario::should_be_successful)'
threads-required = "num-cpus"
+
+[profile.default]
+slow-timeout = { period = "30s", terminate-after = 4 }
diff --git a/Cargo.lock b/Cargo.lock
index a065d3c4..ba9d3820 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -408,25 +408,27 @@ dependencies = [
[[package]]
name = "aws-lc-rs"
-version = "1.12.6"
+version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dabb68eb3a7aa08b46fddfd59a3d55c978243557a90ab804769f7e20e67d2b01"
+checksum = "3c6a895b664295a4ba0c2c0203c7075ea585dd75cd5c37a8efac829e13e460ef"
dependencies = [
"aws-lc-sys",
+ "paste",
"zeroize",
]
[[package]]
name = "aws-lc-sys"
-version = "0.27.1"
+version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "77926887776171ced7d662120a75998e444d3750c951abfe07f90da130514b1f"
+checksum = "0f9dd2e03ee80ca2822dd6ea431163d2ef259f2066a4d6ccaca6d9dcb386aa43"
dependencies = [
"bindgen",
"cc",
"cmake",
"dunce",
"fs_extra",
+ "paste",
]
[[package]]
@@ -842,6 +844,9 @@ name = "bytes"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
+dependencies = [
+ "serde",
+]
[[package]]
name = "bzip2"
@@ -896,9 +901,9 @@ dependencies = [
[[package]]
name = "cc"
-version = "1.2.17"
+version = "1.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fcb57c740ae1daf453ae85f16e37396f672b039e00d9d866e07ddb24e328e3a"
+checksum = "0c3d1b2e905a3a7b00a6141adb0e4c0bb941d11caf55349d863942a1cc44e3c9"
dependencies = [
"jobserver",
"libc",
@@ -1614,6 +1619,18 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "enum_dispatch"
+version = "0.3.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd"
+dependencies = [
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.100",
+]
+
[[package]]
name = "env_filter"
version = "0.1.3"
@@ -1707,6 +1724,35 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "ext-trait"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d772df1c1a777963712fb68e014235e80863d6a91a85c4e06ba2d16243a310e5"
+dependencies = [
+ "ext-trait-proc_macros",
+]
+
+[[package]]
+name = "ext-trait-proc_macros"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ab7934152eaf26aa5aa9f7371408ad5af4c31357073c9e84c3b9d7f11ad639a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "extension-traits"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a296e5a895621edf9fa8329c83aa1cb69a964643e36cf54d8d7a69b789089537"
+dependencies = [
+ "ext-trait",
+]
+
[[package]]
name = "fast-async-mutex"
version = "0.6.7"
@@ -2825,6 +2871,31 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
+[[package]]
+name = "lending-iterator"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc07588c853b50689205fb5c00498aa681d89828e0ce8cbd965ebc7a5d8ae260"
+dependencies = [
+ "extension-traits",
+ "lending-iterator-proc_macros",
+ "macro_rules_attribute",
+ "never-say-never",
+ "nougat",
+ "polonius-the-crab",
+]
+
+[[package]]
+name = "lending-iterator-proc_macros"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5445dd1c0deb1e97b8a16561d17fc686ca83e8411128fb036e9668a72d51b1d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
[[package]]
name = "libc"
version = "0.2.171"
@@ -2969,6 +3040,22 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "macro_rules_attribute"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf0c9b980bf4f3a37fd7b1c066941dd1b1d0152ce6ee6e8fe8c49b9f6810d862"
+dependencies = [
+ "macro_rules_attribute-proc_macro",
+ "paste",
+]
+
+[[package]]
+name = "macro_rules_attribute-proc_macro"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "58093314a45e00c77d5c508f76e77c3396afbbc0d01506e7fae47b018bac2b1d"
+
[[package]]
name = "matchers"
version = "0.1.0"
@@ -3013,6 +3100,15 @@ version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
+[[package]]
+name = "memmap2"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3f7eed9d3848f8b98834af67102b720745c4ec028fcd0aa0239277e7de374f"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "mimalloc"
version = "0.1.44"
@@ -3137,6 +3233,12 @@ dependencies = [
"tempfile",
]
+[[package]]
+name = "never-say-never"
+version = "6.6.666"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf5a574dadd7941adeaa71823ecba5e28331b8313fb2e1c6a5c7e5981ea53ad6"
+
[[package]]
name = "nix"
version = "0.29.0"
@@ -3171,6 +3273,27 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be"
+[[package]]
+name = "nougat"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97b57b9ced431322f054fc673f1d3c7fa52d80efd9df74ad2fc759f044742510"
+dependencies = [
+ "macro_rules_attribute",
+ "nougat-proc_macros",
+]
+
+[[package]]
+name = "nougat-proc_macros"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c84f77a45e99a2f9b492695d99e1c23844619caa5f3e57647cffacad773ca257"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
[[package]]
name = "ntapi"
version = "0.4.1"
@@ -3532,7 +3655,7 @@ checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
dependencies = [
"cfg-if",
"libc",
- "redox_syscall 0.5.10",
+ "redox_syscall 0.5.8",
"smallvec",
"windows-targets 0.52.6",
]
@@ -3547,6 +3670,12 @@ dependencies = [
"windows-sys 0.48.0",
]
+[[package]]
+name = "paste"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+
[[package]]
name = "pbkdf2"
version = "0.12.2"
@@ -3679,6 +3808,12 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
+[[package]]
+name = "polonius-the-crab"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a69ee997a6282f8462abf1e0d8c38c965e968799e912b3bed8c9e8a28c2f9f"
+
[[package]]
name = "polyval"
version = "0.6.2"
@@ -4081,9 +4216,9 @@ dependencies = [
[[package]]
name = "redox_syscall"
-version = "0.5.10"
+version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b8c0c260b63a8219631167be35e6a988e9554dbd323f8bd08439c8ed1302bd1"
+checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834"
dependencies = [
"bitflags 2.9.0",
]
@@ -4250,9 +4385,9 @@ dependencies = [
[[package]]
name = "ring"
-version = "0.17.14"
+version = "0.17.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+checksum = "e75ec5e92c4d8aede845126adc388046234541629e76029599ed35a003c7ed24"
dependencies = [
"cc",
"cfg-if",
@@ -4738,7 +4873,7 @@ dependencies = [
[[package]]
name = "server"
-version = "0.4.300"
+version = "0.5.0"
dependencies = [
"ahash 0.8.11",
"anyhow",
@@ -4756,6 +4891,7 @@ dependencies = [
"dashmap",
"derive_more",
"dotenvy",
+ "enum_dispatch",
"error_set",
"figlet-rs",
"figment",
@@ -4764,6 +4900,8 @@ dependencies = [
"human-repr",
"iggy",
"jsonwebtoken",
+ "lending-iterator",
+ "memmap2",
"mimalloc",
"mockall",
"moka",
@@ -6684,18 +6822,18 @@ dependencies = [
[[package]]
name = "zstd-safe"
-version = "7.2.4"
+version = "7.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"
+checksum = "54a3ab4db68cea366acc5c897c7b4d4d1b8994a9cd6e6f841f8964566a419059"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
-version = "2.0.15+zstd.1.5.7"
+version = "2.0.13+zstd.1.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eb81183ddd97d0c74cedf1d50d85c8d08c1b8b68ee863bdee9e706eedba1a237"
+checksum = "38ff0f21cfee8f97d94cef41359e0c89aa6113028ab0291aa8ca0038995a95aa"
dependencies = [
"cc",
"pkg-config",
diff --git a/Cargo.toml b/Cargo.toml
index f2fdad78..43413457 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -29,7 +29,7 @@ members = [
"integration",
"sdk",
"server",
- "tools"
+ "tools",
]
[workspace.metadata.cargo-machete]
diff --git a/bench/src/actors/consumer.rs b/bench/src/actors/consumer.rs
index f05e63d1..b726b527 100644
--- a/bench/src/actors/consumer.rs
+++ b/bench/src/actors/consumer.rs
@@ -25,7 +25,8 @@ use iggy::client::{ConsumerGroupClient, MessageClient};
use iggy::clients::client::IggyClient;
use iggy::consumer::Consumer as IggyConsumer;
use iggy::error::IggyError;
-use iggy::messages::poll_messages::{PollingKind, PollingStrategy};
+use iggy::messages::PollingKind;
+use iggy::prelude::PollingStrategy;
use iggy::utils::byte_size::IggyByteSize;
use iggy::utils::duration::IggyDuration;
use iggy::utils::sizeable::Sizeable;
@@ -147,6 +148,7 @@ impl Consumer {
self.consumer_id, self.warmup_time
);
}
+
let warmup_end = Instant::now() + self.warmup_time.get_duration();
while Instant::now() < warmup_end {
let offset = current_iteration * messages_per_batch as u64;
@@ -246,7 +248,6 @@ impl Consumer {
let polled_messages = polled_messages.unwrap();
if polled_messages.messages.is_empty() {
- // Store initial poll timestamp if this is the first attempt
if initial_poll_timestamp.is_none() {
initial_poll_timestamp = Some(before_poll);
}
@@ -305,11 +306,11 @@ impl Consumer {
// We don't need to calculate the size whole batch every time by iterating over it - just always use the size of the first message
if batch_user_size_bytes == 0 || batch_size_total_bytes == 0 {
- batch_user_size_bytes =
- polled_messages.messages[0].payload.len() as u64 * messages_per_batch as u64;
+ batch_user_size_bytes = polled_messages.messages[0].payload.len() as u64
+ * polled_messages.messages.len() as u64;
batch_size_total_bytes =
polled_messages.messages[0].get_size_bytes().as_bytes_u64()
- * messages_per_batch as u64;
+ * polled_messages.messages.len() as u64;
}
total_user_data_bytes += IggyByteSize::from(batch_user_size_bytes);
diff --git a/bench/src/actors/producer.rs b/bench/src/actors/producer.rs
index 83d727c7..8ab3ea64 100644
--- a/bench/src/actors/producer.rs
+++ b/bench/src/actors/producer.rs
@@ -24,7 +24,8 @@ use human_repr::HumanCount;
use iggy::client::MessageClient;
use iggy::clients::client::IggyClient;
use iggy::error::IggyError;
-use iggy::messages::send_messages::{Message, Partitioning};
+use iggy::prelude::IggyMessage;
+use iggy::prelude::Partitioning;
use iggy::utils::byte_size::IggyByteSize;
use iggy::utils::duration::IggyDuration;
use iggy::utils::sizeable::Sizeable;
@@ -109,8 +110,8 @@ impl Producer {
let mut batch_total_bytes = 0;
let mut messages = Vec::with_capacity(messages_per_batch as usize);
for _ in 0..messages_per_batch {
- let message = Message::from_str(&payload).unwrap();
- batch_user_data_bytes += message.length as u64;
+ let message = IggyMessage::from_str(&payload).unwrap();
+ batch_user_data_bytes += message.payload.len() as u64;
batch_total_bytes += message.get_size_bytes().as_bytes_u64();
messages.push(message);
}
@@ -154,7 +155,10 @@ impl Producer {
let start_timestamp = Instant::now();
let mut latencies: Vec<Duration> = Vec::with_capacity(message_batches as usize);
let mut records = Vec::with_capacity(message_batches as usize);
+ let mut total_overhead_time = Duration::from_secs(0);
for i in 1..=message_batches {
+ let iteration_start = Instant::now();
+
// Apply rate limiting if configured
if let Some(limiter) = &self.rate_limiter {
limiter.throttle(batch_total_bytes).await;
@@ -168,6 +172,10 @@ impl Producer {
.await?;
let latency = before_send.elapsed();
+ let iteration_time = iteration_start.elapsed();
+ let overhead_time = iteration_time - latency;
+ total_overhead_time += overhead_time;
+
let messages_processed = (i * messages_per_batch) as u64;
let batches_processed = i as u64;
let user_data_bytes = batches_processed * batch_user_data_bytes;
@@ -200,6 +208,20 @@ impl Producer {
&metrics,
);
+ let avg_overhead_per_batch =
+ total_overhead_time.as_micros() as f64 / message_batches as f64;
+ let total_elapsed = start_timestamp.elapsed();
+ let send_time = total_elapsed - total_overhead_time;
+ info!(
+ "Producer #{} → Overhead stats: Total time: {} ms, Send time: {} ms, Overhead time: {} ms ({:.2}%), Avg overhead per batch: {:.2} μs",
+ self.producer_id,
+ total_elapsed.as_millis(),
+ send_time.as_millis(),
+ total_overhead_time.as_millis(),
+ (total_overhead_time.as_micros() as f64 / total_elapsed.as_micros() as f64) * 100.0,
+ avg_overhead_per_batch
+ );
+
Ok(metrics)
}
diff --git a/bench/src/actors/producing_consumer.rs b/bench/src/actors/producing_consumer.rs
index e906ec23..079a5b6e 100644
--- a/bench/src/actors/producing_consumer.rs
+++ b/bench/src/actors/producing_consumer.rs
@@ -16,7 +16,8 @@
* under the License.
*/
-use crate::actors::utils::{calculate_latency_from_first_message, put_timestamp_in_first_message};
+use crate::actors::utils::calculate_latency_from_first_message;
+use crate::actors::utils::put_timestamp_in_first_message;
use crate::analytics::metrics::individual::from_records;
use crate::analytics::record::BenchmarkRecord;
use crate::rate_limiter::RateLimiter;
@@ -26,8 +27,7 @@ use iggy::client::MessageClient;
use iggy::clients::client::IggyClient;
use iggy::consumer::Consumer as IggyConsumer;
use iggy::error::IggyError;
-use iggy::messages::poll_messages::{PollingKind, PollingStrategy};
-use iggy::messages::send_messages::{Message, Partitioning};
+use iggy::prelude::*;
use iggy::utils::byte_size::IggyByteSize;
use iggy::utils::duration::IggyDuration;
use iggy::utils::sizeable::Sizeable;
@@ -122,8 +122,8 @@ impl ProducingConsumer {
let mut batch_total_bytes = 0;
let mut messages = Vec::with_capacity(messages_per_batch as usize);
for _ in 0..messages_per_batch {
- let message = Message::from_str(&payload).unwrap();
- batch_user_data_bytes += message.length as u64;
+ let message = IggyMessage::from_str(&payload).unwrap();
+ batch_user_data_bytes += message.payload.len() as u64;
batch_total_bytes += message.get_size_bytes().as_bytes_u64();
messages.push(message);
}
@@ -190,6 +190,7 @@ impl ProducingConsumer {
self.polling_kind
),
};
+
let polled_messages = client
.poll_messages(
&stream_id,
@@ -223,6 +224,7 @@ impl ProducingConsumer {
continue;
}
+
current_offset += messages_per_batch as u64;
}
}
diff --git a/bench/src/actors/utils.rs b/bench/src/actors/utils.rs
index 2ed4fee4..5aaccda8 100644
--- a/bench/src/actors/utils.rs
+++ b/bench/src/actors/utils.rs
@@ -16,36 +16,28 @@
* under the License.
*/
-use std::time::Duration;
-
use bytes::Bytes;
-use iggy::{messages::send_messages::Message, models::messages::PolledMessage};
+use iggy::prelude::IggyMessage;
+use std::time::Duration;
-pub fn put_timestamp_in_first_message(message: &mut Message) {
+pub fn put_timestamp_in_first_message(message: &mut IggyMessage) {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_micros() as u64;
- // Convert current payload to Vec<u8>
let mut payload_vec = message.payload.to_vec();
-
- // Ensure payload is at least 8 bytes
if payload_vec.len() < 8 {
let mut new_payload = vec![0u8; 8];
new_payload.extend_from_slice(&payload_vec);
payload_vec = new_payload;
}
-
- // Put timestamp in first 8 bytes
let timestamp_bytes = now.to_le_bytes();
payload_vec[0..8].copy_from_slice(×tamp_bytes);
-
- // Convert back to Bytes
message.payload = Bytes::from(payload_vec);
}
-pub fn calculate_latency_from_first_message(message: &PolledMessage) -> Duration {
+pub fn calculate_latency_from_first_message(message: &IggyMessage) -> Duration {
let send_timestamp = u64::from_le_bytes(message.payload[0..8].try_into().unwrap());
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
diff --git a/bench/src/benchmarks/benchmark.rs b/bench/src/benchmarks/benchmark.rs
index faa9af87..67a58cc3 100644
--- a/bench/src/benchmarks/benchmark.rs
+++ b/bench/src/benchmarks/benchmark.rs
@@ -69,7 +69,7 @@ impl From<IggyBenchArgs> for Box<dyn Benchmarkable> {
BenchmarkKindCommand::EndToEndProducingConsumerGroup(_) => Box::new(
EndToEndProducingConsumerGroupBenchmark::new(Arc::new(args), client_factory),
),
- _ => todo!(),
+ _ => unreachable!(),
}
}
}
diff --git a/bench/src/benchmarks/consumer_benchmark.rs b/bench/src/benchmarks/consumer_benchmark.rs
index b7531171..3c6cdde0 100644
--- a/bench/src/benchmarks/consumer_benchmark.rs
+++ b/bench/src/benchmarks/consumer_benchmark.rs
@@ -22,7 +22,7 @@ use crate::benchmarks::benchmark::Benchmarkable;
use crate::rate_limiter::RateLimiter;
use async_trait::async_trait;
use iggy::error::IggyError;
-use iggy::messages::poll_messages::PollingKind;
+use iggy::messages::PollingKind;
use iggy_bench_report::benchmark_kind::BenchmarkKind;
use iggy_bench_report::individual_metrics::BenchmarkIndividualMetrics;
use integration::test_server::ClientFactory;
diff --git a/bench/src/benchmarks/consumer_group_benchmark.rs b/bench/src/benchmarks/consumer_group_benchmark.rs
index 6e55f4a1..13fb163a 100644
--- a/bench/src/benchmarks/consumer_group_benchmark.rs
+++ b/bench/src/benchmarks/consumer_group_benchmark.rs
@@ -26,7 +26,7 @@ use crate::{
use async_trait::async_trait;
use iggy::{
client::ConsumerGroupClient, clients::client::IggyClient, error::IggyError,
- messages::poll_messages::PollingKind,
+ messages::PollingKind,
};
use iggy_bench_report::{
benchmark_kind::BenchmarkKind, individual_metrics::BenchmarkIndividualMetrics,
diff --git a/bench/src/benchmarks/producer_and_consumer_benchmark.rs b/bench/src/benchmarks/producer_and_consumer_benchmark.rs
index 68782de0..49950b2f 100644
--- a/bench/src/benchmarks/producer_and_consumer_benchmark.rs
+++ b/bench/src/benchmarks/producer_and_consumer_benchmark.rs
@@ -23,7 +23,7 @@ use crate::benchmarks::benchmark::Benchmarkable;
use crate::rate_limiter::RateLimiter;
use async_trait::async_trait;
use iggy::error::IggyError;
-use iggy::messages::poll_messages::PollingKind;
+use iggy::messages::PollingKind;
use iggy_bench_report::benchmark_kind::BenchmarkKind;
use iggy_bench_report::individual_metrics::BenchmarkIndividualMetrics;
use integration::test_server::ClientFactory;
diff --git a/bench/src/benchmarks/producer_and_consumer_group_benchmark.rs b/bench/src/benchmarks/producer_and_consumer_group_benchmark.rs
index a7b6cbfa..7acdc33d 100644
--- a/bench/src/benchmarks/producer_and_consumer_group_benchmark.rs
+++ b/bench/src/benchmarks/producer_and_consumer_group_benchmark.rs
@@ -24,10 +24,8 @@ use crate::{
rate_limiter::RateLimiter,
};
use async_trait::async_trait;
-use iggy::{
- client::ConsumerGroupClient, clients::client::IggyClient, error::IggyError,
- messages::poll_messages::PollingKind,
-};
+use iggy::messages::PollingKind;
+use iggy::{client::ConsumerGroupClient, clients::client::IggyClient, error::IggyError};
use iggy_bench_report::{
benchmark_kind::BenchmarkKind, individual_metrics::BenchmarkIndividualMetrics,
};
diff --git a/bench/src/benchmarks/producing_consumer_benchmark.rs b/bench/src/benchmarks/producing_consumer_benchmark.rs
index 2cdf2bc0..59564a7b 100644
--- a/bench/src/benchmarks/producing_consumer_benchmark.rs
+++ b/bench/src/benchmarks/producing_consumer_benchmark.rs
@@ -22,7 +22,7 @@ use crate::benchmarks::benchmark::Benchmarkable;
use crate::rate_limiter::RateLimiter;
use async_trait::async_trait;
use iggy::error::IggyError;
-use iggy::messages::poll_messages::PollingKind;
+use iggy::messages::PollingKind;
use iggy_bench_report::benchmark_kind::BenchmarkKind;
use iggy_bench_report::individual_metrics::BenchmarkIndividualMetrics;
use integration::test_server::ClientFactory;
diff --git a/bench/src/benchmarks/producing_consumer_group_benchmark.rs b/bench/src/benchmarks/producing_consumer_group_benchmark.rs
index bae9d5b1..4a2ce09a 100644
--- a/bench/src/benchmarks/producing_consumer_group_benchmark.rs
+++ b/bench/src/benchmarks/producing_consumer_group_benchmark.rs
@@ -25,7 +25,7 @@ use async_trait::async_trait;
use iggy::client::ConsumerGroupClient;
use iggy::clients::client::IggyClient;
use iggy::error::IggyError;
-use iggy::messages::poll_messages::PollingKind;
+use iggy::messages::PollingKind;
use iggy_bench_report::benchmark_kind::BenchmarkKind;
use iggy_bench_report::individual_metrics::BenchmarkIndividualMetrics;
use integration::test_server::{login_root, ClientFactory};
diff --git a/cli/Cargo.toml b/cli/Cargo.toml
index d184ee93..6d0a0c48 100644
--- a/cli/Cargo.toml
+++ b/cli/Cargo.toml
@@ -27,6 +27,10 @@ license = "Apache-2.0"
keywords = ["iggy", "cli", "messaging", "streaming"]
readme = "../README.md"
+[package.metadata.binstall]
+pkg-url = "{ repo }/releases/download/{ name }-{ version }/{ name }-{ target }{ archive-suffix }"
+bin-dir = "{ bin }{ binary-ext }"
+
[features]
default = ["login-session"]
login-session = ["dep:keyring"]
@@ -55,7 +59,3 @@ tracing-subscriber = { version = "0.3.19", default-features = false, features =
[[bin]]
name = "iggy"
path = "src/main.rs"
-
-[package.metadata.binstall]
-pkg-url = "{ repo }/releases/download/{ name }-{ version }/{ name }-{ target }{ archive-suffix }"
-bin-dir = "{ bin }{ binary-ext }"
diff --git a/cli/src/args/message.rs b/cli/src/args/message.rs
index 1f1e4853..934ee616 100644
--- a/cli/src/args/message.rs
+++ b/cli/src/args/message.rs
@@ -18,10 +18,7 @@
use clap::builder::NonEmptyStringValueParser;
use clap::{ArgGroup, Args, Subcommand};
-use iggy::error::IggyError;
-use iggy::error::IggyError::InvalidFormat;
-use iggy::identifier::Identifier;
-use iggy::models::header::{HeaderKey, HeaderValue};
+use iggy::prelude::*;
use std::str::FromStr;
#[derive(Debug, Clone, Subcommand)]
@@ -102,7 +99,7 @@ pub(crate) struct SendMessagesArgs {
pub(crate) messages: Option<Vec<String>>,
/// Comma separated list of key:kind:value, sent as header with the message
///
- /// Headers are comma seperated key-value pairs that can be sent with the message.
+ /// Headers are comma separated key-value pairs that can be sent with the message.
/// Kind can be one of the following: raw, string, bool, int8, int16, int32, int64,
/// int128, uint8, uint16, uint32, uint64, uint128, float32, float64
#[clap(verbatim_doc_comment)]
@@ -127,7 +124,7 @@ fn parse_key_val(s: &str) -> Result<(HeaderKey, HeaderValue), IggyError> {
let parts = lower.split(':').collect::<Vec<_>>();
if parts.len() != 3 {
- Err(InvalidFormat)?;
+ return Err(IggyError::InvalidFormat);
}
let key = HeaderKey::from_str(parts[0])?;
diff --git a/configs/server.toml b/configs/server.toml
index be7f1b1a..446ee49a 100644
--- a/configs/server.toml
+++ b/configs/server.toml
@@ -386,16 +386,6 @@ retention = "7 days"
# Interval for printing system information to the log.
sysinfo_print_interval = "10 s"
-# Cache configuration.
-[system.cache]
-# Enables or disables the system cache.
-# `true` activates caching for frequently accessed data.
-# `false` disables caching, data is always read from the source.
-enabled = true
-
-# Maximum size of the cache, e.g. "4GB".
-size = "4 GB"
-
# Encryption configuration
[system.encryption]
# Determines whether server-side data encryption for the messages payloads and state commands is enabled (boolean).
@@ -461,17 +451,27 @@ enforce_fsync = false
# `false` skips these checks for faster loading at the risk of undetected corruption.
validate_checksum = false
-# The threshold of buffered messages before triggering a save to disk (integer).
+# The count threshold of buffered messages before triggering a save to disk (integer).
# Specifies how many messages accumulate before persisting to storage.
# Adjusting this can balance between write performance and data durability.
+# This is soft limit, actual number of messages may be higher, depending on last batch size.
+# Together with `size_of_messages_required_to_save` it defines the threshold of buffered messages.
messages_required_to_save = 1000
+# The size threshold of buffered messages before triggering a save to disk (string).
+# Specifies how much size of messages accumulate before persisting to storage.
+# Adjusting this can balance between write performance and data durability.
+# This is soft limit, actual number of messages may be higher, depending on last batch size.
+# Together with `messages_required_to_save` it defines the threshold of buffered messages.
+size_of_messages_required_to_save = "1 MB"
+
# Segment configuration
[system.segment]
# Defines the soft limit for the size of a storage segment.
# When a segment reaches this size, a new segment is created for subsequent data.
# Example: if `size` is set "1GB", the actual segment size may be 1GB + the size of remaining messages in received batch.
size = "1 GB"
+
# Configures the message time-based expiry setting.
# "none" means messages are kept indefinitely.
# A time value in human-readable format determines the lifespan of messages.
@@ -488,10 +488,12 @@ server_confirmation = "wait"
# Configures whether expired segments are archived (boolean) or just deleted without archiving.
archive_expired = false
-# Controls whether to cache indexes (time and positional) for segment access (boolean).
-# `true` keeps indexes in memory, speeding up data retrieval.
-# `false` reads indexes from disk, which can conserve memory at the cost of access speed.
-cache_indexes = true
+# Controls whether to cache indexes (time and positional) for segment access.
+# Possible values:
+# - "true" or "all": keeps indexes in memory, speeding up data retrieval at the cost of memory
+# - "open_segment": keeps indexes in memory only for the currently open segment
+# - "false" or "none": reads indexes from disk, which can conserve memory at the cost of access speed
+cache_indexes = "open_segment"
# Message deduplication configuration
[system.message_deduplication]
diff --git a/examples/Cargo.toml b/examples/Cargo.toml
index efe3d0e8..169a2341 100644
--- a/examples/Cargo.toml
+++ b/examples/Cargo.toml
@@ -21,6 +21,20 @@ version = "0.0.5"
edition = "2021"
license = "Apache-2.0"
+[dependencies]
+ahash = { version = "0.8.11", features = ["serde"] }
+anyhow = "1.0.97"
+bytes = "1.10.1"
+clap = { version = "4.5.34", features = ["derive"] }
+futures-util = "0.3.31"
+iggy = { path = "../sdk" }
+rand = "0.9.0"
+serde = { version = "1.0.219", features = ["derive", "rc"] }
+serde_json = "1.0.140"
+tokio = { version = "1.44.1", features = ["full"] }
+tracing = { version = "0.1.41" }
+tracing-subscriber = { version = "0.3.19", features = ["fmt", "env-filter"] }
+
[[example]]
name = "getting-started-consumer"
path = "src/getting-started/consumer/main.rs"
@@ -89,16 +103,3 @@ path = "src/stream-builder/stream-producer/main.rs"
name = "stream-producer-config"
path = "src/stream-builder/stream-producer-config/main.rs"
-[dependencies]
-ahash = { version = "0.8.11", features = ["serde"] }
-anyhow = "1.0.97"
-bytes = "1.10.1"
-clap = { version = "4.5.34", features = ["derive"] }
-futures-util = "0.3.31"
-iggy = { path = "../sdk" }
-rand = "0.9.0"
-serde = { version = "1.0.219", features = ["derive", "rc"] }
-serde_json = "1.0.140"
-tokio = { version = "1.44.1", features = ["full"] }
-tracing = { version = "0.1.41" }
-tracing-subscriber = { version = "0.3.19", features = ["fmt", "env-filter"] }
diff --git a/examples/src/basic/consumer/main.rs b/examples/src/basic/consumer/main.rs
index 6fc1cbb8..7de50d3f 100644
--- a/examples/src/basic/consumer/main.rs
+++ b/examples/src/basic/consumer/main.rs
@@ -17,11 +17,7 @@
*/
use clap::Parser;
-use iggy::client::Client;
-use iggy::client_provider;
-use iggy::client_provider::ClientProviderConfig;
-use iggy::clients::client::IggyClient;
-use iggy::models::messages::PolledMessage;
+use iggy::prelude::*;
use iggy_examples::shared::args::Args;
use iggy_examples::shared::system;
use std::error::Error;
@@ -50,12 +46,12 @@ async fn main() -> Result<(), Box<dyn Error>> {
system::consume_messages(&args, &client, &handle_message).await
}
-fn handle_message(message: &PolledMessage) -> Result<(), Box<dyn Error>> {
+fn handle_message(message: &IggyMessage) -> Result<(), Box<dyn Error>> {
// The payload can be of any type as it is a raw byte array. In this case it's a simple string.
let payload = std::str::from_utf8(&message.payload)?;
info!(
"Handling message at offset: {}, payload: {}...",
- message.offset, payload
+ message.header.offset, payload
);
Ok(())
}
diff --git a/examples/src/basic/producer/main.rs b/examples/src/basic/producer/main.rs
index 6b5595db..17296335 100644
--- a/examples/src/basic/producer/main.rs
+++ b/examples/src/basic/producer/main.rs
@@ -17,11 +17,7 @@
*/
use clap::Parser;
-use iggy::client::Client;
-use iggy::client_provider;
-use iggy::client_provider::ClientProviderConfig;
-use iggy::clients::client::IggyClient;
-use iggy::messages::send_messages::{Message, Partitioning};
+use iggy::prelude::*;
use iggy_examples::shared::args::Args;
use iggy_examples::shared::system;
use std::error::Error;
@@ -82,7 +78,7 @@ async fn produce_messages(args: &Args, client: &dyn Client) -> Result<(), Box<dy
for _ in 0..args.messages_per_batch {
current_id += 1;
let payload = format!("message-{current_id}");
- let message = Message::from_str(&payload)?;
+ let message = IggyMessage::from_str(&payload)?;
messages.push(message);
sent_messages.push(payload);
}
diff --git a/examples/src/getting-started/consumer/main.rs b/examples/src/getting-started/consumer/main.rs
index 0cf7f73a..6280a335 100644
--- a/examples/src/getting-started/consumer/main.rs
+++ b/examples/src/getting-started/consumer/main.rs
@@ -16,13 +16,7 @@
* under the License.
*/
-use iggy::client::{Client, UserClient};
-use iggy::clients::builder::IggyClientBuilder;
-use iggy::consumer::Consumer;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::models::messages::PolledMessage;
-use iggy::users::defaults::*;
-use iggy::utils::duration::IggyDuration;
+use iggy::prelude::*;
use std::env;
use std::error::Error;
use std::str::FromStr;
@@ -107,12 +101,12 @@ async fn consume_messages(client: &dyn Client) -> Result<(), Box<dyn Error>> {
}
}
-fn handle_message(message: &PolledMessage) -> Result<(), Box<dyn Error>> {
+fn handle_message(message: &IggyMessage) -> Result<(), Box<dyn Error>> {
// The payload can be of any type as it is a raw byte array. In this case it's a simple string.
let payload = std::str::from_utf8(&message.payload)?;
info!(
"Handling message at offset: {}, payload: {}...",
- message.offset, payload
+ message.header.offset, payload
);
Ok(())
}
diff --git a/examples/src/getting-started/producer/main.rs b/examples/src/getting-started/producer/main.rs
index 1e7a1aaf..60e8a1f4 100644
--- a/examples/src/getting-started/producer/main.rs
+++ b/examples/src/getting-started/producer/main.rs
@@ -16,15 +16,7 @@
* under the License.
*/
-use iggy::client::{Client, StreamClient, TopicClient, UserClient};
-use iggy::clients::builder::IggyClientBuilder;
-use iggy::clients::client::IggyClient;
-use iggy::compression::compression_algorithm::CompressionAlgorithm;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::users::defaults::*;
-use iggy::utils::duration::IggyDuration;
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use std::env;
use std::error::Error;
use std::str::FromStr;
@@ -112,7 +104,7 @@ async fn produce_messages(client: &dyn Client) -> Result<(), Box<dyn Error>> {
for _ in 0..messages_per_batch {
current_id += 1;
let payload = format!("message-{current_id}");
- let message = Message::from_str(&payload)?;
+ let message = IggyMessage::from_str(&payload)?;
messages.push(message);
}
client
diff --git a/examples/src/message-envelope/consumer/main.rs b/examples/src/message-envelope/consumer/main.rs
index 5a416b75..5d9fecbd 100644
--- a/examples/src/message-envelope/consumer/main.rs
+++ b/examples/src/message-envelope/consumer/main.rs
@@ -18,11 +18,7 @@
use anyhow::Result;
use clap::Parser;
-use iggy::client::Client;
-use iggy::client_provider;
-use iggy::client_provider::ClientProviderConfig;
-use iggy::clients::client::IggyClient;
-use iggy::models::messages::PolledMessage;
+use iggy::prelude::*;
use iggy_examples::shared::args::Args;
use iggy_examples::shared::messages::*;
use iggy_examples::shared::system;
@@ -52,14 +48,14 @@ async fn main() -> Result<(), Box<dyn Error>> {
system::consume_messages(&args, &client, &handle_message).await
}
-fn handle_message(message: &PolledMessage) -> Result<(), Box<dyn Error>> {
+fn handle_message(message: &IggyMessage) -> Result<(), Box<dyn Error>> {
// The payload can be of any type as it is a raw byte array. In this case it's a JSON string.
let json = std::str::from_utf8(&message.payload)?;
// The message envelope can be used to send the different types of messages to the same topic.
let envelope = serde_json::from_str::<Envelope>(json)?;
info!(
"Handling message type: {} at offset: {}...",
- envelope.message_type, message.offset
+ envelope.message_type, message.header.offset
);
match envelope.message_type.as_str() {
ORDER_CREATED_TYPE => {
diff --git a/examples/src/message-envelope/producer/main.rs b/examples/src/message-envelope/producer/main.rs
index f12d9047..605c88c4 100644
--- a/examples/src/message-envelope/producer/main.rs
+++ b/examples/src/message-envelope/producer/main.rs
@@ -18,11 +18,7 @@
use anyhow::Result;
use clap::Parser;
-use iggy::client::{Client, MessageClient};
-use iggy::client_provider;
-use iggy::client_provider::ClientProviderConfig;
-use iggy::clients::client::IggyClient;
-use iggy::messages::send_messages::{Message, Partitioning};
+use iggy::prelude::*;
use iggy_examples::shared::args::Args;
use iggy_examples::shared::messages_generator::MessagesGenerator;
use iggy_examples::shared::system;
@@ -84,7 +80,7 @@ async fn produce_messages(args: &Args, client: &IggyClient) -> Result<(), Box<dy
let serializable_message = message_generator.generate();
// You can send the different message types to the same partition, or stick to the single type.
let json_envelope = serializable_message.to_json_envelope();
- let message = Message::from_str(&json_envelope)?;
+ let message = IggyMessage::from_str(&json_envelope)?;
messages.push(message);
// This is used for the logging purposes only.
serializable_messages.push(serializable_message);
diff --git a/examples/src/message-headers/consumer/main.rs b/examples/src/message-headers/consumer/main.rs
index 6ef78a0b..8d643cfe 100644
--- a/examples/src/message-headers/consumer/main.rs
+++ b/examples/src/message-headers/consumer/main.rs
@@ -18,12 +18,7 @@
use anyhow::Result;
use clap::Parser;
-use iggy::client::Client;
-use iggy::client_provider;
-use iggy::client_provider::ClientProviderConfig;
-use iggy::clients::client::IggyClient;
-use iggy::models::header::HeaderKey;
-use iggy::models::messages::PolledMessage;
+use iggy::prelude::*;
use iggy_examples::shared::args::Args;
use iggy_examples::shared::messages::*;
use iggy_examples::shared::system;
@@ -53,21 +48,16 @@ async fn main() -> Result<(), Box<dyn Error>> {
system::consume_messages(&args, &client, &handle_message).await
}
-fn handle_message(message: &PolledMessage) -> Result<(), Box<dyn Error>> {
+fn handle_message(message: &IggyMessage) -> Result<(), Box<dyn Error>> {
// The payload can be of any type as it is a raw byte array. In this case it's a JSON string.
let payload = std::str::from_utf8(&message.payload)?;
// The message type is stored in the custom message header.
let header_key = HeaderKey::new("message_type").unwrap();
- let message_type = message
- .headers
- .as_ref()
- .unwrap()
- .get(&header_key)
- .unwrap()
- .as_str()?;
+ let headers_map = message.user_headers_map()?.unwrap();
+ let message_type = headers_map.get(&header_key).unwrap().as_str()?;
info!(
"Handling message type: {} at offset: {}...",
- message_type, message.offset
+ message_type, message.header.offset
);
match message_type {
ORDER_CREATED_TYPE => {
diff --git a/examples/src/message-headers/producer/main.rs b/examples/src/message-headers/producer/main.rs
index 5ccd963a..5833cce6 100644
--- a/examples/src/message-headers/producer/main.rs
+++ b/examples/src/message-headers/producer/main.rs
@@ -19,12 +19,7 @@
use anyhow::Result;
use bytes::Bytes;
use clap::Parser;
-use iggy::client::{Client, MessageClient};
-use iggy::client_provider;
-use iggy::client_provider::ClientProviderConfig;
-use iggy::clients::client::IggyClient;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::models::header::{HeaderKey, HeaderValue};
+use iggy::prelude::*;
use iggy_examples::shared::args::Args;
use iggy_examples::shared::messages_generator::MessagesGenerator;
use iggy_examples::shared::system;
@@ -96,7 +91,11 @@ async fn produce_messages(args: &Args, client: &IggyClient) -> Result<(), Box<dy
HeaderValue::from_str(message_type).unwrap(),
);
- let message = Message::new(None, Bytes::from(json), Some(headers));
+ let message = IggyMessage::builder()
+ .payload(Bytes::from(json))
+ .headers(headers)
+ .build()
+ .unwrap();
messages.push(message);
// This is used for the logging purposes only.
serializable_messages.push(serializable_message);
diff --git a/examples/src/multi-tenant/consumer/main.rs b/examples/src/multi-tenant/consumer/main.rs
index ac135b89..ded20180 100644
--- a/examples/src/multi-tenant/consumer/main.rs
+++ b/examples/src/multi-tenant/consumer/main.rs
@@ -20,16 +20,7 @@ use ahash::AHashMap;
use clap::Parser;
use futures_util::future::join_all;
use futures_util::StreamExt;
-use iggy::client::{Client, StreamClient, TopicClient, UserClient};
-use iggy::clients::client::IggyClient;
-use iggy::clients::consumer::{AutoCommit, AutoCommitWhen, IggyConsumer};
-use iggy::error::IggyError;
-use iggy::identifier::Identifier;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::models::permissions::{Permissions, StreamPermissions, TopicPermissions};
-use iggy::models::user_status::UserStatus;
-use iggy::users::defaults::{DEFAULT_ROOT_PASSWORD, DEFAULT_ROOT_USERNAME};
-use iggy::utils::duration::IggyDuration;
+use iggy::prelude::*;
use iggy_examples::shared::args::Args;
use std::collections::HashMap;
use std::env;
@@ -251,7 +242,7 @@ fn start_consumers(tenant_id: u32, consumers: Vec<TenantConsumer>) -> Vec<JoinHa
if let Ok(message) = message {
let current_offset = message.current_offset;
let partition_id = message.partition_id;
- let offset = message.message.offset;
+ let offset = message.message.header.offset;
let payload = std::str::from_utf8(&message.message.payload);
if payload.is_err() {
let error = payload.unwrap_err();
diff --git a/examples/src/multi-tenant/producer/main.rs b/examples/src/multi-tenant/producer/main.rs
index ff73850f..faed4eea 100644
--- a/examples/src/multi-tenant/producer/main.rs
+++ b/examples/src/multi-tenant/producer/main.rs
@@ -19,19 +19,7 @@
use ahash::AHashMap;
use clap::Parser;
use futures_util::future::join_all;
-use iggy::client::{Client, StreamClient, UserClient};
-use iggy::clients::builder::IggyClientBuilder;
-use iggy::clients::client::IggyClient;
-use iggy::clients::producer::IggyProducer;
-use iggy::error::IggyError;
-use iggy::identifier::Identifier;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::models::permissions::{Permissions, StreamPermissions};
-use iggy::models::user_status::UserStatus;
-use iggy::users::defaults::{DEFAULT_ROOT_PASSWORD, DEFAULT_ROOT_USERNAME};
-use iggy::utils::duration::IggyDuration;
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use iggy_examples::shared::args::Args;
use std::collections::HashMap;
use std::env;
@@ -234,7 +222,7 @@ fn start_producers(
let mut messages = Vec::with_capacity(batch_size as usize);
for _ in 1..=batch_size {
let payload = format!("{message}-{producer_id}-{message_id}");
- let message = Message::from_str(&payload).expect("Invalid message");
+ let message = IggyMessage::from_str(&payload).expect("Invalid message");
messages.push(message);
}
diff --git a/examples/src/new-sdk/consumer/main.rs b/examples/src/new-sdk/consumer/main.rs
index 3d573e0f..4556d930 100644
--- a/examples/src/new-sdk/consumer/main.rs
+++ b/examples/src/new-sdk/consumer/main.rs
@@ -18,14 +18,7 @@
use clap::Parser;
use futures_util::StreamExt;
-use iggy::client::Client;
-use iggy::client_provider;
-use iggy::client_provider::ClientProviderConfig;
-use iggy::clients::client::IggyClient;
-use iggy::clients::consumer::{AutoCommit, AutoCommitWhen, IggyConsumer, ReceivedMessage};
-use iggy::consumer::ConsumerKind;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::utils::duration::IggyDuration;
+use iggy::prelude::*;
use iggy_examples::shared::args::Args;
use iggy_examples::shared::messages::{
Envelope, OrderConfirmed, OrderCreated, OrderRejected, ORDER_CONFIRMED_TYPE,
@@ -112,7 +105,10 @@ fn handle_message(message: &ReceivedMessage) -> anyhow::Result<(), Box<dyn Error
let envelope = serde_json::from_str::<Envelope>(json)?;
info!(
"Handling message type: {} at offset: {} in partition ID: {} with current offset: {}",
- envelope.message_type, message.message.offset, message.partition_id, message.current_offset,
+ envelope.message_type,
+ message.message.header.offset,
+ message.partition_id,
+ message.current_offset,
);
match envelope.message_type.as_str() {
ORDER_CREATED_TYPE => {
diff --git a/examples/src/new-sdk/producer/main.rs b/examples/src/new-sdk/producer/main.rs
index f73d6c0e..b909921c 100644
--- a/examples/src/new-sdk/producer/main.rs
+++ b/examples/src/new-sdk/producer/main.rs
@@ -17,15 +17,7 @@
*/
use clap::Parser;
-use iggy::client::Client;
-use iggy::client_provider;
-use iggy::client_provider::ClientProviderConfig;
-use iggy::clients::client::IggyClient;
-use iggy::clients::producer::IggyProducer;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::utils::duration::IggyDuration;
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use iggy_examples::shared::args::Args;
use iggy_examples::shared::messages_generator::MessagesGenerator;
use std::error::Error;
@@ -93,7 +85,7 @@ async fn produce_messages(
for _ in 0..args.messages_per_batch {
let serializable_message = message_generator.generate();
let json_envelope = serializable_message.to_json_envelope();
- let message = Message::from_str(&json_envelope)?;
+ let message = IggyMessage::from_str(&json_envelope)?;
messages.push(message);
}
producer.send(messages).await?;
diff --git a/examples/src/shared/system.rs b/examples/src/shared/system.rs
index 41d7e8a5..2ab34485 100644
--- a/examples/src/shared/system.rs
+++ b/examples/src/shared/system.rs
@@ -17,18 +17,10 @@
*/
use crate::shared::args::Args;
-use iggy::client::Client;
-use iggy::compression::compression_algorithm::CompressionAlgorithm;
-use iggy::consumer::{Consumer, ConsumerKind};
-use iggy::error::IggyError;
-use iggy::identifier::Identifier;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::models::messages::PolledMessage;
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use tracing::info;
-type MessageHandler = dyn Fn(&PolledMessage) -> Result<(), Box<dyn std::error::Error>>;
+type MessageHandler = dyn Fn(&IggyMessage) -> Result<(), Box<dyn std::error::Error>>;
pub async fn init_by_consumer(args: &Args, client: &dyn Client) {
let (stream_id, topic_id, partition_id) = (
diff --git a/examples/src/stream-builder/stream-basic/main.rs b/examples/src/stream-builder/stream-basic/main.rs
index d78528cb..e90baaff 100644
--- a/examples/src/stream-builder/stream-basic/main.rs
+++ b/examples/src/stream-builder/stream-basic/main.rs
@@ -17,11 +17,8 @@
*/
use crate::shared::stream::PrintEventConsumer;
-use iggy::client::{Client, StreamClient};
use iggy::consumer_ext::IggyConsumerMessageExt;
-use iggy::error::IggyError;
-use iggy::messages::send_messages::Message;
-use iggy::stream_builder::{IggyStream, IggyStreamConfig};
+use iggy::prelude::*;
use iggy_examples::shared;
use std::str::FromStr;
use tokio::sync::oneshot;
@@ -50,9 +47,15 @@ async fn main() -> Result<(), IggyError> {
});
println!("Send 3 test messages...");
- producer.send_one(Message::from_str("Hello World")?).await?;
- producer.send_one(Message::from_str("Hola Iggy")?).await?;
- producer.send_one(Message::from_str("Hi Apache")?).await?;
+ producer
+ .send_one(IggyMessage::from_str("Hello World")?)
+ .await?;
+ producer
+ .send_one(IggyMessage::from_str("Hola Iggy")?)
+ .await?;
+ producer
+ .send_one(IggyMessage::from_str("Hi Apache")?)
+ .await?;
// Wait a bit for all messages to arrive.
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
diff --git a/examples/src/stream-builder/stream-consumer-config/main.rs b/examples/src/stream-builder/stream-consumer-config/main.rs
index a65d5e35..8006b0ce 100644
--- a/examples/src/stream-builder/stream-consumer-config/main.rs
+++ b/examples/src/stream-builder/stream-consumer-config/main.rs
@@ -16,15 +16,7 @@
* under the License.
*/
-use iggy::client::Client;
-use iggy::clients::consumer::{AutoCommit, AutoCommitWhen};
-use iggy::consumer::ConsumerKind;
-use iggy::consumer_ext::IggyConsumerMessageExt;
-use iggy::error::IggyError;
-use iggy::identifier::Identifier;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::stream_builder::{IggyConsumerConfig, IggyStreamConsumer};
-use iggy::utils::duration::IggyDuration;
+use iggy::prelude::*;
use iggy_examples::shared::stream::PrintEventConsumer;
use std::str::FromStr;
use tokio::sync::oneshot;
diff --git a/examples/src/stream-builder/stream-consumer/main.rs b/examples/src/stream-builder/stream-consumer/main.rs
index 93a74b87..f3faa47d 100644
--- a/examples/src/stream-builder/stream-consumer/main.rs
+++ b/examples/src/stream-builder/stream-consumer/main.rs
@@ -16,10 +16,7 @@
* under the License.
*/
-use iggy::client::Client;
-use iggy::consumer_ext::IggyConsumerMessageExt;
-use iggy::error::IggyError;
-use iggy::stream_builder::{IggyConsumerConfig, IggyStreamConsumer};
+use iggy::prelude::*;
use iggy_examples::shared::stream::PrintEventConsumer;
use tokio::sync::oneshot;
diff --git a/examples/src/stream-builder/stream-producer-config/main.rs b/examples/src/stream-builder/stream-producer-config/main.rs
index 388a2bcc..5dd6e481 100644
--- a/examples/src/stream-builder/stream-producer-config/main.rs
+++ b/examples/src/stream-builder/stream-producer-config/main.rs
@@ -16,12 +16,7 @@
* under the License.
*/
-use iggy::client::{Client, StreamClient};
-use iggy::error::IggyError;
-use iggy::identifier::Identifier;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::stream_builder::{IggyProducerConfig, IggyStreamProducer};
-use iggy::utils::duration::IggyDuration;
+use iggy::prelude::*;
use std::str::FromStr;
const IGGY_URL: &str = "iggy://iggy:iggy@localhost:8090";
@@ -71,7 +66,9 @@ async fn main() -> Result<(), IggyError> {
let (client, producer) = IggyStreamProducer::with_client_from_url(IGGY_URL, &config).await?;
println!("Send 3 test messages...");
- producer.send_one(Message::from_str("Hello World")?).await?;
+ producer
+ .send_one(IggyMessage::from_str("Hello World")?)
+ .await?;
// Wait a bit for all messages to arrive.
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
diff --git a/examples/src/stream-builder/stream-producer/main.rs b/examples/src/stream-builder/stream-producer/main.rs
index 811ecd0f..6a83b63d 100644
--- a/examples/src/stream-builder/stream-producer/main.rs
+++ b/examples/src/stream-builder/stream-producer/main.rs
@@ -16,10 +16,7 @@
* under the License.
*/
-use iggy::client::{Client, StreamClient};
-use iggy::error::IggyError;
-use iggy::messages::send_messages::Message;
-use iggy::stream_builder::{IggyProducerConfig, IggyStreamProducer};
+use iggy::prelude::*;
use std::str::FromStr;
const IGGY_URL: &str = "iggy://iggy:iggy@localhost:8090";
@@ -32,9 +29,15 @@ async fn main() -> Result<(), IggyError> {
let (client, producer) = IggyStreamProducer::with_client_from_url(IGGY_URL, &config).await?;
println!("Send 3 test messages...");
- producer.send_one(Message::from_str("Hello World")?).await?;
- producer.send_one(Message::from_str("Hola Iggy")?).await?;
- producer.send_one(Message::from_str("Hi Apache")?).await?;
+ producer
+ .send_one(IggyMessage::from_str("Hello World")?)
+ .await?;
+ producer
+ .send_one(IggyMessage::from_str("Hola Iggy")?)
+ .await?;
+ producer
+ .send_one(IggyMessage::from_str("Hi Apache")?)
+ .await?;
// Wait a bit for all messages to arrive.
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
diff --git a/integration/Cargo.toml b/integration/Cargo.toml
index 5e339829..bf68668c 100644
--- a/integration/Cargo.toml
+++ b/integration/Cargo.toml
@@ -21,6 +21,11 @@ version = "0.0.1"
edition = "2021"
license = "Apache-2.0"
+# Some tests are failing in CI due to lack of IPv6 interfaces
+# inside the docker containers. This is a temporary workaround (hopefully).
+[features]
+ci-qemu = []
+
[dependencies]
ahash = { version = "0.8.11", features = ["serde"] }
assert_cmd = "2.0.16"
@@ -48,8 +53,3 @@ tracing-subscriber = { version = "0.3.19", features = ["fmt", "env-filter"] }
twox-hash = { version = "2.1.0", features = ["xxhash32"] }
uuid = { version = "1.16.0", features = ["v7", "fast-rng", "zerocopy"] }
zip = "2.5.0"
-
-# Some tests are failing in CI due to lack of IPv6 interfaces
-# inside the docker containers. This is a temporary workaround (hopefully).
-[features]
-ci-qemu = []
diff --git a/integration/tests/cli/consumer_offset/test_consumer_offset_get_command.rs b/integration/tests/cli/consumer_offset/test_consumer_offset_get_command.rs
index 9e9b1a8a..a1699236 100644
--- a/integration/tests/cli/consumer_offset/test_consumer_offset_get_command.rs
+++ b/integration/tests/cli/consumer_offset/test_consumer_offset_get_command.rs
@@ -22,12 +22,7 @@ use crate::cli::common::{
};
use assert_cmd::assert::Assert;
use async_trait::async_trait;
-use iggy::client::Client;
-use iggy::consumer::{Consumer, ConsumerKind};
-use iggy::identifier::Identifier;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use predicates::str::{contains, starts_with};
use serial_test::parallel;
use std::str::FromStr;
@@ -122,7 +117,7 @@ impl IggyCmdTestCase for TestConsumerOffsetGetCmd {
assert!(topic.is_ok());
let mut messages = (1..=self.messages_count)
- .filter_map(|id| Message::from_str(format!("Test message {id}").as_str()).ok())
+ .filter_map(|id| IggyMessage::from_str(format!("Test message {id}").as_str()).ok())
.collect::<Vec<_>>();
let send_status = client
diff --git a/integration/tests/cli/consumer_offset/test_consumer_offset_set_command.rs b/integration/tests/cli/consumer_offset/test_consumer_offset_set_command.rs
index 0f357500..3ab26704 100644
--- a/integration/tests/cli/consumer_offset/test_consumer_offset_set_command.rs
+++ b/integration/tests/cli/consumer_offset/test_consumer_offset_set_command.rs
@@ -22,12 +22,7 @@ use crate::cli::common::{
};
use assert_cmd::assert::Assert;
use async_trait::async_trait;
-use iggy::client::Client;
-use iggy::consumer::{Consumer, ConsumerKind};
-use iggy::identifier::Identifier;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use predicates::str::diff;
use serial_test::parallel;
use std::str::FromStr;
@@ -122,7 +117,7 @@ impl IggyCmdTestCase for TestConsumerOffsetSetCmd {
assert!(topic.is_ok());
let mut messages = (1..=self.stored_offset + 1)
- .filter_map(|id| Message::from_str(format!("Test message {id}").as_str()).ok())
+ .filter_map(|id| IggyMessage::from_str(format!("Test message {id}").as_str()).ok())
.collect::<Vec<_>>();
let send_status = client
diff --git a/integration/tests/cli/message/test_message_poll_command.rs b/integration/tests/cli/message/test_message_poll_command.rs
index a196b6e1..072a618d 100644
--- a/integration/tests/cli/message/test_message_poll_command.rs
+++ b/integration/tests/cli/message/test_message_poll_command.rs
@@ -23,12 +23,7 @@ use crate::cli::common::{
use assert_cmd::assert::Assert;
use async_trait::async_trait;
use bytes::Bytes;
-use iggy::client::Client;
-use iggy::messages::poll_messages::{PollingKind, PollingStrategy};
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::models::header::{HeaderKey, HeaderValue};
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use predicates::str::{contains, starts_with};
use serial_test::parallel;
use std::collections::HashMap;
@@ -150,7 +145,7 @@ impl IggyCmdTestCase for TestMessagePollCmd {
.iter()
.map(|s| {
let payload = Bytes::from(s.as_bytes().to_vec());
- Message::new(None, payload, Some(HashMap::from([self.headers.clone()])))
+ IggyMessage::with_headers(payload, HashMap::from([self.headers.clone()]))
})
.collect::<Vec<_>>();
diff --git a/integration/tests/cli/message/test_message_poll_to_file_command.rs b/integration/tests/cli/message/test_message_poll_to_file_command.rs
index 921b01a8..6afb7b29 100644
--- a/integration/tests/cli/message/test_message_poll_to_file_command.rs
+++ b/integration/tests/cli/message/test_message_poll_to_file_command.rs
@@ -20,13 +20,7 @@ use crate::cli::common::{IggyCmdCommand, IggyCmdTest, IggyCmdTestCase};
use assert_cmd::assert::Assert;
use async_trait::async_trait;
use bytes::Bytes;
-use iggy::client::Client;
-use iggy::identifier::Identifier;
-use iggy::messages::poll_messages::{PollingKind, PollingStrategy};
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::models::header::{HeaderKey, HeaderValue};
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use predicates::str::{contains, is_match, starts_with};
use serial_test::parallel;
use std::collections::HashMap;
@@ -130,7 +124,7 @@ impl IggyCmdTestCase for TestMessagePollToFileCmd<'_> {
.iter()
.map(|s| {
let payload = Bytes::from(s.as_bytes().to_vec());
- Message::new(None, payload, Some(self.headers.clone()))
+ IggyMessage::with_headers(payload, self.headers.clone())
})
.collect::<Vec<_>>();
diff --git a/integration/tests/cli/message/test_message_reply_via_file.rs b/integration/tests/cli/message/test_message_reply_via_file.rs
index 99a26c14..f4cbd6c6 100644
--- a/integration/tests/cli/message/test_message_reply_via_file.rs
+++ b/integration/tests/cli/message/test_message_reply_via_file.rs
@@ -19,8 +19,7 @@
use crate::cli::common::IggyCmdTest;
use crate::cli::message::test_message_poll_to_file_command::TestMessagePollToFileCmd;
use crate::cli::message::test_message_send_from_file_command::TestMessageSendFromFileCmd;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::models::header::{HeaderKey, HeaderValue};
+use iggy::prelude::*;
use serial_test::parallel;
use std::collections::HashMap;
use std::str::FromStr;
diff --git a/integration/tests/cli/message/test_message_send_command.rs b/integration/tests/cli/message/test_message_send_command.rs
index 0528c243..74524335 100644
--- a/integration/tests/cli/message/test_message_send_command.rs
+++ b/integration/tests/cli/message/test_message_send_command.rs
@@ -22,12 +22,7 @@ use crate::cli::common::{
};
use assert_cmd::assert::Assert;
use async_trait::async_trait;
-use iggy::client::Client;
-use iggy::consumer::Consumer;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::models::header::{HeaderKey, HeaderValue};
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use predicates::str::diff;
use serial_test::parallel;
use std::collections::HashMap;
@@ -248,8 +243,8 @@ impl IggyCmdTestCase for TestMessageSendCmd {
if let Some(expected_header) = &self.header {
polled_messages.messages.iter().for_each(|m| {
- assert!(m.headers.is_some());
- assert_eq!(expected_header, m.headers.as_ref().unwrap());
+ assert!(m.user_headers.is_some());
+ assert_eq!(expected_header, &m.user_headers_map().unwrap().unwrap());
})
};
@@ -435,7 +430,7 @@ Options:
-H, --headers <HEADERS>
Comma separated list of key:kind:value, sent as header with the message
{CLAP_INDENT}
- Headers are comma seperated key-value pairs that can be sent with the message.
+ Headers are comma separated key-value pairs that can be sent with the message.
Kind can be one of the following: raw, string, bool, int8, int16, int32, int64,
int128, uint8, uint16, uint32, uint64, uint128, float32, float64
diff --git a/integration/tests/cli/message/test_message_send_from_file_command.rs b/integration/tests/cli/message/test_message_send_from_file_command.rs
index 8fcba389..457c1e83 100644
--- a/integration/tests/cli/message/test_message_send_from_file_command.rs
+++ b/integration/tests/cli/message/test_message_send_from_file_command.rs
@@ -20,15 +20,7 @@ use crate::cli::common::{IggyCmdCommand, IggyCmdTest, IggyCmdTestCase};
use assert_cmd::assert::Assert;
use async_trait::async_trait;
use bytes::Bytes;
-use iggy::bytes_serializable::BytesSerializable;
-use iggy::client::Client;
-use iggy::consumer::Consumer;
-use iggy::identifier::Identifier;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::messages::send_messages::Message;
-use iggy::models::header::{HeaderKey, HeaderValue};
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use predicates::str::{ends_with, is_match, starts_with};
use serial_test::parallel;
use std::collections::HashMap;
@@ -127,15 +119,15 @@ impl IggyCmdTestCase for TestMessageSendFromFileCmd<'_> {
.iter()
.map(|s| {
let payload = Bytes::from(s.as_bytes().to_vec());
- Message::new(None, payload, Some(self.headers.clone()))
+ IggyMessage::with_headers(payload, self.headers.clone())
})
.collect::<Vec<_>>();
for message in messages.iter() {
- let message = Message::new(
- Some(message.id),
+ let message = IggyMessage::with_id_and_headers(
+ message.header.id,
message.payload.clone(),
- message.headers.clone(),
+ message.user_headers_map().unwrap().unwrap(),
);
let write_result = file.write_all(&message.to_bytes()).await;
@@ -214,8 +206,11 @@ impl IggyCmdTestCase for TestMessageSendFromFileCmd<'_> {
message.payload,
Bytes::from(self.messages[i].as_bytes().to_vec())
);
- assert_eq!(message.headers.is_some(), !self.headers.is_empty());
- assert_eq!(message.headers.as_ref().unwrap(), &self.headers);
+ assert_eq!(
+ message.user_headers_map().unwrap().is_some(),
+ !self.headers.is_empty()
+ );
+ assert_eq!(&message.user_headers_map().unwrap().unwrap(), &self.headers);
}
let topic_delete = client.delete_topic(&stream_id, &topic_id).await;
diff --git a/integration/tests/cli/stream/test_stream_purge_command.rs b/integration/tests/cli/stream/test_stream_purge_command.rs
index 445f5702..f8ce290b 100644
--- a/integration/tests/cli/stream/test_stream_purge_command.rs
+++ b/integration/tests/cli/stream/test_stream_purge_command.rs
@@ -22,10 +22,7 @@ use crate::cli::common::{
};
use assert_cmd::assert::Assert;
use async_trait::async_trait;
-use iggy::client::Client;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use predicates::str::diff;
use serial_test::parallel;
use std::str::FromStr;
@@ -81,7 +78,7 @@ impl IggyCmdTestCase for TestStreamPurgeCmd {
let mut messages = (1..100)
.map(|n| format!("message {}", n))
- .filter_map(|s| Message::from_str(s.as_str()).ok())
+ .filter_map(|s| IggyMessage::from_str(s.as_str()).ok())
.collect::<Vec<_>>();
let send_status = client
diff --git a/integration/tests/cli/topic/test_topic_purge_command.rs b/integration/tests/cli/topic/test_topic_purge_command.rs
index aaf01abf..d25b7f20 100644
--- a/integration/tests/cli/topic/test_topic_purge_command.rs
+++ b/integration/tests/cli/topic/test_topic_purge_command.rs
@@ -22,10 +22,7 @@ use crate::cli::common::{
};
use assert_cmd::assert::Assert;
use async_trait::async_trait;
-use iggy::client::Client;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use predicates::str::diff;
use serial_test::parallel;
use std::str::FromStr;
@@ -97,7 +94,7 @@ impl IggyCmdTestCase for TestTopicPurgeCmd {
let mut messages = (1..100)
.map(|n| format!("message {}", n))
- .filter_map(|s| Message::from_str(s.as_str()).ok())
+ .filter_map(|s| IggyMessage::from_str(s.as_str()).ok())
.collect::<Vec<_>>();
let send_status = client
diff --git a/integration/tests/examples/mod.rs b/integration/tests/examples/mod.rs
index 3c9227d9..9fd22c0e 100644
--- a/integration/tests/examples/mod.rs
+++ b/integration/tests/examples/mod.rs
@@ -118,7 +118,7 @@ impl<'a> IggyExampleTest<'a> {
pub(crate) async fn setup(&mut self, existing_stream_and_topic: bool) {
self.client.connect().await.unwrap();
let ping_result = self.client.ping().await;
- assert!(ping_result.is_ok());
+ assert!(ping_result.is_ok(), "Failed to ping server");
self.client
.login_user(DEFAULT_ROOT_USERNAME, DEFAULT_ROOT_PASSWORD)
.await
@@ -185,6 +185,11 @@ impl IggyExampleTest<'_> {
.as_ref()
.to_string()
});
+
+ let producer_stdout = producer_handle
+ .await
+ .expect("Failed to join producer, check producer logs");
+
let consumer_handle = tokio::spawn(async move {
let consumer_assert = consumer_cmd
.timeout(Duration::from_secs(10))
@@ -195,9 +200,11 @@ impl IggyExampleTest<'_> {
.as_ref()
.to_string()
});
- (
- producer_handle.await.unwrap(),
- consumer_handle.await.unwrap(),
- )
+
+ let consumer_stdout = consumer_handle
+ .await
+ .expect("Failed to join consumer, check consumer logs");
+
+ (producer_stdout, consumer_stdout)
}
}
diff --git a/integration/tests/mod.rs b/integration/tests/mod.rs
index 53af6fd3..557fa10a 100644
--- a/integration/tests/mod.rs
+++ b/integration/tests/mod.rs
@@ -18,7 +18,7 @@
use ctor::{ctor, dtor};
use lazy_static::lazy_static;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::RwLock;
@@ -39,7 +39,8 @@ lazy_static! {
static ref TESTS_FAILED: AtomicBool = AtomicBool::new(false);
static ref LOGS_BUFFER: Arc<RwLock<HashMap<String, Vec<u8>>>> =
Arc::new(RwLock::new(HashMap::new()));
- static ref FAILED_TEST_CASES: Arc<RwLock<Vec<String>>> = Arc::new(RwLock::new(Vec::new()));
+ static ref FAILED_TEST_CASES: Arc<RwLock<HashSet<String>>> =
+ Arc::new(RwLock::new(HashSet::new()));
}
static INIT: Once = Once::new();
@@ -50,7 +51,7 @@ fn setup() {
let mut logger = env_logger::builder();
logger.is_test(true);
- logger.filter(None, log::LevelFilter::Debug);
+ logger.filter(None, log::LevelFilter::Info);
logger.target(env_logger::Target::Pipe(Box::new(LogWriter(log_buffer))));
logger.format(move |buf, record| {
let timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.6f");
@@ -67,7 +68,10 @@ fn setup() {
let thread = thread::current();
let thread_name = thread.name().unwrap_or(UNKNOWN_TEST_NAME);
let failed_tests = FAILED_TEST_CASES.clone();
- failed_tests.write().unwrap().push(thread_name.to_string());
+ failed_tests
+ .write()
+ .unwrap()
+ .insert(thread_name.to_string());
// If a test panics, set the failure flag to true
TESTS_FAILED.store(true, Ordering::SeqCst);
diff --git a/integration/tests/server/scenarios/consumer_group_with_multiple_clients_polling_messages_scenario.rs b/integration/tests/server/scenarios/consumer_group_with_multiple_clients_polling_messages_scenario.rs
index 756b3324..b0a4a004 100644
--- a/integration/tests/server/scenarios/consumer_group_with_multiple_clients_polling_messages_scenario.rs
+++ b/integration/tests/server/scenarios/consumer_group_with_multiple_clients_polling_messages_scenario.rs
@@ -21,16 +21,7 @@ use crate::server::scenarios::{
CONSUMER_GROUP_NAME, MESSAGES_COUNT, PARTITIONS_COUNT, STREAM_ID, STREAM_NAME, TOPIC_ID,
TOPIC_NAME,
};
-use iggy::client::{ConsumerGroupClient, MessageClient, StreamClient, SystemClient, TopicClient};
-use iggy::clients::client::IggyClient;
-use iggy::compression::compression_algorithm::CompressionAlgorithm;
-use iggy::consumer::Consumer;
-use iggy::identifier::Identifier;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::models::consumer_group::ConsumerGroupDetails;
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use integration::test_server::{
assert_clean_system, create_user, login_root, login_user, ClientFactory,
};
@@ -122,7 +113,7 @@ async fn execute_using_messages_key_key(
) {
// 1. Send messages to the calculated partition ID on the server side by using entity ID as a key
for entity_id in 1..=MESSAGES_COUNT {
- let message = Message::from_str(&create_message_payload(entity_id)).unwrap();
+ let message = IggyMessage::from_str(&create_message_payload(entity_id)).unwrap();
let mut messages = vec![message];
system_client
.send_messages(
@@ -185,7 +176,8 @@ async fn execute_using_none_key(
}
let message =
- Message::from_str(&create_extended_message_payload(partition_id, entity_id)).unwrap();
+ IggyMessage::from_str(&create_extended_message_payload(partition_id, entity_id))
+ .unwrap();
let mut messages = vec![message];
system_client
.send_messages(
@@ -239,7 +231,7 @@ async fn validate_message_polling(client: &IggyClient, consumer_group: &Consumer
assert_eq!(polled_messages.messages.len(), 1);
let message = &polled_messages.messages[0];
let offset = (i - 1) as u64;
- assert_eq!(message.offset, offset);
+ assert_eq!(message.header.offset, offset);
let entity_id = start_entity_id + ((i - 1) * PARTITIONS_COUNT);
let payload = from_utf8(&message.payload).unwrap();
assert_eq!(
diff --git a/integration/tests/server/scenarios/consumer_group_with_single_client_polling_messages_scenario.rs b/integration/tests/server/scenarios/consumer_group_with_single_client_polling_messages_scenario.rs
index a426d035..55688839 100644
--- a/integration/tests/server/scenarios/consumer_group_with_single_client_polling_messages_scenario.rs
+++ b/integration/tests/server/scenarios/consumer_group_with_single_client_polling_messages_scenario.rs
@@ -21,15 +21,7 @@ use crate::server::scenarios::{
CONSUMER_GROUP_NAME, MESSAGES_COUNT, PARTITIONS_COUNT, STREAM_ID, STREAM_NAME, TOPIC_ID,
TOPIC_NAME,
};
-use iggy::client::{ConsumerGroupClient, MessageClient, StreamClient, SystemClient, TopicClient};
-use iggy::clients::client::IggyClient;
-use iggy::compression::compression_algorithm::CompressionAlgorithm;
-use iggy::consumer::Consumer;
-use iggy::identifier::Identifier;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use integration::test_server::{assert_clean_system, login_root, ClientFactory};
use std::str::{from_utf8, FromStr};
@@ -101,7 +93,7 @@ async fn init_system(client: &IggyClient) {
async fn execute_using_messages_key_key(client: &IggyClient) {
// 1. Send messages to the calculated partition ID on the server side by using entity ID as a key
for entity_id in 1..=MESSAGES_COUNT {
- let message = Message::from_str(&create_message_payload(entity_id)).unwrap();
+ let message = IggyMessage::from_str(&create_message_payload(entity_id)).unwrap();
let mut messages = vec![message];
client
.send_messages(
@@ -150,7 +142,8 @@ async fn execute_using_none_key(client: &IggyClient) {
}
let message =
- Message::from_str(&create_extended_message_payload(partition_id, entity_id)).unwrap();
+ IggyMessage::from_str(&create_extended_message_payload(partition_id, entity_id))
+ .unwrap();
let mut messages = vec![message];
client
.send_messages(
@@ -168,7 +161,7 @@ async fn execute_using_none_key(client: &IggyClient) {
let mut partition_id = 1;
let mut offset = 0;
let mut entity_id = 1;
- for _ in 1..=PARTITIONS_COUNT * MESSAGES_COUNT {
+ for i in 1..=PARTITIONS_COUNT * MESSAGES_COUNT {
let polled_messages = client
.poll_messages(
&Identifier::numeric(STREAM_ID).unwrap(),
@@ -182,9 +175,13 @@ async fn execute_using_none_key(client: &IggyClient) {
.await
.unwrap();
- assert_eq!(polled_messages.messages.len(), 1);
+ assert_eq!(
+ polled_messages.messages.len(),
+ 1,
+ "polled messages count is not 1 at iteration {i}"
+ );
let message = &polled_messages.messages[0];
- assert_eq!(message.offset, offset);
+ assert_eq!(message.header.offset, offset);
let payload = from_utf8(&message.payload).unwrap();
assert_eq!(
payload,
diff --git a/integration/tests/server/scenarios/create_message_payload.rs b/integration/tests/server/scenarios/create_message_payload.rs
index 4277d5e8..e713c5fe 100644
--- a/integration/tests/server/scenarios/create_message_payload.rs
+++ b/integration/tests/server/scenarios/create_message_payload.rs
@@ -17,14 +17,7 @@
*/
use bytes::Bytes;
-use iggy::client::{MessageClient, StreamClient, TopicClient};
-use iggy::clients::client::IggyClient;
-use iggy::consumer::Consumer;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::models::header::{HeaderKey, HeaderValue};
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use integration::test_server::{assert_clean_system, login_root, ClientFactory};
use std::collections::HashMap;
use std::str::FromStr;
@@ -50,12 +43,8 @@ pub async fn run(client_factory: &dyn ClientFactory) {
let id = (offset + 1) as u128;
let payload = create_message_payload(offset as u64);
let headers = create_message_headers();
- messages.push(Message {
- id,
- length: payload.len() as u32,
- payload,
- headers: Some(headers),
- });
+ let message = IggyMessage::with_id_and_headers(id, payload, headers);
+ messages.push(message);
}
client
@@ -85,8 +74,8 @@ pub async fn run(client_factory: &dyn ClientFactory) {
assert_eq!(polled_messages.messages.len() as u32, MESSAGES_COUNT);
for i in 0..MESSAGES_COUNT {
let message = polled_messages.messages.get(i as usize).unwrap();
- assert!(message.headers.is_some());
- let headers = message.headers.as_ref().unwrap();
+ assert!(message.user_headers.is_some());
+ let headers = message.user_headers_map().unwrap().unwrap();
assert_eq!(headers.len(), 3);
assert_eq!(
headers
diff --git a/integration/tests/server/scenarios/message_headers_scenario.rs b/integration/tests/server/scenarios/message_headers_scenario.rs
index 833c1f89..8d3309fc 100644
--- a/integration/tests/server/scenarios/message_headers_scenario.rs
+++ b/integration/tests/server/scenarios/message_headers_scenario.rs
@@ -21,16 +21,7 @@ use crate::server::scenarios::{
TOPIC_ID, TOPIC_NAME,
};
use bytes::Bytes;
-use iggy::client::{MessageClient, StreamClient, TopicClient};
-use iggy::clients::client::IggyClient;
-use iggy::compression::compression_algorithm::CompressionAlgorithm;
-use iggy::consumer::Consumer;
-use iggy::identifier::Identifier;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::models::header::{HeaderKey, HeaderValue};
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use integration::test_server::{assert_clean_system, login_root, ClientFactory};
use std::collections::HashMap;
use std::str::FromStr;
@@ -46,12 +37,7 @@ pub async fn run(client_factory: &dyn ClientFactory) {
let id = (offset + 1) as u128;
let payload = create_message_payload(offset as u64);
let headers = create_message_headers();
- messages.push(Message {
- id,
- length: payload.len() as u32,
- payload,
- headers: Some(headers),
- });
+ messages.push(IggyMessage::with_id_and_headers(id, payload, headers));
}
client
@@ -82,8 +68,8 @@ pub async fn run(client_factory: &dyn ClientFactory) {
assert_eq!(polled_messages.messages.len() as u32, MESSAGES_COUNT);
for i in 0..MESSAGES_COUNT {
let message = polled_messages.messages.get(i as usize).unwrap();
- assert!(message.headers.is_some());
- let headers = message.headers.as_ref().unwrap();
+ assert!(message.user_headers.is_some());
+ let headers = message.user_headers_map().unwrap().unwrap();
assert_eq!(headers.len(), 3);
assert_eq!(
headers
diff --git a/integration/tests/server/scenarios/message_size_scenario.rs b/integration/tests/server/scenarios/message_size_scenario.rs
index 5d8a05e0..9dc26e21 100644
--- a/integration/tests/server/scenarios/message_size_scenario.rs
+++ b/integration/tests/server/scenarios/message_size_scenario.rs
@@ -17,15 +17,7 @@
*/
use bytes::Bytes;
-use iggy::client::{MessageClient, StreamClient, TopicClient};
-use iggy::clients::client::IggyClient;
-use iggy::consumer::Consumer;
-use iggy::error::IggyError;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::models::header::{HeaderKey, HeaderValue};
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use integration::test_server::{assert_clean_system, login_root, ClientFactory};
use std::collections::HashMap;
use std::str::FromStr;
@@ -36,7 +28,7 @@ const STREAM_NAME: &str = "test-stream";
const TOPIC_NAME: &str = "test-topic";
const PARTITIONS_COUNT: u32 = 3;
const PARTITION_ID: u32 = 1;
-const MAX_HEADER_SIZE: usize = 255;
+const MAX_SINGLE_HEADER_SIZE: usize = 200;
enum MessageToSend {
NoMessage,
@@ -82,7 +74,7 @@ pub async fn run(client_factory: &dyn ClientFactory) {
send_message_and_check_result(
&client,
MessageToSend::OfSizeWithHeaders(100_001, 10_000_000),
- Err(IggyError::TooBigHeadersPayload),
+ Err(IggyError::TooBigUserHeaders),
)
.await;
send_message_and_check_result(
@@ -190,29 +182,41 @@ fn create_string_of_size(size: usize) -> String {
"x".repeat(size)
}
-fn create_message_header_of_size(size: usize) -> HashMap<HeaderKey, HeaderValue> {
+fn create_message_header_of_size(target_size: usize) -> HashMap<HeaderKey, HeaderValue> {
let mut headers = HashMap::new();
let mut header_id = 1;
- let mut size = size;
+ let mut current_size = 0;
- while size > 0 {
- let header_size = if size > MAX_HEADER_SIZE {
- MAX_HEADER_SIZE
+ while current_size < target_size {
+ let remaining_size = target_size - current_size;
+
+ let key_str = format!("header-{header_id}");
+ let key_overhead = 4; // 4 bytes for key length
+ let value_overhead = 5; // 1 byte for type + 4 bytes for value length
+ let total_overhead = key_overhead + key_str.len() + value_overhead;
+
+ let value_size = if remaining_size <= total_overhead {
+ break;
+ } else if remaining_size - total_overhead > MAX_SINGLE_HEADER_SIZE {
+ MAX_SINGLE_HEADER_SIZE
} else {
- size
+ remaining_size - total_overhead
};
- headers.insert(
- HeaderKey::new(format!("header-{header_id}").as_str()).unwrap(),
- HeaderValue::from_str(create_string_of_size(header_size).as_str()).unwrap(),
- );
+
+ let key = HeaderKey::new(key_str.as_str()).unwrap();
+ let value = HeaderValue::from_str(create_string_of_size(value_size).as_str()).unwrap();
+
+ let actual_header_size = 4 + key_str.len() + 1 + 4 + value_size;
+ current_size += actual_header_size;
+
+ headers.insert(key, value);
header_id += 1;
- size -= header_size;
}
headers
}
-fn create_message(header_size: Option<usize>, payload_size: usize) -> Message {
+fn create_message(header_size: Option<usize>, payload_size: usize) -> IggyMessage {
let headers = match header_size {
Some(header_size) => {
if header_size > 0 {
@@ -225,10 +229,10 @@ fn create_message(header_size: Option<usize>, payload_size: usize) -> Message {
};
let payload = create_string_of_size(payload_size);
- Message {
- id: 1u128,
- length: payload.len() as u32,
- payload: Bytes::from(payload),
- headers,
+
+ if let Some(headers) = headers {
+ IggyMessage::with_id_and_headers(1u128, Bytes::from(payload), headers)
+ } else {
+ IggyMessage::with_id(1u128, Bytes::from(payload))
}
}
diff --git a/integration/tests/server/scenarios/mod.rs b/integration/tests/server/scenarios/mod.rs
index f0cc2ea1..32fab4c2 100644
--- a/integration/tests/server/scenarios/mod.rs
+++ b/integration/tests/server/scenarios/mod.rs
@@ -46,7 +46,7 @@ const USERNAME_2: &str = "user2";
const USERNAME_3: &str = "user3";
const CONSUMER_ID: u32 = 1;
const CONSUMER_KIND: ConsumerKind = ConsumerKind::Consumer;
-const MESSAGES_COUNT: u32 = 1000;
+const MESSAGES_COUNT: u32 = 1337;
async fn create_client(client_factory: &dyn ClientFactory) -> IggyClient {
let client = client_factory.create_client().await;
diff --git a/integration/tests/server/scenarios/stream_size_validation_scenario.rs b/integration/tests/server/scenarios/stream_size_validation_scenario.rs
index f153f5f0..0e9f5358 100644
--- a/integration/tests/server/scenarios/stream_size_validation_scenario.rs
+++ b/integration/tests/server/scenarios/stream_size_validation_scenario.rs
@@ -18,13 +18,7 @@
use crate::server::scenarios::{create_client, PARTITIONS_COUNT, PARTITION_ID};
use bytes::Bytes;
-use iggy::client::{MessageClient, StreamClient, SystemClient, TopicClient};
-use iggy::clients::client::IggyClient;
-use iggy::compression::compression_algorithm::CompressionAlgorithm;
-use iggy::identifier::Identifier;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use integration::test_server::{assert_clean_system, login_root, ClientFactory};
use std::str::FromStr;
use tracing_subscriber::layer::SubscriberExt;
@@ -36,7 +30,7 @@ const T1_NAME: &str = "test-topic-1";
const S2_NAME: &str = "test-stream-2";
const T2_NAME: &str = "test-topic-2";
const MESSAGE_PAYLOAD_SIZE_BYTES: u64 = 57;
-const MSG_SIZE: u64 = 16 + 8 + 8 + 4 + 4 + 4 + 1 + MESSAGE_PAYLOAD_SIZE_BYTES; // number of bytes in a single message
+const MSG_SIZE: u64 = IGGY_MESSAGE_HEADER_SIZE as u64 + MESSAGE_PAYLOAD_SIZE_BYTES; // number of bytes in a single message
const MSGS_COUNT: u64 = 117; // number of messages in a single topic after one pass of appending
const MSGS_SIZE: u64 = MSG_SIZE * MSGS_COUNT; // number of bytes in a single topic after one pass of appending
@@ -287,18 +281,13 @@ async fn purge_stream(client: &IggyClient, stream_name: &str) {
.unwrap();
}
-fn create_messages() -> Vec<Message> {
+fn create_messages() -> Vec<IggyMessage> {
let mut messages = Vec::new();
for offset in 0..MSGS_COUNT {
let id = (offset + 1) as u128;
let payload = Bytes::from(vec![0xD; MESSAGE_PAYLOAD_SIZE_BYTES as usize]);
- let message = Message {
- id,
- length: payload.len() as u32,
- payload,
- headers: None,
- };
+ let message = IggyMessage::with_id(id, payload);
messages.push(message);
}
messages
diff --git a/integration/tests/server/scenarios/system_scenario.rs b/integration/tests/server/scenarios/system_scenario.rs
index 76280a45..d6e13c84 100644
--- a/integration/tests/server/scenarios/system_scenario.rs
+++ b/integration/tests/server/scenarios/system_scenario.rs
@@ -16,31 +16,15 @@
* under the License.
*/
-use bytes::Bytes;
-use std::str::FromStr;
-
use crate::server::scenarios::{
get_consumer_group, leave_consumer_group, CONSUMER_GROUP_ID, CONSUMER_GROUP_NAME, CONSUMER_ID,
CONSUMER_KIND, MESSAGES_COUNT, PARTITIONS_COUNT, PARTITION_ID, STREAM_ID, STREAM_NAME,
TOPIC_ID, TOPIC_NAME,
};
-use iggy::client::{
- ConsumerGroupClient, ConsumerOffsetClient, MessageClient, PartitionClient, StreamClient,
- SystemClient, TopicClient, UserClient,
-};
-use iggy::clients::client::IggyClient;
-use iggy::compression::compression_algorithm::CompressionAlgorithm;
-use iggy::consumer::Consumer;
-use iggy::error::IggyError;
-use iggy::identifier::Identifier;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::models::messages::PolledMessage;
-use iggy::users::defaults::{DEFAULT_ROOT_PASSWORD, DEFAULT_ROOT_USERNAME};
-use iggy::utils::byte_size::IggyByteSize;
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::topic_size::MaxTopicSize;
+use bytes::Bytes;
+use iggy::prelude::*;
use integration::test_server::{assert_clean_system, ClientFactory};
+use std::str::FromStr;
pub async fn run(client_factory: &dyn ClientFactory) {
let client = client_factory.create_client().await;
@@ -307,7 +291,7 @@ pub async fn run(client_factory: &dyn ClientFactory) {
assert_eq!(topic.name, TOPIC_NAME);
assert_eq!(topic.partitions_count, PARTITIONS_COUNT);
assert_eq!(topic.partitions.len(), PARTITIONS_COUNT as usize);
- assert_eq!(topic.size, 55914);
+ assert_eq!(topic.size, 89806);
assert_eq!(topic.messages_count, MESSAGES_COUNT as u64);
let topic_partition = topic.partitions.get((PARTITION_ID - 1) as usize).unwrap();
assert_eq!(topic_partition.id, PARTITION_ID);
@@ -421,8 +405,8 @@ pub async fn run(client_factory: &dyn ClientFactory) {
.await
.unwrap();
assert_eq!(polled_messages.messages.len() as u32, messages_count);
- let first_offset = polled_messages.messages.first().unwrap().offset;
- let last_offset = polled_messages.messages.last().unwrap().offset;
+ let first_offset = polled_messages.messages.first().unwrap().header.offset;
+ let last_offset = polled_messages.messages.last().unwrap().header.offset;
let expected_last_offset = stored_offset + messages_count as u64;
assert_eq!(first_offset, stored_offset + 1);
assert_eq!(last_offset, expected_last_offset);
@@ -803,24 +787,19 @@ pub async fn run(client_factory: &dyn ClientFactory) {
assert_clean_system(&client).await;
}
-fn assert_message(message: &PolledMessage, offset: u64) {
+fn assert_message(message: &IggyMessage, offset: u64) {
let expected_payload = create_message_payload(offset);
- assert!(message.timestamp > 0);
- assert_eq!(message.offset, offset);
+ assert!(message.header.timestamp > 0);
+ assert_eq!(message.header.offset, offset);
assert_eq!(message.payload, expected_payload);
}
-fn create_messages() -> Vec<Message> {
+fn create_messages() -> Vec<IggyMessage> {
let mut messages = Vec::new();
for offset in 0..MESSAGES_COUNT {
let id = (offset + 1) as u128;
let payload = create_message_payload(offset as u64);
- messages.push(Message {
- id,
- length: payload.len() as u32,
- payload,
- headers: None,
- });
+ messages.push(IggyMessage::with_id(id, payload));
}
messages
}
diff --git a/integration/tests/state/file.rs b/integration/tests/state/file.rs
index 2a771a9a..aae6f92c 100644
--- a/integration/tests/state/file.rs
+++ b/integration/tests/state/file.rs
@@ -53,7 +53,7 @@ async fn should_apply_single_entry() {
});
let command_bytes = command.to_bytes();
- state.apply(user_id, command).await.unwrap();
+ state.apply(user_id, &command).await.unwrap();
let mut entries = state.load_entries().await.unwrap();
assert_eq!(entries.len(), 1);
@@ -79,7 +79,7 @@ async fn should_apply_encrypted_entry() {
});
let command_bytes = command.to_bytes();
- state.apply(user_id, command).await.unwrap();
+ state.apply(user_id, &command).await.unwrap();
let mut entries = state.load_entries().await.unwrap();
assert_eq!(entries.len(), 1);
@@ -110,7 +110,7 @@ async fn should_apply_multiple_entries() {
});
let create_user_bytes = create_user.to_bytes();
- state.apply(first_user_id, create_user).await.unwrap();
+ state.apply(first_user_id, &create_user).await.unwrap();
assert_eq!(state.current_index(), 0);
assert_eq!(state.entries_count(), 1);
@@ -126,7 +126,7 @@ async fn should_apply_multiple_entries() {
});
let create_stream_bytes = create_stream.to_bytes();
- state.apply(second_user_id, create_stream).await.unwrap();
+ state.apply(second_user_id, &create_stream).await.unwrap();
assert_eq!(state.current_index(), 1);
assert_eq!(state.entries_count(), 2);
diff --git a/integration/tests/state/mod.rs b/integration/tests/state/mod.rs
index 48be87dc..31cf2e5b 100644
--- a/integration/tests/state/mod.rs
+++ b/integration/tests/state/mod.rs
@@ -45,7 +45,7 @@ impl StateSetup {
pub async fn create(encryption_key: Option<&[u8]>) -> StateSetup {
let directory_path = format!("state_{}", Uuid::now_v7().to_u128_le());
- let log_path = format!("{}/log", directory_path);
+ let messages_file_path = format!("{}/log", directory_path);
create_dir(&directory_path).await.unwrap();
let version = SemanticVersion::from_str("1.2.3").unwrap();
@@ -55,7 +55,12 @@ impl StateSetup {
Aes256GcmEncryptor::new(key).unwrap(),
))
});
- let state = FileState::new(&log_path, &version, Arc::new(persister), encryptor);
+ let state = FileState::new(
+ &messages_file_path,
+ &version,
+ Arc::new(persister),
+ encryptor,
+ );
Self {
directory_path,
diff --git a/integration/tests/state/system.rs b/integration/tests/state/system.rs
index 5fde9b6b..48cf4d16 100644
--- a/integration/tests/state/system.rs
+++ b/integration/tests/state/system.rs
@@ -149,7 +149,7 @@ async fn should_be_initialized_based_on_state_entries() {
state
.apply(
user_id,
- EntryCommand::CreateUser(CreateUserWithId {
+ &EntryCommand::CreateUser(CreateUserWithId {
user_id,
command: create_user,
}),
@@ -159,7 +159,7 @@ async fn should_be_initialized_based_on_state_entries() {
state
.apply(
user_id,
- EntryCommand::CreateStream(CreateStreamWithId {
+ &EntryCommand::CreateStream(CreateStreamWithId {
stream_id: stream1_id,
command: create_stream1,
}),
@@ -169,7 +169,7 @@ async fn should_be_initialized_based_on_state_entries() {
state
.apply(
user_id,
- EntryCommand::CreateTopic(CreateTopicWithId {
+ &EntryCommand::CreateTopic(CreateTopicWithId {
topic_id: topic1_id,
command: create_topic1,
}),
@@ -179,7 +179,7 @@ async fn should_be_initialized_based_on_state_entries() {
state
.apply(
user_id,
- EntryCommand::CreateStream(CreateStreamWithId {
+ &EntryCommand::CreateStream(CreateStreamWithId {
stream_id: stream2_id,
command: create_stream2,
}),
@@ -189,7 +189,7 @@ async fn should_be_initialized_based_on_state_entries() {
state
.apply(
user_id,
- EntryCommand::CreateTopic(CreateTopicWithId {
+ &EntryCommand::CreateTopic(CreateTopicWithId {
topic_id: topic2_id,
command: create_topic2,
}),
@@ -197,24 +197,24 @@ async fn should_be_initialized_based_on_state_entries() {
.await
.unwrap();
state
- .apply(user_id, EntryCommand::CreatePartitions(create_partitions))
+ .apply(user_id, &EntryCommand::CreatePartitions(create_partitions))
.await
.unwrap();
state
- .apply(user_id, EntryCommand::DeleteStream(delete_stream2))
+ .apply(user_id, &EntryCommand::DeleteStream(delete_stream2))
.await
.unwrap();
state
.apply(
user_id,
- EntryCommand::CreatePersonalAccessToken(create_personal_access_token),
+ &EntryCommand::CreatePersonalAccessToken(create_personal_access_token),
)
.await
.unwrap();
state
.apply(
user_id,
- EntryCommand::CreateConsumerGroup(CreateConsumerGroupWithId {
+ &EntryCommand::CreateConsumerGroup(CreateConsumerGroupWithId {
group_id,
command: create_consumer_group,
}),
diff --git a/integration/tests/streaming/get_by_offset.rs b/integration/tests/streaming/get_by_offset.rs
index f8fc2552..7eab64aa 100644
--- a/integration/tests/streaming/get_by_offset.rs
+++ b/integration/tests/streaming/get_by_offset.rs
@@ -18,17 +18,11 @@
use crate::streaming::common::test_setup::TestSetup;
use bytes::BytesMut;
-use iggy::bytes_serializable::BytesSerializable;
-use iggy::messages::send_messages::Message;
-use iggy::models::header::{HeaderKey, HeaderValue};
-use iggy::utils::byte_size::IggyByteSize;
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::sizeable::Sizeable;
-use iggy::utils::timestamp::IggyTimestamp;
-use server::configs::resource_quota::MemoryResourceQuota;
-use server::configs::system::{CacheConfig, PartitionConfig, SegmentConfig, SystemConfig};
-use server::streaming::batching::appendable_batch_info::AppendableBatchInfo;
+use iggy::prelude::*;
+use server::configs::cache_indexes::CacheIndexesConfig;
+use server::configs::system::{PartitionConfig, SegmentConfig, SystemConfig};
use server::streaming::partitions::partition::Partition;
+use server::streaming::segments::IggyMessagesBatchMut;
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::atomic::{AtomicU32, AtomicU64};
@@ -40,53 +34,66 @@ use test_case::test_matrix;
*/
fn msg_size(size: u64) -> IggyByteSize {
- IggyByteSize::from_str(&format!("{}b", size)).unwrap()
+ IggyByteSize::from_str(&format!("{}B", size)).unwrap()
}
fn segment_size(size: u64) -> IggyByteSize {
- IggyByteSize::from_str(&format!("{}b", size)).unwrap()
+ IggyByteSize::from_str(&format!("{}B", size)).unwrap()
}
fn msgs_req_to_save(count: u32) -> u32 {
count
}
-fn msg_cache_size(size: u64) -> Option<IggyByteSize> {
- if size == 0 {
- return None;
- }
- Some(IggyByteSize::from_str(&format!("{}b", size)).unwrap())
+fn index_cache_all() -> CacheIndexesConfig {
+ CacheIndexesConfig::All
+}
+
+fn index_cache_none() -> CacheIndexesConfig {
+ CacheIndexesConfig::None
+}
+
+fn index_cache_open_segment() -> CacheIndexesConfig {
+ CacheIndexesConfig::OpenSegment
+}
+
+fn small_batches() -> Vec<u32> {
+ vec![3, 4, 5, 6, 7]
+}
+
+fn medium_batches() -> Vec<u32> {
+ vec![10, 20, 30, 40]
}
-fn index_cache_enabled() -> bool {
- true
+fn large_batches() -> Vec<u32> {
+ vec![100, 200, 300, 400]
}
-fn index_cache_disabled() -> bool {
- false
+fn very_large_batches() -> Vec<u32> {
+ vec![500, 1000, 1500, 1000]
}
#[test_matrix(
[msg_size(50), msg_size(1000), msg_size(20000)],
- [msgs_req_to_save(10), msgs_req_to_save(24), msgs_req_to_save(1000)],
- [segment_size(500), segment_size(2000), segment_size(100000)],
- [msg_cache_size(0), msg_cache_size(5000), msg_cache_size(50000), msg_cache_size(2000000)],
- [index_cache_disabled(), index_cache_enabled()])]
+ [small_batches(), medium_batches(), large_batches(), very_large_batches()],
+ [msgs_req_to_save(1), msgs_req_to_save(24), msgs_req_to_save(1000), msgs_req_to_save(10000)],
+ [segment_size(10), segment_size(200), segment_size(10000000)],
+ [index_cache_none(), index_cache_all(), index_cache_open_segment()])]
#[tokio::test]
async fn test_get_messages_by_offset(
message_size: IggyByteSize,
+ batch_sizes: Vec<u32>,
messages_required_to_save: u32,
segment_size: IggyByteSize,
- msg_cache_size: Option<IggyByteSize>,
- index_cache_enabled: bool,
+ cache_indexes: CacheIndexesConfig,
) {
println!(
- "Running test with msg_cache_enabled: {}, messages_required_to_save: {}, segment_size: {}, message_size: {}, cache_indexes: {}",
- msg_cache_size.is_some(),
+ "Running test with message_size: {}, batches: {:?}, messages_required_to_save: {}, segment_size: {}, cache_indexes: {}",
+ message_size,
+ batch_sizes,
messages_required_to_save,
segment_size,
- message_size,
- index_cache_enabled
+ cache_indexes
);
let setup = TestSetup::init().await;
@@ -94,26 +101,17 @@ async fn test_get_messages_by_offset(
let topic_id = 1;
let partition_id = 1;
- // Define batch sizes for 5 appends
- let batch_sizes = [3, 4, 5, 6, 7];
- let total_messages: u32 = batch_sizes.iter().sum();
+ let total_messages_count = batch_sizes.iter().sum();
- let msg_cache_enabled = msg_cache_size.is_some();
- let msg_cache_size =
- MemoryResourceQuota::Bytes(msg_cache_size.unwrap_or(IggyByteSize::from_str("0").unwrap()));
let config = Arc::new(SystemConfig {
path: setup.config.path.to_string(),
- cache: CacheConfig {
- enabled: msg_cache_enabled,
- size: msg_cache_size,
- },
partition: PartitionConfig {
messages_required_to_save,
enforce_fsync: true,
..Default::default()
},
segment: SegmentConfig {
- cache_indexes: index_cache_enabled,
+ cache_indexes,
size: segment_size,
..Default::default()
},
@@ -140,8 +138,10 @@ async fn test_get_messages_by_offset(
setup.create_partitions_directory(stream_id, topic_id).await;
partition.persist().await.unwrap();
- let mut all_messages = Vec::with_capacity(total_messages as usize);
- for i in 1..=total_messages {
+ let mut all_messages = Vec::with_capacity(total_messages_count as usize);
+
+ // Generate all messages as defined in the test matrix
+ for i in 1..=total_messages_count {
let id = i as u128;
let beginning_of_payload = format!("message {}", i);
let mut payload = BytesMut::new();
@@ -162,12 +162,13 @@ async fn test_get_messages_by_offset(
HeaderKey::new("key-3").unwrap(),
HeaderValue::from_uint64(123456).unwrap(),
);
- let message = Message {
- id,
- length: payload.len() as u32,
- payload: payload.clone(),
- headers: Some(headers),
- };
+
+ let message = IggyMessage::builder()
+ .id(id)
+ .payload(payload)
+ .headers(headers)
+ .build()
+ .expect("Failed to create message with valid payload and headers");
all_messages.push(message);
}
@@ -175,130 +176,205 @@ async fn test_get_messages_by_offset(
let mut batch_offsets = Vec::with_capacity(batch_sizes.len());
let mut current_pos = 0;
- // Append all batches
- for batch_size in batch_sizes {
- let batch = all_messages[current_pos..current_pos + batch_size as usize].to_vec();
- let batch_info = AppendableBatchInfo::new(
- batch
- .iter()
- .map(|msg| msg.get_size_bytes())
- .sum::<IggyByteSize>(),
- partition.partition_id,
+ // Append all batches as defined in the test matrix
+ for (batch_idx, &batch_len) in batch_sizes.iter().enumerate() {
+ // If we've generated too many messages, skip the rest
+ if current_pos + batch_len as usize > all_messages.len() {
+ break;
+ }
+
+ println!(
+ "Appending batch {}/{} with {} messages",
+ batch_idx + 1,
+ batch_sizes.len(),
+ batch_len
);
- partition
- .append_messages(batch_info, batch.clone(), None)
- .await
- .unwrap();
+
+ let batch_end_pos = current_pos + batch_len as usize;
+ let messages_slice_to_append = &all_messages[current_pos..batch_end_pos];
+
+ let messages_size = messages_slice_to_append
+ .iter()
+ .map(|m| m.get_size_bytes().as_bytes_u64() as u32)
+ .sum();
+
+ let batch = IggyMessagesBatchMut::from_messages(messages_slice_to_append, messages_size);
+ assert_eq!(batch.count(), batch_len);
+ partition.append_messages(batch, None).await.unwrap();
batch_offsets.push(partition.current_offset);
- current_pos += batch_size as usize;
+ current_pos += batch_len as usize;
}
+ // Use the exact total messages count from the test matrix
+ let total_sent_messages = total_messages_count;
+
// Test 1: All messages from start
let all_loaded_messages = partition
- .get_messages_by_offset(0, total_messages)
+ .get_messages_by_offset(0, total_sent_messages)
.await
.unwrap();
assert_eq!(
- all_loaded_messages.len(),
- total_messages as usize,
+ all_loaded_messages.count(),
+ total_sent_messages,
"Expected {} messages from start, but got {}",
- total_messages,
- all_loaded_messages.len()
+ total_sent_messages,
+ all_loaded_messages.count()
);
// Test 2: Get messages from middle (after 3rd batch)
- let middle_offset = batch_offsets[2];
- let remaining_messages = total_messages - (batch_sizes[0] + batch_sizes[1] + batch_sizes[2]);
- let middle_messages = partition
- .get_messages_by_offset(middle_offset + 1, remaining_messages)
- .await
- .unwrap();
- assert_eq!(
- middle_messages.len(),
- remaining_messages as usize,
- "Expected {} messages from middle offset, but got {}",
- remaining_messages,
- middle_messages.len()
- );
+ if batch_offsets.len() >= 3 {
+ let middle_offset = batch_offsets[2];
+ let prior_batches_sum: u32 = batch_sizes[..3].iter().sum();
+ let remaining_messages = total_sent_messages - prior_batches_sum;
+
+ let middle_messages = partition
+ .get_messages_by_offset(middle_offset + 1, remaining_messages)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ middle_messages.count(),
+ remaining_messages,
+ "Expected {} messages from middle offset, but got {}",
+ remaining_messages,
+ middle_messages.count()
+ );
+ }
// Test 3: No messages beyond final offset
- let final_offset = batch_offsets.last().unwrap();
- let no_messages = partition
- .get_messages_by_offset(final_offset + 1, 1)
- .await
- .unwrap();
- assert_eq!(
- no_messages.len(),
- 0,
- "Expected no messages beyond final offset, but got {}",
- no_messages.len()
- );
+ if !batch_offsets.is_empty() {
+ let final_offset = *batch_offsets.last().unwrap();
+ let no_messages = partition
+ .get_messages_by_offset(final_offset + 1, 1)
+ .await
+ .unwrap();
+ assert_eq!(
+ no_messages.count(),
+ 0,
+ "Expected no messages beyond final offset, but got {}",
+ no_messages.count()
+ );
+ }
// Test 4: Small subset from start
- let subset_size = 3;
+ let subset_size = std::cmp::min(3, total_sent_messages);
let subset_messages = partition
.get_messages_by_offset(0, subset_size)
.await
.unwrap();
assert_eq!(
- subset_messages.len(),
- subset_size as usize,
+ subset_messages.count(),
+ subset_size,
"Expected {} messages in subset from start, but got {}",
subset_size,
- subset_messages.len()
+ subset_messages.count()
);
// Test 5: Messages spanning multiple batches
- let span_offset = batch_offsets[1] + 1; // Start from middle of 2nd batch
- let span_size = 8; // Should span across 2nd, 3rd, and into 4th batch
- let spanning_messages = partition
- .get_messages_by_offset(span_offset, span_size)
- .await
- .unwrap();
- assert_eq!(
- spanning_messages.len(),
- span_size as usize,
- "Expected {} messages spanning multiple batches, but got {}",
- span_size,
- spanning_messages.len()
+ if batch_offsets.len() >= 4 {
+ let span_offset = batch_offsets[1] + 1; // Start from middle of 2nd batch
+ let span_size = 8; // Should span across 2nd, 3rd, and into 4th batch
+ let batches = partition
+ .get_messages_by_offset(span_offset, span_size)
+ .await
+ .unwrap();
+ assert_eq!(
+ batches.count(),
+ span_size,
+ "Expected {} messages spanning multiple batches, but got {}",
+ span_size,
+ batches.count()
+ );
+
+ // Test 6: Validate message content and ordering for all messages
+ let mut i = 0;
+
+ for batch in batches.iter() {
+ for msg in batch.iter() {
+ let expected_offset = span_offset + i as u64;
+ assert!(
+ msg.header().offset() >= expected_offset,
+ "Message offset {} at position {} should be >= expected offset {}",
+ msg.header().offset(),
+ i,
+ expected_offset
+ );
+
+ let original_offset = msg.header().offset() as usize;
+ if original_offset < all_messages.len() {
+ let original_message = &all_messages[original_offset];
+
+ let loaded_id = msg.header().id();
+ let original_id = original_message.header.id;
+ assert_eq!(
+ loaded_id,
+ original_id,
+ "Message ID mismatch at offset {}",
+ msg.header().offset(),
+ );
+
+ let loaded_payload = msg.payload();
+ let original_payload = &original_message.payload;
+ assert_eq!(
+ loaded_payload,
+ original_payload,
+ "Payload mismatch at offset {}",
+ msg.header().offset(),
+ );
+
+ let loaded_headers = msg.user_headers_map().unwrap().unwrap();
+ let original_headers = HashMap::from_bytes(
+ original_message.user_headers.as_ref().unwrap().clone(),
+ )
+ .unwrap();
+ assert_eq!(
+ loaded_headers,
+ original_headers,
+ "Headers mismatch at offset {}",
+ msg.header().offset(),
+ );
+ }
+ i += 1;
+ }
+ }
+ }
+
+ // Add sequential read test for all batch sizes
+ println!(
+ "Verifying sequential reads, expecting {} messages",
+ total_sent_messages
);
- // Test 6: Validate message content and ordering
- for (i, msg) in spanning_messages.iter().enumerate() {
- let expected_offset = span_offset + i as u64;
- assert!(
- msg.offset >= expected_offset,
- "Message offset {} at position {} should be >= expected offset {}",
- msg.offset,
- i,
- expected_offset
- );
+ let chunk_size = 500;
+ let mut verified_count = 0;
+
+ for chunk_start in (0..total_sent_messages).step_by(chunk_size as usize) {
+ let read_size = std::cmp::min(chunk_size, total_sent_messages - chunk_start);
+
+ let chunk = partition
+ .get_messages_by_offset(chunk_start as u64, read_size)
+ .await
+ .unwrap();
- // Verify message contents match original
- let original_idx = msg.offset as usize;
- let original_message = &all_messages[original_idx];
- assert_eq!(
- msg.id, original_message.id,
- "Message ID mismatch at offset {}: expected {}, got {}",
- msg.offset, original_message.id, msg.id
- );
assert_eq!(
- msg.payload, original_message.payload,
- "Payload mismatch at offset {}: expected {:?}, got {:?}",
- msg.offset, original_message.payload, msg.payload
+ chunk.count(),
+ read_size,
+ "Failed to read chunk at offset {} with size {}",
+ chunk_start,
+ read_size
);
- assert_eq!(
- msg.headers
- .as_ref()
- .map(|bytes| HashMap::from_bytes(bytes.clone()).unwrap()),
- original_message.headers,
- "Headers mismatch at offset {}: expected {:?}, got {:?}",
- msg.offset,
- original_message.headers,
- msg.headers
- .as_ref()
- .map(|bytes| HashMap::from_bytes(bytes.clone()).unwrap())
+
+ verified_count += chunk.count();
+
+ println!(
+ "Read chunk at offset {} with size {}, verified count: {}",
+ chunk_start, read_size, verified_count
);
}
+
+ assert_eq!(
+ verified_count, total_sent_messages,
+ "Sequential chunk reads didn't cover all messages"
+ );
}
diff --git a/integration/tests/streaming/get_by_timestamp.rs b/integration/tests/streaming/get_by_timestamp.rs
index e2d0661c..e7c8b1dd 100644
--- a/integration/tests/streaming/get_by_timestamp.rs
+++ b/integration/tests/streaming/get_by_timestamp.rs
@@ -18,21 +18,17 @@
use crate::streaming::common::test_setup::TestSetup;
use bytes::BytesMut;
-use iggy::bytes_serializable::BytesSerializable;
-use iggy::messages::send_messages::Message;
-use iggy::models::header::{HeaderKey, HeaderValue};
-use iggy::utils::byte_size::IggyByteSize;
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::sizeable::Sizeable;
-use iggy::utils::timestamp::IggyTimestamp;
-use server::configs::resource_quota::MemoryResourceQuota;
-use server::configs::system::{CacheConfig, PartitionConfig, SegmentConfig, SystemConfig};
-use server::streaming::batching::appendable_batch_info::AppendableBatchInfo;
+use iggy::confirmation::Confirmation;
+use iggy::prelude::*;
+use server::configs::cache_indexes::CacheIndexesConfig;
+use server::configs::system::{PartitionConfig, SegmentConfig, SystemConfig};
use server::streaming::partitions::partition::Partition;
+use server::streaming::segments::IggyMessagesBatchMut;
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::atomic::{AtomicU32, AtomicU64};
use std::sync::Arc;
+use std::thread::sleep;
use test_case::test_matrix;
/*
@@ -40,53 +36,66 @@ use test_case::test_matrix;
*/
fn msg_size(size: u64) -> IggyByteSize {
- IggyByteSize::from_str(&format!("{}b", size)).unwrap()
+ IggyByteSize::from_str(&format!("{}B", size)).unwrap()
}
fn segment_size(size: u64) -> IggyByteSize {
- IggyByteSize::from_str(&format!("{}b", size)).unwrap()
+ IggyByteSize::from_str(&format!("{}B", size)).unwrap()
}
fn msgs_req_to_save(count: u32) -> u32 {
count
}
-fn msg_cache_size(size: u64) -> Option<IggyByteSize> {
- if size == 0 {
- return None;
- }
- Some(IggyByteSize::from_str(&format!("{}b", size)).unwrap())
+fn index_cache_all() -> CacheIndexesConfig {
+ CacheIndexesConfig::All
+}
+
+fn index_cache_none() -> CacheIndexesConfig {
+ CacheIndexesConfig::None
+}
+
+fn index_cache_open_segment() -> CacheIndexesConfig {
+ CacheIndexesConfig::OpenSegment
+}
+
+fn small_batches() -> Vec<u32> {
+ vec![3, 4, 5, 6, 7]
}
-fn index_cache_enabled() -> bool {
- true
+fn medium_batches() -> Vec<u32> {
+ vec![10, 20, 30, 40]
}
-fn index_cache_disabled() -> bool {
- false
+fn large_batches() -> Vec<u32> {
+ vec![100, 200, 300, 400]
+}
+
+fn very_large_batches() -> Vec<u32> {
+ vec![500, 1000, 1500, 1000]
}
#[test_matrix(
[msg_size(50), msg_size(1000), msg_size(20000)],
- [msgs_req_to_save(3), msgs_req_to_save(10), msgs_req_to_save(1000)],
- [segment_size(500), segment_size(2000), segment_size(100000)],
- [msg_cache_size(0), msg_cache_size(5000), msg_cache_size(50000), msg_cache_size(2000000)],
- [index_cache_disabled(), index_cache_enabled()])]
+ [small_batches(), medium_batches(), large_batches(), very_large_batches()],
+ [msgs_req_to_save(1), msgs_req_to_save(24), msgs_req_to_save(1000), msgs_req_to_save(10000)],
+ [segment_size(10), segment_size(200), segment_size(10000000)],
+ [index_cache_none(), index_cache_all(), index_cache_open_segment()])]
#[tokio::test]
async fn test_get_messages_by_timestamp(
message_size: IggyByteSize,
+ batch_sizes: Vec<u32>,
messages_required_to_save: u32,
segment_size: IggyByteSize,
- msg_cache_size: Option<IggyByteSize>,
- index_cache_enabled: bool,
+ cache_indexes: CacheIndexesConfig,
) {
println!(
- "Running test with msg_cache_enabled: {}, messages_required_to_save: {}, segment_size: {}, message_size: {}, cache_indexes: {}",
- msg_cache_size.is_some(),
+ "Running test with message_size: {}, batches: {:?}, messages_required_to_save: {}, segment_size: {}, cache_indexes: {}",
+ message_size,
+ batch_sizes,
messages_required_to_save,
segment_size,
- message_size,
- index_cache_enabled
+ cache_indexes
);
let setup = TestSetup::init().await;
@@ -94,31 +103,23 @@ async fn test_get_messages_by_timestamp(
let topic_id = 1;
let partition_id = 1;
- // Define batch sizes for 5 appends
- let batch_sizes = [3, 4, 5, 6, 7];
- let total_messages: u32 = batch_sizes.iter().sum();
+ let total_messages_count = batch_sizes.iter().sum();
- let msg_cache_enabled = msg_cache_size.is_some();
- let msg_cache_size =
- MemoryResourceQuota::Bytes(msg_cache_size.unwrap_or(IggyByteSize::from_str("0").unwrap()));
let config = Arc::new(SystemConfig {
path: setup.config.path.to_string(),
- cache: CacheConfig {
- enabled: msg_cache_enabled,
- size: msg_cache_size,
- },
partition: PartitionConfig {
messages_required_to_save,
enforce_fsync: true,
..Default::default()
},
segment: SegmentConfig {
- cache_indexes: index_cache_enabled,
+ cache_indexes,
size: segment_size,
..Default::default()
},
..Default::default()
});
+
let mut partition = Partition::create(
stream_id,
topic_id,
@@ -139,8 +140,10 @@ async fn test_get_messages_by_timestamp(
setup.create_partitions_directory(stream_id, topic_id).await;
partition.persist().await.unwrap();
- let mut all_messages = Vec::with_capacity(total_messages as usize);
- for i in 1..=total_messages {
+ let mut all_messages = Vec::with_capacity(total_messages_count as usize);
+
+ // Generate all messages as defined in the test matrix
+ for i in 1..=total_messages_count {
let id = i as u128;
let beginning_of_payload = format!("message {}", i);
let mut payload = BytesMut::new();
@@ -161,149 +164,200 @@ async fn test_get_messages_by_timestamp(
HeaderKey::new("key-3").unwrap(),
HeaderValue::from_uint64(123456).unwrap(),
);
- let message = Message {
- id,
- length: payload.len() as u32,
- payload: payload.clone(),
- headers: Some(headers),
- };
+
+ let message = IggyMessage::builder()
+ .id(id)
+ .payload(payload)
+ .headers(headers)
+ .build()
+ .expect("Failed to create message with valid payload and headers");
+
all_messages.push(message);
}
+ // Timestamp tracking for messages
let initial_timestamp = IggyTimestamp::now();
let mut batch_timestamps = Vec::with_capacity(batch_sizes.len());
let mut current_pos = 0;
- // Append all batches with timestamps
- for batch_size in batch_sizes {
- let batch = all_messages[current_pos..current_pos + batch_size as usize].to_vec();
- let batch_info = AppendableBatchInfo::new(
- batch
- .iter()
- .map(|msg| msg.get_size_bytes())
- .sum::<IggyByteSize>(),
- partition.partition_id,
+ // Append all batches as defined in the test matrix with separate timestamps
+ for (batch_idx, &batch_len) in batch_sizes.iter().enumerate() {
+ // Add a small delay between batches to ensure distinct timestamps
+ sleep(std::time::Duration::from_millis(2));
+
+ // If we've generated too many messages, skip the rest
+ if current_pos + batch_len as usize > all_messages.len() {
+ break;
+ }
+
+ println!(
+ "Appending batch {}/{} with {} messages",
+ batch_idx + 1,
+ batch_sizes.len(),
+ batch_len
);
+
+ let batch_end_pos = current_pos + batch_len as usize;
+ let messages_slice_to_append = &all_messages[current_pos..batch_end_pos];
+
+ let messages_size = messages_slice_to_append
+ .iter()
+ .map(|m| m.get_size_bytes().as_bytes_u64() as u32)
+ .sum();
+
+ let batch = IggyMessagesBatchMut::from_messages(messages_slice_to_append, messages_size);
+ assert_eq!(batch.count(), batch_len);
partition
- .append_messages(batch_info, batch.clone(), None)
+ .append_messages(batch, Some(Confirmation::Wait))
.await
.unwrap();
+ // Capture the timestamp of this batch
batch_timestamps.push(IggyTimestamp::now());
- current_pos += batch_size as usize;
+ current_pos += batch_len as usize;
+
+ // Add a small delay between batches to ensure distinct timestamps
+ sleep(std::time::Duration::from_millis(2));
}
let final_timestamp = IggyTimestamp::now();
+ // Use the exact total messages count from the test matrix
+ let total_sent_messages = total_messages_count;
+
// Test 1: All messages from initial timestamp
let all_loaded_messages = partition
- .get_messages_by_timestamp(initial_timestamp, total_messages)
+ .get_messages_by_timestamp(initial_timestamp, total_sent_messages)
.await
.unwrap();
assert_eq!(
- all_loaded_messages.len(),
- total_messages as usize,
+ all_loaded_messages.count(),
+ total_sent_messages,
"Expected {} messages from initial timestamp, but got {}",
- total_messages,
- all_loaded_messages.len()
+ total_sent_messages,
+ all_loaded_messages.count()
);
// Test 2: Get messages from middle timestamp (after 3rd batch)
- let middle_timestamp = batch_timestamps[2];
- let remaining_messages = total_messages - (batch_sizes[0] + batch_sizes[1] + batch_sizes[2]);
- let middle_messages = partition
- .get_messages_by_timestamp(middle_timestamp, remaining_messages)
- .await
- .unwrap();
- assert_eq!(
- middle_messages.len(),
- remaining_messages as usize,
- "Expected {} messages from middle timestamp, but got {}",
- remaining_messages,
- middle_messages.len()
- );
+ if batch_timestamps.len() >= 3 {
+ // Use a timestamp that's just before the 3rd batch's timestamp to ensure we get messages
+ // from that batch onwards
+ let middle_timestamp = IggyTimestamp::from(batch_timestamps[2].as_micros() + 1000);
+
+ // Calculate how many messages should be in batches after the 3rd
+ let prior_batches_sum: u32 = batch_sizes[..3].iter().sum();
+ let remaining_messages = total_sent_messages - prior_batches_sum;
+
+ let middle_messages = partition
+ .get_messages_by_timestamp(middle_timestamp, remaining_messages)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ middle_messages.count(),
+ remaining_messages,
+ "Expected {} messages from middle timestamp, but got {}",
+ remaining_messages,
+ middle_messages.count()
+ );
+ }
- // Test 3: No messages from final timestamp
+ // Test 3: No messages after final timestamp
let no_messages = partition
.get_messages_by_timestamp(final_timestamp, 1)
.await
.unwrap();
assert_eq!(
- no_messages.len(),
+ no_messages.count(),
0,
- "Expected no messages from final timestamp, but got {}",
- no_messages.len()
+ "Expected no messages after final timestamp, but got {}",
+ no_messages.count()
);
// Test 4: Small subset from initial timestamp
- let subset_size = 3;
+ let subset_size = std::cmp::min(3, total_sent_messages);
let subset_messages = partition
.get_messages_by_timestamp(initial_timestamp, subset_size)
.await
.unwrap();
assert_eq!(
- subset_messages.len(),
- subset_size as usize,
+ subset_messages.count(),
+ subset_size,
"Expected {} messages in subset from initial timestamp, but got {}",
subset_size,
- subset_messages.len()
+ subset_messages.count()
);
- for i in 0..subset_messages.len() {
- let loaded_message = &subset_messages[i];
- let original_message = &all_messages[i];
- assert_eq!(
- loaded_message.id, original_message.id,
- "Message ID mismatch at position {}: expected {}, got {}",
- i, original_message.id, loaded_message.id
- );
- assert_eq!(
- loaded_message.payload, original_message.payload,
- "Payload mismatch at position {}: expected {:?}, got {:?}",
- i, original_message.payload, loaded_message.payload
- );
+
+ // Test 5: Messages spanning multiple batches by timestamp
+ if batch_timestamps.len() >= 4 {
+ // Use a timestamp that's just before the 2nd batch's timestamp
+ let span_timestamp = IggyTimestamp::from(batch_timestamps[1].as_micros() + 1000);
+ let span_size = 8; // Should span across multiple batches
+
+ let spanning_messages = partition
+ .get_messages_by_timestamp(span_timestamp, span_size)
+ .await
+ .unwrap();
+
assert_eq!(
- loaded_message
- .headers
- .as_ref()
- .map(|bytes| HashMap::from_bytes(bytes.clone()).unwrap()),
- original_message.headers,
- "Headers mismatch at position {}: expected {:?}, got {:?}",
- i,
- original_message.headers,
- loaded_message
- .headers
- .as_ref()
- .map(|bytes| HashMap::from_bytes(bytes.clone()).unwrap())
- );
- assert!(
- loaded_message.timestamp >= initial_timestamp.as_micros(),
- "Message timestamp {} at position {} is less than initial timestamp {}",
- loaded_message.timestamp,
- i,
- initial_timestamp
+ spanning_messages.count(),
+ span_size,
+ "Expected {} messages spanning multiple batches, but got {}",
+ span_size,
+ spanning_messages.count()
);
- }
- // Test 5: Messages spanning multiple batches (from middle of 2nd batch timestamp)
- let span_timestamp = batch_timestamps[1];
- let span_size = 8; // Should span across 2nd, 3rd, and into 4th batch
- let spanning_messages = partition
- .get_messages_by_timestamp(span_timestamp, span_size)
- .await
- .unwrap();
- assert_eq!(
- spanning_messages.len(),
- span_size as usize,
- "Expected {} messages spanning multiple batches, but got {}",
- span_size,
- spanning_messages.len()
- );
- for msg in spanning_messages.iter() {
- assert!(
- msg.timestamp >= span_timestamp.as_micros(),
- "Message timestamp {} should be >= span timestamp {}",
- msg.timestamp,
- span_timestamp
- );
+ // Verify that all messages have timestamps >= our reference timestamp
+ let span_timestamp_micros = span_timestamp.as_micros();
+
+ // Test 6: Validate message content and ordering
+ for batch in spanning_messages.iter() {
+ for msg in batch.iter() {
+ let msg_timestamp = msg.header().timestamp();
+ assert!(
+ msg_timestamp >= span_timestamp_micros,
+ "Message timestamp {} should be >= span timestamp {}",
+ msg_timestamp,
+ span_timestamp_micros
+ );
+
+ // Verify message content
+ let loaded_id = msg.header().id();
+ let original_offset = msg.header().offset() as usize;
+
+ if original_offset < all_messages.len() {
+ let original_message = &all_messages[original_offset];
+ let original_id = original_message.header.id;
+
+ assert_eq!(
+ loaded_id,
+ original_id,
+ "Message ID mismatch at offset {}",
+ msg.header().offset(),
+ );
+
+ let loaded_payload = msg.payload();
+ let original_payload = &original_message.payload;
+ assert_eq!(
+ loaded_payload,
+ original_payload,
+ "Payload mismatch at offset {}",
+ msg.header().offset(),
+ );
+
+ let loaded_headers = msg.user_headers_map().unwrap().unwrap();
+ let original_headers = HashMap::from_bytes(
+ original_message.user_headers.as_ref().unwrap().clone(),
+ )
+ .unwrap();
+ assert_eq!(
+ loaded_headers,
+ original_headers,
+ "Headers mismatch at offset {}",
+ msg.header().offset(),
+ );
+ }
+ }
+ }
}
}
diff --git a/integration/tests/streaming/messages.rs b/integration/tests/streaming/messages.rs
index 3edc83d7..a45b38dc 100644
--- a/integration/tests/streaming/messages.rs
+++ b/integration/tests/streaming/messages.rs
@@ -18,17 +18,11 @@
use crate::streaming::common::test_setup::TestSetup;
use bytes::Bytes;
-use iggy::bytes_serializable::BytesSerializable;
-use iggy::messages::send_messages::Message;
-use iggy::models::header::{HeaderKey, HeaderValue};
-use iggy::utils::byte_size::IggyByteSize;
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::sizeable::Sizeable;
-use iggy::utils::timestamp::IggyTimestamp;
+use iggy::prelude::*;
use server::configs::system::{PartitionConfig, SystemConfig};
use server::state::system::PartitionState;
-use server::streaming::batching::appendable_batch_info::AppendableBatchInfo;
use server::streaming::partitions::partition::Partition;
+use server::streaming::segments::IggyMessagesBatchMut;
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::atomic::{AtomicU32, AtomicU64};
@@ -86,12 +80,13 @@ async fn should_persist_messages_and_then_load_them_by_timestamp() {
HeaderKey::new("key-3").unwrap(),
HeaderValue::from_uint64(123456).unwrap(),
);
- let message = Message {
- id,
- length: payload.len() as u32,
- payload: payload.clone(),
- headers: Some(headers),
- };
+ let message = IggyMessage::builder()
+ .id(id)
+ .payload(payload)
+ .headers(headers)
+ .build()
+ .expect("Failed to create message with valid payload and headers");
+
messages.push(message);
}
@@ -111,41 +106,42 @@ async fn should_persist_messages_and_then_load_them_by_timestamp() {
HeaderKey::new("key-3").unwrap(),
HeaderValue::from_uint64(123456).unwrap(),
);
- let message = Message {
- id,
- length: payload.len() as u32,
- payload: payload.clone(),
- headers: Some(headers),
- };
- appended_messages.push(message.clone());
- messages_two.push(message);
+
+ let message = IggyMessage::builder()
+ .id(id)
+ .payload(payload.clone())
+ .headers(headers.clone())
+ .build()
+ .expect("Failed to create message with valid payload and headers");
+
+ let message_clone = IggyMessage::builder()
+ .id(id)
+ .payload(payload)
+ .headers(headers)
+ .build()
+ .expect("Failed to create message with valid payload and headers");
+
+ appended_messages.push(message);
+ messages_two.push(message_clone);
}
setup.create_partitions_directory(stream_id, topic_id).await;
partition.persist().await.unwrap();
- let appendable_batch_info = AppendableBatchInfo::new(
- messages
- .iter()
- .map(|msg| msg.get_size_bytes())
- .sum::<IggyByteSize>(),
- partition.partition_id,
- );
- let appendable_batch_info_two = AppendableBatchInfo::new(
- messages_two
- .iter()
- .map(|msg| msg.get_size_bytes())
- .sum::<IggyByteSize>(),
- partition.partition_id,
- );
- partition
- .append_messages(appendable_batch_info, messages, None)
- .await
- .unwrap();
+ let messages_size = messages
+ .iter()
+ .map(|msg| msg.get_size_bytes().as_bytes_u32())
+ .sum::<u32>();
+ let batch = IggyMessagesBatchMut::from_messages(&messages, messages_size);
+
+ let messages_size_two = messages_two
+ .iter()
+ .map(|msg| msg.get_size_bytes().as_bytes_u32())
+ .sum::<u32>();
+ let batch_two = IggyMessagesBatchMut::from_messages(&messages_two, messages_size_two);
+
+ partition.append_messages(batch, None).await.unwrap();
let test_timestamp = IggyTimestamp::now();
- partition
- .append_messages(appendable_batch_info_two, messages_two, None)
- .await
- .unwrap();
+ partition.append_messages(batch_two, None).await.unwrap();
let loaded_messages = partition
.get_messages_by_timestamp(test_timestamp, messages_count)
@@ -153,47 +149,36 @@ async fn should_persist_messages_and_then_load_them_by_timestamp() {
.unwrap();
assert_eq!(
- loaded_messages.len(),
- messages_count as usize,
- "Expected loaded messages count to be {}, but got {}",
+ loaded_messages.count(),
messages_count,
- loaded_messages.len()
+ "Unexpected loaded messages count"
);
- for i in 0..loaded_messages.len() {
- let loaded_message = &loaded_messages[i];
+ (0..loaded_messages.count() as usize).for_each(|i| {
+ let loaded_message = &loaded_messages.get(i).unwrap();
let appended_message = &appended_messages[i];
assert_eq!(
- loaded_message.id, appended_message.id,
- "Message ID mismatch at position {}: expected {}, got {}",
- i, appended_message.id, loaded_message.id
+ loaded_message.header().id(),
+ appended_message.header.id,
+ "Message ID mismatch at position {i}"
);
assert_eq!(
- loaded_message.payload, appended_message.payload,
- "Payload mismatch at position {}: expected {:?}, got {:?}",
- i, appended_message.payload, loaded_message.payload
+ loaded_message.payload(),
+ appended_message.payload,
+ "Payload mismatch at position {i}",
);
assert!(
- loaded_message.timestamp >= test_timestamp.as_micros(),
+ loaded_message.header().timestamp() >= test_timestamp.as_micros(),
"Message timestamp {} at position {} is less than test timestamp {}",
- loaded_message.timestamp,
+ loaded_message.header().timestamp(),
i,
test_timestamp
);
assert_eq!(
- loaded_message
- .headers
- .as_ref()
- .map(|bytes| HashMap::from_bytes(bytes.clone()).unwrap()),
- appended_message.headers,
- "Headers mismatch at position {}: expected {:?}, got {:?}",
- i,
- appended_message.headers,
- loaded_message
- .headers
- .as_ref()
- .map(|bytes| HashMap::from_bytes(bytes.clone()).unwrap())
+ loaded_message.user_headers_map().unwrap().unwrap(),
+ appended_message.user_headers_map().unwrap().unwrap(),
+ "Headers mismatch at position {i}",
);
- }
+ });
}
#[tokio::test]
@@ -247,35 +232,23 @@ async fn should_persist_messages_and_then_load_them_from_disk() {
HeaderKey::new("key-3").unwrap(),
HeaderValue::from_uint64(123456).unwrap(),
);
- let appended_message = Message {
- id,
- length: payload.len() as u32,
- payload: payload.clone(),
- headers: Some(headers.clone()),
- };
- let message = Message {
- id,
- length: payload.len() as u32,
- payload: payload.clone(),
- headers: Some(headers),
- };
+
+ let appended_message =
+ IggyMessage::with_id_and_headers(id, payload.clone(), headers.clone());
+ let message = IggyMessage::with_id_and_headers(id, payload, headers);
+
appended_messages.push(appended_message);
messages.push(message);
}
setup.create_partitions_directory(stream_id, topic_id).await;
partition.persist().await.unwrap();
- let appendable_batch_info = AppendableBatchInfo::new(
- messages
- .iter()
- .map(|msg| msg.get_size_bytes())
- .sum::<IggyByteSize>(),
- partition.partition_id,
- );
- partition
- .append_messages(appendable_batch_info, messages, None)
- .await
- .unwrap();
+ let messages_size = messages
+ .iter()
+ .map(|msg| msg.get_size_bytes().as_bytes_u32())
+ .sum::<u32>();
+ let batch = IggyMessagesBatchMut::from_messages(&messages, messages_size);
+ partition.append_messages(batch, None).await.unwrap();
assert_eq!(
partition.unsaved_messages_count, 0,
"Expected unsaved messages count to be 0, but got {}",
@@ -309,39 +282,27 @@ async fn should_persist_messages_and_then_load_them_from_disk() {
.await
.unwrap();
assert_eq!(
- loaded_messages.len(),
- messages_count as usize,
- "Expected loaded messages count to be {}, but got {}",
+ loaded_messages.count(),
messages_count,
- loaded_messages.len()
+ "Unexpected loaded messages count "
);
- for i in 1..=messages_count {
- let index = i as usize - 1;
- let loaded_message = &loaded_messages[index];
- let appended_message = &appended_messages[index];
+ (0..messages_count as usize).for_each(|i| {
+ let loaded_message = &loaded_messages.get(i).unwrap();
+ let appended_message = &appended_messages[i];
assert_eq!(
- loaded_message.id, appended_message.id,
- "Message ID mismatch at position {}: expected {}, got {}",
- i, appended_message.id, loaded_message.id
+ loaded_message.header().id(),
+ appended_message.header.id,
+ "Message ID mismatch at position {i}",
);
assert_eq!(
- loaded_message.payload, appended_message.payload,
- "Payload mismatch at position {}: expected {:?}, got {:?}",
- i, appended_message.payload, loaded_message.payload
+ loaded_message.payload(),
+ appended_message.payload,
+ "Payload mismatch at position {i}",
);
assert_eq!(
- loaded_message
- .headers
- .as_ref()
- .map(|bytes| HashMap::from_bytes(bytes.clone()).unwrap()),
- appended_message.headers,
- "Headers mismatch at position {}: expected {:?}, got {:?}",
- i,
- appended_message.headers,
- loaded_message
- .headers
- .as_ref()
- .map(|bytes| HashMap::from_bytes(bytes.clone()).unwrap())
+ loaded_message.user_headers_map().unwrap().unwrap(),
+ appended_message.user_headers_map().unwrap().unwrap(),
+ "Headers mismatch at position {i}",
);
- }
+ });
}
diff --git a/integration/tests/streaming/mod.rs b/integration/tests/streaming/mod.rs
index 72d5ebe7..b5df4c0a 100644
--- a/integration/tests/streaming/mod.rs
+++ b/integration/tests/streaming/mod.rs
@@ -17,7 +17,7 @@
*/
use bytes::Bytes;
-use iggy::messages::send_messages::Message;
+use iggy::prelude::IggyMessage;
mod common;
mod consumer_offset;
@@ -32,7 +32,7 @@ mod system;
mod topic;
mod topic_messages;
-fn create_messages() -> Vec<Message> {
+fn create_messages() -> Vec<IggyMessage> {
vec![
create_message(1, "message 1"),
create_message(2, "message 2"),
@@ -43,12 +43,11 @@ fn create_messages() -> Vec<Message> {
]
}
-fn create_message(id: u128, payload: &str) -> Message {
+fn create_message(id: u128, payload: &str) -> IggyMessage {
let payload = Bytes::from(payload.to_string());
- Message {
- id,
- length: payload.len() as u32,
- payload,
- headers: None,
- }
+ IggyMessage::builder()
+ .id(id)
+ .payload(payload)
+ .build()
+ .expect("Failed to create message with valid payload and headers")
}
diff --git a/integration/tests/streaming/partition.rs b/integration/tests/streaming/partition.rs
index 7fd305b9..d772414b 100644
--- a/integration/tests/streaming/partition.rs
+++ b/integration/tests/streaming/partition.rs
@@ -18,12 +18,10 @@
use crate::streaming::common::test_setup::TestSetup;
use crate::streaming::create_messages;
-use iggy::utils::byte_size::IggyByteSize;
use iggy::utils::expiry::IggyExpiry;
use iggy::utils::sizeable::Sizeable;
use iggy::utils::timestamp::IggyTimestamp;
use server::state::system::PartitionState;
-use server::streaming::batching::appendable_batch_info::AppendableBatchInfo;
use server::streaming::partitions::partition::Partition;
use server::streaming::segments::*;
use std::sync::atomic::{AtomicU32, AtomicU64};
@@ -129,11 +127,6 @@ async fn should_load_existing_partition_from_disk() {
loaded_partition.should_increment_offset,
partition.should_increment_offset
);
- assert_eq!(loaded_partition.cache.is_some(), partition.cache.is_some());
- assert_eq!(
- loaded_partition.cache.unwrap().is_empty(),
- partition.cache.unwrap().is_empty()
- );
}
}
@@ -199,20 +192,15 @@ async fn should_purge_existing_partition_on_disk() {
partition.persist().await.unwrap();
assert_persisted_partition(&partition.partition_path, with_segment).await;
let messages = create_messages();
- let messages_count = messages.len();
- let appendable_batch_info = AppendableBatchInfo::new(
- messages
- .iter()
- .map(|msg| msg.get_size_bytes())
- .sum::<IggyByteSize>(),
- partition.partition_id,
- );
- partition
- .append_messages(appendable_batch_info, messages, None)
- .await
- .unwrap();
+ let messages_count = messages.len() as u32;
+ let messages_size: u32 = messages
+ .iter()
+ .map(|msg| msg.get_size_bytes().as_bytes_u32())
+ .sum();
+ let batch = IggyMessagesBatchMut::from_messages(&messages, messages_size);
+ partition.append_messages(batch, None).await.unwrap();
let loaded_messages = partition.get_messages_by_offset(0, 100).await.unwrap();
- assert_eq!(loaded_messages.len(), messages_count);
+ assert_eq!(loaded_messages.count(), messages_count);
partition.purge().await.unwrap();
assert_eq!(partition.current_offset, 0);
assert_eq!(partition.unsaved_messages_count, 0);
@@ -228,9 +216,9 @@ async fn assert_persisted_partition(partition_path: &str, with_segment: bool) {
if with_segment {
let start_offset = 0u64;
let segment_path = format!("{}/{:0>20}", partition_path, start_offset);
- let log_path = format!("{}.{}", segment_path, LOG_EXTENSION);
+ let messages_file_path = format!("{}.{}", segment_path, LOG_EXTENSION);
let index_path = format!("{}.{}", segment_path, INDEX_EXTENSION);
- assert!(fs::metadata(&log_path).await.is_ok());
+ assert!(fs::metadata(&messages_file_path).await.is_ok());
assert!(fs::metadata(&index_path).await.is_ok());
}
}
diff --git a/integration/tests/streaming/segment.rs b/integration/tests/streaming/segment.rs
index b62196d1..4dce6154 100644
--- a/integration/tests/streaming/segment.rs
+++ b/integration/tests/streaming/segment.rs
@@ -17,27 +17,23 @@
*/
use crate::streaming::common::test_setup::TestSetup;
+use crate::streaming::create_message;
use bytes::Bytes;
-use iggy::bytes_serializable::BytesSerializable;
use iggy::compression::compression_algorithm::CompressionAlgorithm;
use iggy::confirmation::Confirmation;
use iggy::error::IggyError;
use iggy::identifier::Identifier;
use iggy::locking::IggySharedMutFn;
-use iggy::models::messages::{MessageState, PolledMessage};
-use iggy::utils::byte_size::IggyByteSize;
-use iggy::utils::expiry::IggyExpiry;
+use iggy::prelude::*;
use iggy::utils::topic_size::MaxTopicSize;
-use iggy::utils::{checksum, timestamp::IggyTimestamp};
use server::configs::server::{DataMaintenanceConfig, PersonalAccessTokenConfig};
-use server::configs::system::{SegmentConfig, SystemConfig};
-use server::streaming::local_sizeable::LocalSizeable;
-use server::streaming::models::messages::RetainedMessage;
+use server::configs::system::{PartitionConfig, SegmentConfig, SystemConfig};
use server::streaming::segments::*;
use server::streaming::session::Session;
use server::streaming::systems::system::System;
use std::fs::DirEntry;
use std::net::{Ipv4Addr, SocketAddr};
+use std::str::FromStr;
use std::sync::atomic::AtomicU64;
use std::sync::Arc;
use std::time::Duration;
@@ -132,14 +128,19 @@ async fn should_load_existing_segment_from_disk() {
loaded_segment.load_from_disk().await.unwrap();
let loaded_messages = loaded_segment.get_messages_by_offset(0, 10).await.unwrap();
- assert_eq!(loaded_segment.partition_id, segment.partition_id);
- assert_eq!(loaded_segment.start_offset, segment.start_offset);
- assert_eq!(loaded_segment.current_offset, segment.current_offset);
- assert_eq!(loaded_segment.end_offset, segment.end_offset);
- assert_eq!(loaded_segment.size_bytes, segment.size_bytes);
- assert_eq!(loaded_segment.is_closed, segment.is_closed);
- assert_eq!(loaded_segment.log_path, segment.log_path);
- assert_eq!(loaded_segment.index_path, segment.index_path);
+ assert_eq!(loaded_segment.partition_id(), segment.partition_id());
+ assert_eq!(loaded_segment.start_offset(), segment.start_offset());
+ assert_eq!(loaded_segment.end_offset(), segment.end_offset());
+ assert_eq!(
+ loaded_segment.get_messages_size(),
+ segment.get_messages_size()
+ );
+ assert_eq!(loaded_segment.is_closed(), segment.is_closed());
+ assert_eq!(
+ loaded_segment.messages_file_path(),
+ segment.messages_file_path()
+ );
+ assert_eq!(loaded_segment.index_file_path(), segment.index_file_path());
assert!(loaded_messages.is_empty());
}
}
@@ -179,27 +180,15 @@ async fn should_persist_and_load_segment_with_messages() {
.await;
let messages_count = 10;
let mut messages = Vec::new();
- let mut batch_size = IggyByteSize::default();
+ let mut messages_size = 0;
for i in 0..messages_count {
- let message = create_message(i, "test", IggyTimestamp::now());
-
- let retained_message = Arc::new(RetainedMessage {
- id: message.id,
- offset: message.offset,
- timestamp: message.timestamp,
- checksum: message.checksum,
- message_state: message.state,
- headers: message.headers.map(|headers| headers.to_bytes()),
- payload: message.payload.clone(),
- });
- batch_size += retained_message.get_size_bytes();
- messages.push(retained_message);
+ let message = IggyMessage::with_id(i as u128, Bytes::from("test"));
+ messages_size += message.get_size_bytes().as_bytes_u32();
+ messages.push(message);
}
+ let batch = IggyMessagesBatchMut::from_messages(&messages, messages_size);
- segment
- .append_batch(batch_size, messages_count as u32, &messages)
- .await
- .unwrap();
+ segment.append_batch(0, batch, None).await.unwrap();
segment.persist_messages(None).await.unwrap();
let mut loaded_segment = Segment::create(
stream_id,
@@ -217,10 +206,10 @@ async fn should_persist_and_load_segment_with_messages() {
);
loaded_segment.load_from_disk().await.unwrap();
let messages = loaded_segment
- .get_messages_by_offset(0, messages_count as u32)
+ .get_messages_by_offset(0, messages_count)
.await
.unwrap();
- assert_eq!(messages.len(), messages_count as usize);
+ assert_eq!(messages.count(), messages_count);
}
#[tokio::test]
@@ -265,27 +254,14 @@ async fn should_persist_and_load_segment_with_messages_with_nowait_confirmation(
.await;
let messages_count = 10;
let mut messages = Vec::new();
- let mut batch_size = IggyByteSize::default();
+ let mut messages_size = 0;
for i in 0..messages_count {
- let message = create_message(i, "test", IggyTimestamp::now());
-
- let retained_message = Arc::new(RetainedMessage {
- id: message.id,
- offset: message.offset,
- timestamp: message.timestamp,
- checksum: message.checksum,
- message_state: message.state,
- headers: message.headers.map(|headers| headers.to_bytes()),
- payload: message.payload.clone(),
- });
- batch_size += retained_message.get_size_bytes();
- messages.push(retained_message);
+ let message = IggyMessage::with_id(i as u128, Bytes::from("test"));
+ messages_size += message.get_size_bytes().as_bytes_u32();
+ messages.push(message);
}
-
- segment
- .append_batch(batch_size, messages_count as u32, &messages)
- .await
- .unwrap();
+ let batch = IggyMessagesBatchMut::from_messages(&messages, messages_size);
+ segment.append_batch(0, batch, None).await.unwrap();
segment
.persist_messages(Some(Confirmation::NoWait))
.await
@@ -307,21 +283,32 @@ async fn should_persist_and_load_segment_with_messages_with_nowait_confirmation(
);
loaded_segment.load_from_disk().await.unwrap();
let messages = loaded_segment
- .get_messages_by_offset(0, messages_count as u32)
+ .get_messages_by_offset(0, messages_count)
.await
.unwrap();
- assert_eq!(messages.len(), messages_count as usize);
+ assert_eq!(messages.count(), messages_count);
}
#[tokio::test]
async fn given_all_expired_messages_segment_should_be_expired() {
- let setup = TestSetup::init().await;
+ let config = SystemConfig {
+ partition: PartitionConfig {
+ enforce_fsync: true,
+ ..Default::default()
+ },
+ segment: SegmentConfig {
+ size: IggyByteSize::from_str("10B").unwrap(), // small size to force expiration
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let setup = TestSetup::init_with_config(config).await;
let stream_id = 1;
let topic_id = 2;
let partition_id = 3;
let start_offset = 0;
- let message_expiry_ms = 1000;
- let message_expiry = 1000u64.into();
+ let message_expiry_us = 100000;
+ let message_expiry = message_expiry_us.into();
let mut segment = Segment::create(
stream_id,
topic_id,
@@ -349,46 +336,43 @@ async fn given_all_expired_messages_segment_should_be_expired() {
)
.await;
let messages_count = 10;
- let now = IggyTimestamp::now();
- let mut expired_timestamp = (now.as_micros() - 2 * message_expiry_ms).into();
- let mut batch_size = IggyByteSize::default();
let mut messages = Vec::new();
+ let mut messages_size = 0;
for i in 0..messages_count {
- let message = create_message(i, "test", expired_timestamp);
- expired_timestamp = (expired_timestamp.as_micros() + 1).into();
-
- let retained_message = Arc::new(RetainedMessage {
- id: message.id,
- offset: message.offset,
- timestamp: message.timestamp,
- checksum: message.checksum,
- message_state: message.state,
- headers: message.headers.map(|headers| headers.to_bytes()),
- payload: message.payload.clone(),
- });
- batch_size += retained_message.get_size_bytes();
- messages.push(retained_message);
+ let message = IggyMessage::with_id(i as u128, Bytes::from("test"));
+ messages_size += message.get_size_bytes().as_bytes_u32();
+ messages.push(message);
}
- segment
- .append_batch(batch_size, messages_count as u32, &messages)
- .await
- .unwrap();
+ let batch = IggyMessagesBatchMut::from_messages(&messages, messages_size);
+ segment.append_batch(0, batch, None).await.unwrap();
segment.persist_messages(None).await.unwrap();
+ let not_expired_ts = IggyTimestamp::now();
+ let expired_ts = not_expired_ts + IggyDuration::from(message_expiry_us + 1);
- segment.is_closed = true;
- let is_expired = segment.is_expired(now).await;
- assert!(is_expired);
+ assert!(segment.is_expired(expired_ts).await);
+ assert!(!segment.is_expired(not_expired_ts).await);
}
#[tokio::test]
async fn given_at_least_one_not_expired_message_segment_should_not_be_expired() {
- let setup = TestSetup::init().await;
+ let config = SystemConfig {
+ partition: PartitionConfig {
+ enforce_fsync: true,
+ ..Default::default()
+ },
+ segment: SegmentConfig {
+ size: IggyByteSize::from_str("10B").unwrap(), // small size to force expiration
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let setup = TestSetup::init_with_config(config).await;
let stream_id = 1;
let topic_id = 2;
let partition_id = 3;
let start_offset = 0;
- let message_expiry_ms = 1000;
- let message_expiry = message_expiry_ms.into();
+ let message_expiry_us = 50000;
+ let message_expiry = message_expiry_us.into();
let mut segment = Segment::create(
stream_id,
topic_id,
@@ -415,65 +399,58 @@ async fn given_at_least_one_not_expired_message_segment_should_not_be_expired()
start_offset,
)
.await;
- let now = IggyTimestamp::now();
- let expired_timestamp = now.as_micros() - 2 * message_expiry_ms;
- let not_expired_timestamp = now.as_micros() - message_expiry_ms + 1;
- let expired_message = create_message(0, "test", expired_timestamp.into());
- let not_expired_message = create_message(1, "test", not_expired_timestamp.into());
-
- let expired_retained_message = Arc::new(RetainedMessage {
- id: expired_message.id,
- offset: expired_message.offset,
- timestamp: expired_message.timestamp,
- checksum: expired_message.checksum,
- message_state: expired_message.state,
- headers: expired_message.headers.map(|headers| headers.to_bytes()),
- payload: expired_message.payload.clone(),
- });
- let mut expired_messages = Vec::new();
- let expired_message_size = expired_retained_message.get_size_bytes();
- expired_messages.push(expired_retained_message);
-
- let mut not_expired_messages = Vec::new();
- let not_expired_retained_message = Arc::new(RetainedMessage {
- id: not_expired_message.id,
- offset: not_expired_message.offset,
- timestamp: not_expired_message.timestamp,
- checksum: not_expired_message.checksum,
- message_state: not_expired_message.state,
- headers: not_expired_message
- .headers
- .map(|headers| headers.to_bytes()),
- payload: not_expired_message.payload.clone(),
- });
- let not_expired_message_size = not_expired_retained_message.get_size_bytes();
- not_expired_messages.push(not_expired_retained_message);
- segment
- .append_batch(expired_message_size, 1, &expired_messages)
- .await
- .unwrap();
- segment
- .append_batch(not_expired_message_size, 1, ¬_expired_messages)
- .await
- .unwrap();
+ let nothing_expired_ts = IggyTimestamp::now();
+
+ let first_message = vec![IggyMessage::create(Bytes::from("expired"))];
+ let first_message_size = first_message[0].get_size_bytes().as_bytes_u32();
+ let first_batch = IggyMessagesBatchMut::from_messages(&first_message, first_message_size);
+ segment.append_batch(0, first_batch, None).await.unwrap();
+
+ sleep(Duration::from_micros(message_expiry_us / 2)).await;
+ let first_message_expired_ts = IggyTimestamp::now();
+
+ let second_message = vec![IggyMessage::create(Bytes::from("not-expired"))];
+ let second_message_size = second_message[0].get_size_bytes().as_bytes_u32();
+ let second_batch = IggyMessagesBatchMut::from_messages(&second_message, second_message_size);
+ segment.append_batch(1, second_batch, None).await.unwrap();
+
+ let second_message_expired_ts =
+ IggyTimestamp::now() + IggyDuration::from(message_expiry_us * 2);
+
segment.persist_messages(None).await.unwrap();
- let is_expired = segment.is_expired(now).await;
- assert!(!is_expired);
+ assert!(
+ !segment.is_expired(nothing_expired_ts).await,
+ "Segment should not be expired for nothing expired timestamp"
+ );
+ assert!(
+ !segment.is_expired(first_message_expired_ts).await,
+ "Segment should not be expired for first message expired timestamp"
+ );
+ assert!(
+ segment.is_expired(second_message_expired_ts).await,
+ "Segment should be expired for second message expired timestamp"
+ );
}
#[tokio::test]
async fn should_delete_persisted_segments() -> Result<(), Box<dyn std::error::Error>> {
- // Initial Setup.
- let setup = TestSetup::init().await;
+ let config = SystemConfig {
+ segment: SegmentConfig {
+ size: IggyByteSize::from_str("10B").unwrap(), // small size to force segment closure
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let setup = TestSetup::init_with_config(config).await;
let mut system = System::new(
setup.config.clone(),
DataMaintenanceConfig::default(),
PersonalAccessTokenConfig::default(),
);
- // Properties.
+ // Properties
let stream_id = Identifier::numeric(1)?;
let stream_name = "test";
let topic_name = "test_topic";
@@ -511,22 +488,33 @@ async fn should_delete_persisted_segments() -> Result<(), Box<dyn std::error::Er
.await?;
let topic = system.find_topic(&session, &stream_id, &topic_id)?;
-
let partitions = topic.get_partitions();
-
- let mut partition = partitions
+ let partition = partitions
.first()
.ok_or(IggyError::Error)
- .inspect_err(|_| log::error!("Cannot retrieve initial partition."))?
- .write()
- .await;
+ .inspect_err(|_| log::error!("Cannot retrieve initial partition."))?;
- for n in 0..=3 {
- partition.add_persisted_segment(n).await?;
- }
+ // Create multiple segments by sending messages one by one
+ // Each message should be large enough to cause a segment to close
+ for i in 0..5 {
+ let mut partition_lock = partition.write().await;
+
+ let payload = "payload that will force segment closure due to size";
+ let message = create_message(i, payload);
+ let messages = vec![message];
+
+ let messages_size = messages
+ .iter()
+ .map(|m| m.get_size_bytes().as_bytes_u32())
+ .sum();
+ let batch = IggyMessagesBatchMut::from_messages(&messages, messages_size);
+
+ partition_lock.append_messages(batch, None).await.unwrap();
+
+ drop(partition_lock);
- // Explicitly drop the lock so that we can delete the segments through a different reference.
- drop(partition);
+ sleep(Duration::from_millis(100)).await;
+ }
let partition_path = setup.config.get_partition_path(
stream_id.get_u32_value()?,
@@ -534,82 +522,131 @@ async fn should_delete_persisted_segments() -> Result<(), Box<dyn std::error::Er
partition_id,
);
- // Assert segment files were created correctly.
- let segment_files = get_segment_paths_for_partiton(&partition_path)
- .iter()
- .rev()
- .map(|dir_entry| dir_entry.file_name())
- .collect::<Vec<_>>();
+ let initial_segments = get_segment_paths_for_partition(&partition_path);
+ println!(
+ "Created segments: {:?}",
+ initial_segments
+ .iter()
+ .map(|e| e.file_name())
+ .collect::<Vec<_>>()
+ );
- assert!(segment_files.len() == 4);
+ // Since we've created 5 messages with large payloads, we should have multiple segments
+ assert!(
+ initial_segments.len() >= 4,
+ "Expected at least 4 segments but got {}",
+ initial_segments.len()
+ );
- assert!((0..=3).all(|i| segment_files.iter().any(|val| val
- .to_str()
- .is_some_and(|file_str| file_str == format!("{:0>20}.{}", i, LOG_EXTENSION)))));
+ let mut initial_offsets = get_segment_offsets(&initial_segments);
+ initial_offsets.sort();
+ println!("Initial segment offsets (sorted): {:?}", initial_offsets);
- // Attempt to delete the segment files.
+ let first_keep_count = 3usize;
system
- .delete_segments(&session, &stream_id, &topic_id, partition_id, 2)
+ .delete_segments(
+ &session,
+ &stream_id,
+ &topic_id,
+ partition_id,
+ first_keep_count as u32,
+ )
.await?;
- // Assert no changes as none are closed.
- assert!((0..=3).all(|i| segment_files.iter().any(|val| val
- .to_str()
- .is_some_and(|file_str| file_str == format!("{:0>20}.{}", i, LOG_EXTENSION)))));
-
- let topic = system.find_topic(&session, &stream_id, &topic_id)?;
-
- let partitions = topic.get_partitions();
-
- let mut partition = partitions
- .first()
- .ok_or(IggyError::Error)
- .inspect_err(|_| log::error!("Cannot retrieve initial partition."))?
- .write()
- .await;
-
- // Set the segments to closed.
- for n in 0..=3 {
- let segment = partition.get_segment_mut(n);
-
- if let Some(segment_ref) = segment {
- segment_ref.is_closed = true;
- };
- }
+ let segments_after_first_delete = get_segment_paths_for_partition(&partition_path);
+ println!(
+ "Segments after first deletion (keep={}): {:?}",
+ first_keep_count,
+ segments_after_first_delete
+ .iter()
+ .map(|e| e.file_name())
+ .collect::<Vec<_>>()
+ );
- // Explicitly drop the lock so that we can delete the segments through a different reference.
- drop(partition);
+ // We should have at most first_keep_count + 1 segments after first deletion
+ // (keep_count closed segments + 1 open segment)
+ assert!(
+ segments_after_first_delete.len() <= first_keep_count + 1,
+ "Should have at most {} segments after first deletion but got {}",
+ first_keep_count + 1,
+ segments_after_first_delete.len()
+ );
- // Attempt to delete the segment files.
+ // Second attempt to delete segments - keeping only 1 closed segment + 1 open
+ let second_keep_count = 1usize;
system
- .delete_segments(&session, &stream_id, &topic_id, partition_id, 2)
+ .delete_segments(
+ &session,
+ &stream_id,
+ &topic_id,
+ partition_id,
+ second_keep_count as u32,
+ )
.await?;
- // Assert segment files were deleted correctly.
- let segment_files = get_segment_paths_for_partiton(&partition_path)
- .iter()
- .map(|dir_entry| dir_entry.file_name())
- .collect::<Vec<_>>();
+ let segments_after_second_delete = get_segment_paths_for_partition(&partition_path);
+ println!(
+ "Segments after second deletion (keep={}): {:?}",
+ second_keep_count,
+ segments_after_second_delete
+ .iter()
+ .map(|e| e.file_name())
+ .collect::<Vec<_>>()
+ );
- assert!(segment_files.len() == 2);
+ // We should have at most second_keep_count + 1 segments after second deletion
+ // (keep_count closed segments + 1 open segment)
+ assert!(
+ segments_after_second_delete.len() <= second_keep_count + 1,
+ "Should have at most {} segments after second deletion but got {}",
+ second_keep_count + 1,
+ segments_after_second_delete.len()
+ );
- // Check that the two segments with the largest start_offset's are preserved.
- assert!((2..=3).all(|i| segment_files.iter().any(|val| val
- .to_str()
- .is_some_and(|file_str| file_str == format!("{:0>20}.{}", i, LOG_EXTENSION)))));
+ let mut final_offsets = get_segment_offsets(&segments_after_second_delete);
+ final_offsets.sort();
+
+ let highest_initial_offsets: Vec<u64> = initial_offsets
+ .iter()
+ .rev()
+ .take(second_keep_count + 1)
+ .copied()
+ .collect();
+
+ for &offset in &final_offsets {
+ assert!(
+ highest_initial_offsets.contains(&offset),
+ "Offset {} should not remain after final deletion",
+ offset
+ );
+ }
Ok(())
}
+// Helper function to extract segment offsets from DirEntry list
+fn get_segment_offsets(segments: &[DirEntry]) -> Vec<u64> {
+ segments
+ .iter()
+ .filter_map(|entry| {
+ entry.file_name().to_str().and_then(|name| {
+ name.split('.')
+ .next()
+ .and_then(|offset_str| offset_str.parse::<u64>().ok())
+ })
+ })
+ .collect()
+}
+
async fn assert_persisted_segment(partition_path: &str, start_offset: u64) {
let segment_path = format!("{}/{:0>20}", partition_path, start_offset);
- let log_path = format!("{}.{}", segment_path, LOG_EXTENSION);
+ let messages_file_path = format!("{}.{}", segment_path, LOG_EXTENSION);
let index_path = format!("{}.{}", segment_path, INDEX_EXTENSION);
- assert!(fs::metadata(&log_path).await.is_ok());
+ assert!(fs::metadata(&messages_file_path).await.is_ok());
assert!(fs::metadata(&index_path).await.is_ok());
}
-fn get_segment_paths_for_partiton(partition_path: &str) -> Vec<DirEntry> {
+fn get_segment_paths_for_partition(partition_path: &str) -> Vec<DirEntry> {
let paths = std::fs::read_dir(partition_path)
.map(|read_dir| {
read_dir
@@ -637,20 +674,6 @@ fn get_segment_paths_for_partiton(partition_path: &str) -> Vec<DirEntry> {
paths
}
-fn create_message(offset: u64, payload: &str, timestamp: IggyTimestamp) -> PolledMessage {
- let payload = Bytes::from(payload.to_string());
- let checksum = checksum::calculate(payload.as_ref());
- PolledMessage::create(
- offset,
- MessageState::Available,
- timestamp,
- 0,
- payload,
- checksum,
- None,
- )
-}
-
fn get_start_offsets() -> Vec<u64> {
vec![
0, 1, 2, 9, 10, 99, 100, 110, 200, 1000, 1234, 12345, 100000, 9999999,
diff --git a/integration/tests/streaming/snapshot.rs b/integration/tests/streaming/snapshot.rs
index 66ac7635..772d7972 100644
--- a/integration/tests/streaming/snapshot.rs
+++ b/integration/tests/streaming/snapshot.rs
@@ -42,7 +42,7 @@ async fn should_create_snapshot_file() {
.get_snapshot(
&session,
SnapshotCompression::Deflated,
- vec![SystemSnapshotType::Test],
+ &vec![SystemSnapshotType::Test],
)
.await
.unwrap();
diff --git a/integration/tests/streaming/stream.rs b/integration/tests/streaming/stream.rs
index 1c63df81..a30cbe40 100644
--- a/integration/tests/streaming/stream.rs
+++ b/integration/tests/streaming/stream.rs
@@ -19,16 +19,10 @@
use crate::streaming::common::test_setup::TestSetup;
use crate::streaming::create_messages;
use ahash::AHashMap;
-use iggy::identifier::Identifier;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::messages::send_messages::Partitioning;
-use iggy::utils::byte_size::IggyByteSize;
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::sizeable::Sizeable;
-use iggy::utils::timestamp::IggyTimestamp;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use server::state::system::StreamState;
use server::streaming::polling_consumer::PollingConsumer;
+use server::streaming::segments::IggyMessagesBatchMut;
use server::streaming::streams::stream::Stream;
use tokio::fs;
@@ -142,19 +136,20 @@ async fn should_purge_existing_stream_on_disk() {
.unwrap();
let messages = create_messages();
- let messages_count = messages.len();
+ let messages_count = messages.len() as u32;
+ let messages_size = messages
+ .iter()
+ .map(|msg| msg.get_size_bytes().as_bytes_u32())
+ .sum::<u32>();
+ let batch = IggyMessagesBatchMut::from_messages(&messages, messages_size);
let topic = stream
.get_topic(&Identifier::numeric(topic_id).unwrap())
.unwrap();
- let batch_size = messages
- .iter()
- .map(|msg| msg.get_size_bytes())
- .sum::<IggyByteSize>();
topic
- .append_messages(batch_size, Partitioning::partition_id(1), messages, None)
+ .append_messages(&Partitioning::partition_id(1), batch, None)
.await
.unwrap();
- let loaded_messages = topic
+ let (_, loaded_messages) = topic
.get_messages(
PollingConsumer::Consumer(1, 1),
1,
@@ -164,10 +159,10 @@ async fn should_purge_existing_stream_on_disk() {
.await
.unwrap();
- assert_eq!(loaded_messages.messages.len(), messages_count);
+ assert_eq!(loaded_messages.count(), messages_count);
stream.purge().await.unwrap();
- let loaded_messages = topic
+ let (metadata, loaded_messages) = topic
.get_messages(
PollingConsumer::Consumer(1, 1),
1,
@@ -176,8 +171,8 @@ async fn should_purge_existing_stream_on_disk() {
)
.await
.unwrap();
- assert_eq!(loaded_messages.current_offset, 0);
- assert!(loaded_messages.messages.is_empty());
+ assert_eq!(metadata.current_offset, 0);
+ assert!(loaded_messages.is_empty());
}
}
diff --git a/integration/tests/streaming/topic.rs b/integration/tests/streaming/topic.rs
index b24c96bc..e848964b 100644
--- a/integration/tests/streaming/topic.rs
+++ b/integration/tests/streaming/topic.rs
@@ -19,16 +19,10 @@
use crate::streaming::common::test_setup::TestSetup;
use crate::streaming::create_messages;
use ahash::AHashMap;
-use iggy::compression::compression_algorithm::CompressionAlgorithm;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::messages::send_messages::Partitioning;
-use iggy::utils::byte_size::IggyByteSize;
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::sizeable::Sizeable;
-use iggy::utils::timestamp::IggyTimestamp;
-use iggy::utils::topic_size::MaxTopicSize;
+use iggy::prelude::*;
use server::state::system::{PartitionState, TopicState};
use server::streaming::polling_consumer::PollingConsumer;
+use server::streaming::segments::IggyMessagesBatchMut;
use server::streaming::topics::topic::Topic;
use std::default::Default;
use std::sync::atomic::{AtomicU32, AtomicU64};
@@ -225,16 +219,17 @@ async fn should_purge_existing_topic_on_disk() {
.await;
let messages = create_messages();
- let messages_count = messages.len();
+ let messages_count = messages.len() as u32;
let batch_size = messages
.iter()
- .map(|msg| msg.get_size_bytes())
- .sum::<IggyByteSize>();
+ .map(|msg| msg.get_size_bytes().as_bytes_u32())
+ .sum::<u32>();
+ let batch = IggyMessagesBatchMut::from_messages(&messages, batch_size);
topic
- .append_messages(batch_size, Partitioning::partition_id(1), messages, None)
+ .append_messages(&Partitioning::partition_id(1), batch, None)
.await
.unwrap();
- let loaded_messages = topic
+ let (_, loaded_messages) = topic
.get_messages(
PollingConsumer::Consumer(1, 1),
1,
@@ -243,10 +238,10 @@ async fn should_purge_existing_topic_on_disk() {
)
.await
.unwrap();
- assert_eq!(loaded_messages.messages.len(), messages_count);
+ assert_eq!(loaded_messages.count(), messages_count);
topic.purge().await.unwrap();
- let loaded_messages = topic
+ let (metadata, loaded_messages) = topic
.get_messages(
PollingConsumer::Consumer(1, 1),
1,
@@ -255,8 +250,8 @@ async fn should_purge_existing_topic_on_disk() {
)
.await
.unwrap();
- assert_eq!(loaded_messages.current_offset, 0);
- assert!(loaded_messages.messages.is_empty());
+ assert_eq!(metadata.current_offset, 0);
+ assert!(loaded_messages.is_empty());
}
}
diff --git a/integration/tests/streaming/topic_messages.rs b/integration/tests/streaming/topic_messages.rs
index 484c9617..9572b5b1 100644
--- a/integration/tests/streaming/topic_messages.rs
+++ b/integration/tests/streaming/topic_messages.rs
@@ -18,16 +18,10 @@
use crate::streaming::common::test_setup::TestSetup;
use bytes::Bytes;
-use iggy::locking::IggySharedMutFn;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::messages::send_messages::{Message, Partitioning};
-use iggy::utils::byte_size::IggyByteSize;
-use iggy::utils::expiry::IggyExpiry;
-use iggy::utils::sizeable::Sizeable;
-use iggy::utils::topic_size::MaxTopicSize;
-use server::configs::resource_quota::MemoryResourceQuota;
-use server::configs::system::{CacheConfig, SystemConfig};
+use iggy::prelude::*;
+use server::configs::system::SystemConfig;
use server::streaming::polling_consumer::PollingConsumer;
+use server::streaming::segments::IggyMessagesBatchMut;
use server::streaming::topics::topic::Topic;
use server::streaming::utils::hash;
use std::collections::HashMap;
@@ -36,46 +30,10 @@ use std::sync::atomic::{AtomicU32, AtomicU64};
use std::sync::Arc;
#[tokio::test]
-async fn given_disabled_cache_all_messages_should_be_polled() {
- assert_polling_messages(
- CacheConfig {
- enabled: false,
- ..Default::default()
- },
- false,
- )
- .await;
-}
-
-#[tokio::test]
-async fn given_enabled_cache_with_enough_capacity_all_messages_should_be_polled() {
- assert_polling_messages(
- CacheConfig {
- enabled: true,
- size: MemoryResourceQuota::Bytes(IggyByteSize::from(100_000_000)),
- },
- true,
- )
- .await;
-}
-
-#[tokio::test]
-async fn given_enabled_cache_without_enough_capacity_all_messages_should_be_polled() {
- assert_polling_messages(
- CacheConfig {
- enabled: true,
- size: MemoryResourceQuota::Bytes(IggyByteSize::from(100_000)),
- },
- true,
- )
- .await;
-}
-
-async fn assert_polling_messages(cache: CacheConfig, expect_enabled_cache: bool) {
+async fn assert_polling_messages() {
let messages_count = 1000;
let payload_size_bytes = 1000;
let config = SystemConfig {
- cache,
..Default::default()
};
let setup = TestSetup::init_with_config(config).await;
@@ -93,7 +51,7 @@ async fn assert_polling_messages(cache: CacheConfig, expect_enabled_cache: bool)
let mut sent_messages = Vec::new();
for message in &messages {
sent_messages.push(get_message(
- message.id,
+ message.header.id,
from_utf8(&message.payload).unwrap(),
))
}
@@ -101,13 +59,14 @@ async fn assert_polling_messages(cache: CacheConfig, expect_enabled_cache: bool)
.iter()
.map(|m| m.get_size_bytes())
.sum::<IggyByteSize>();
+ let batch = IggyMessagesBatchMut::from_messages(&messages, batch_size.as_bytes_u32());
topic
- .append_messages(batch_size, partitioning, messages, None)
+ .append_messages(&partitioning, batch, None)
.await
.unwrap();
let consumer = PollingConsumer::Consumer(1, partition_id);
- let polled_messages = topic
+ let (_, polled_messages) = topic
.get_messages(
consumer,
partition_id,
@@ -117,18 +76,16 @@ async fn assert_polling_messages(cache: CacheConfig, expect_enabled_cache: bool)
.await
.unwrap();
assert_eq!(topic.get_messages_count(), messages_count as u64);
- assert_eq!(polled_messages.messages.len(), messages_count as usize);
- let partition = topic.get_partition(partition_id).unwrap();
- let partition = partition.read().await;
- assert_eq!(partition.cache.is_some(), expect_enabled_cache);
- if expect_enabled_cache {
- assert!(partition.cache.as_ref().unwrap().current_size() > 0);
- }
- for (index, polled_message) in polled_messages.messages.iter().enumerate() {
- let sent_message = sent_messages.get(index).unwrap();
- assert_eq!(sent_message.payload, polled_message.payload);
- let polled_payload_str = from_utf8(&polled_message.payload).unwrap();
- assert!(polled_payload_str.starts_with(&format!("{}:", index + 1)));
+ assert_eq!(polled_messages.count(), messages_count);
+ let mut cnt = 0;
+ for batch in polled_messages.iter() {
+ for polled_message in batch.iter() {
+ let sent_message = sent_messages.get(cnt).unwrap();
+ assert_eq!(sent_message.payload, polled_message.payload());
+ let polled_payload_str = from_utf8(polled_message.payload()).unwrap();
+ assert!(polled_payload_str.starts_with(&format!("{}:", cnt + 1)));
+ cnt += 1;
+ }
}
}
@@ -142,13 +99,12 @@ async fn given_key_none_messages_should_be_appended_to_the_next_partition_using_
for i in 1..=partitions_count * messages_per_partition_count {
let payload = get_payload(i);
let batch_size = IggyByteSize::from(16 + 4 + payload.len() as u64);
+ let messages = IggyMessagesBatchMut::from_messages(
+ &[get_message(i as u128, &payload)],
+ batch_size.as_bytes_u32(),
+ );
topic
- .append_messages(
- batch_size,
- partitioning.clone(),
- vec![get_message(i as u128, &payload)],
- None,
- )
+ .append_messages(&partitioning, messages, None)
.await
.unwrap();
}
@@ -168,13 +124,12 @@ async fn given_key_partition_id_messages_should_be_appended_to_the_chosen_partit
for i in 1..=partitions_count * messages_per_partition_count {
let payload = get_payload(i);
let batch_size = IggyByteSize::from(16 + 4 + payload.len() as u64);
+ let messages = IggyMessagesBatchMut::from_messages(
+ &[get_message(i as u128, &payload)],
+ batch_size.as_bytes_u32(),
+ );
topic
- .append_messages(
- batch_size,
- partitioning.clone(),
- vec![get_message(i as u128, &payload)],
- None,
- )
+ .append_messages(&partitioning, messages, None)
.await
.unwrap();
}
@@ -198,13 +153,12 @@ async fn given_key_messages_key_messages_should_be_appended_to_the_calculated_pa
let payload = get_payload(entity_id);
let partitioning = Partitioning::messages_key_u32(entity_id);
let batch_size = IggyByteSize::from(16 + 4 + payload.len() as u64);
+ let messages = IggyMessagesBatchMut::from_messages(
+ &[get_message(entity_id as u128, &payload)],
+ batch_size.as_bytes_u32(),
+ );
topic
- .append_messages(
- batch_size,
- partitioning,
- vec![get_message(entity_id as u128, &payload)],
- None,
- )
+ .append_messages(&partitioning, messages, None)
.await
.unwrap();
}
@@ -235,11 +189,11 @@ fn get_payload(id: u32) -> String {
async fn assert_messages(topic: &Topic, partition_id: u32, expected_messages: u32) {
let consumer = PollingConsumer::Consumer(0, partition_id);
- let polled_messages = topic
+ let (_, polled_messages) = topic
.get_messages(consumer, partition_id, PollingStrategy::offset(0), 1000)
.await
.unwrap();
- assert_eq!(polled_messages.messages.len() as u32, expected_messages);
+ assert_eq!(polled_messages.count(), expected_messages);
}
async fn init_topic(setup: &TestSetup, partitions_count: u32) -> Topic {
@@ -268,13 +222,8 @@ async fn init_topic(setup: &TestSetup, partitions_count: u32) -> Topic {
topic
}
-fn get_message(id: u128, payload: &str) -> Message {
- Message {
- id,
- length: payload.len() as u32,
- payload: Bytes::from(payload.as_bytes().to_vec()),
- headers: None,
- }
+fn get_message(id: u128, payload: &str) -> IggyMessage {
+ IggyMessage::with_id(id, Bytes::from(payload.to_owned()))
}
fn create_payload(size: u32) -> String {
diff --git a/sdk/Cargo.toml b/sdk/Cargo.toml
index f9e79a12..dde3979b 100644
--- a/sdk/Cargo.toml
+++ b/sdk/Cargo.toml
@@ -28,6 +28,12 @@ documentation = "https://iggy.apache.org/docs"
repository = "https://github.com/apache/iggy"
readme = "../README.md"
+[features]
+default = ["tokio_lock"]
+iggy-cli = ["dep:comfy-table", "dep:keyring", "dep:passterm"]
+tokio_lock = []
+fast_async_lock = ["dep:fast-async-mutex"]
+
[dependencies]
aes-gcm = "0.10.3"
ahash = { version = "0.8.11", features = ["serde"] }
@@ -42,7 +48,7 @@ byte-unit = { version = "5.1.6", default-features = false, features = [
"byte",
"std",
] }
-bytes = "1.10.1"
+bytes = { version = "1.10.1", features = ["serde"] }
chrono = { version = "0.4.40" }
clap = { version = "4.5.34", features = ["derive"] }
comfy-table = { version = "7.1.4", optional = true }
@@ -85,9 +91,3 @@ webpki-roots = { version = "0.26.8" }
convert_case = "0.8.0"
serde = { version = "1.0.219", features = ["derive", "rc"] }
serde_derive = "1.0.219"
-
-[features]
-default = ["tokio_lock"]
-iggy-cli = ["dep:comfy-table", "dep:keyring", "dep:passterm"]
-tokio_lock = []
-fast_async_lock = ["dep:fast-async-mutex"]
diff --git a/sdk/src/binary/mapper.rs b/sdk/src/binary/mapper.rs
index c4e4597d..8559c8f4 100644
--- a/sdk/src/binary/mapper.rs
+++ b/sdk/src/binary/mapper.rs
@@ -23,7 +23,6 @@ use crate::models::client_info::{ClientInfo, ClientInfoDetails, ConsumerGroupInf
use crate::models::consumer_group::{ConsumerGroup, ConsumerGroupDetails, ConsumerGroupMember};
use crate::models::consumer_offset_info::ConsumerOffsetInfo;
use crate::models::identity_info::IdentityInfo;
-use crate::models::messages::{MessageState, PolledMessage, PolledMessages};
use crate::models::partition::Partition;
use crate::models::permissions::Permissions;
use crate::models::personal_access_token::{PersonalAccessTokenInfo, RawPersonalAccessToken};
@@ -39,7 +38,6 @@ use bytes::Bytes;
use std::collections::HashMap;
use std::str::from_utf8;
-const EMPTY_MESSAGES: Vec<PolledMessage> = vec![];
const EMPTY_TOPICS: Vec<Topic> = vec![];
const EMPTY_STREAMS: Vec<Stream> = vec![];
const EMPTY_CLIENTS: Vec<ClientInfo> = vec![];
@@ -545,106 +543,6 @@ pub fn map_clients(payload: Bytes) -> Result<Vec<ClientInfo>, IggyError> {
Ok(clients)
}
-pub fn map_polled_messages(payload: Bytes) -> Result<PolledMessages, IggyError> {
- if payload.is_empty() {
- return Ok(PolledMessages {
- messages: EMPTY_MESSAGES,
- partition_id: 0,
- current_offset: 0,
- });
- }
-
- let length = payload.len();
- let partition_id = u32::from_le_bytes(
- payload[..4]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let current_offset = u64::from_le_bytes(
- payload[4..12]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- // Currently ignored
- let _messages_count = u32::from_le_bytes(
- payload[12..16]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let mut position = 16;
- let mut messages = Vec::new();
- while position < length {
- let offset = u64::from_le_bytes(
- payload[position..position + 8]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let state = MessageState::from_code(payload[position + 8])?;
- let timestamp = u64::from_le_bytes(
- payload[position + 9..position + 17]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let id = u128::from_le_bytes(
- payload[position + 17..position + 33]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let checksum = u32::from_le_bytes(
- payload[position + 33..position + 37]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let headers_length = u32::from_le_bytes(
- payload[position + 37..position + 41]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let headers = if headers_length > 0 {
- let headers_payload =
- payload.slice(position + 41..position + 41 + headers_length as usize);
- Some(HashMap::from_bytes(headers_payload)?)
- } else {
- None
- };
- position += headers_length as usize;
- let message_length = u32::from_le_bytes(
- payload[position + 41..position + 45]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let payload_range = position + 45..position + 45 + message_length as usize;
- if payload_range.start > length || payload_range.end > length {
- break;
- }
-
- let payload = payload[payload_range].to_vec();
- let total_size = 45 + message_length as usize;
- position += total_size;
- messages.push(PolledMessage {
- offset,
- timestamp,
- state,
- checksum,
- id,
- headers,
- length: IggyByteSize::from(message_length as u64),
- payload: Bytes::from(payload),
- });
-
- if position + 45 >= length {
- break;
- }
- }
-
- messages.sort_by(|x, y| x.offset.cmp(&y.offset));
- Ok(PolledMessages {
- partition_id,
- current_offset,
- messages,
- })
-}
-
pub fn map_streams(payload: Bytes) -> Result<Vec<Stream>, IggyError> {
if payload.is_empty() {
return Ok(EMPTY_STREAMS);
diff --git a/sdk/src/binary/messages.rs b/sdk/src/binary/messages.rs
index a9c23225..7503ff19 100644
--- a/sdk/src/binary/messages.rs
+++ b/sdk/src/binary/messages.rs
@@ -17,17 +17,15 @@
*/
use crate::binary::binary_client::BinaryClient;
-use crate::binary::{fail_if_not_authenticated, mapper};
+use crate::binary::fail_if_not_authenticated;
use crate::client::MessageClient;
use crate::command::{POLL_MESSAGES_CODE, SEND_MESSAGES_CODE};
use crate::consumer::Consumer;
use crate::error::IggyError;
use crate::identifier::Identifier;
-use crate::messages::flush_unsaved_buffer::FlushUnsavedBuffer;
-use crate::messages::poll_messages::PollingStrategy;
-use crate::messages::send_messages::{Message, Partitioning};
-use crate::messages::{poll_messages, send_messages};
-use crate::models::messages::PolledMessages;
+use crate::messages::{FlushUnsavedBuffer, PollingStrategy};
+use crate::models::messaging::IggyMessage;
+use crate::prelude::{BytesSerializable, Partitioning, PollMessages, PolledMessages, SendMessages};
#[async_trait::async_trait]
impl<B: BinaryClient> MessageClient for B {
@@ -45,7 +43,7 @@ impl<B: BinaryClient> MessageClient for B {
let response = self
.send_raw_with_response(
POLL_MESSAGES_CODE,
- poll_messages::as_bytes(
+ PollMessages::as_bytes(
stream_id,
topic_id,
partition_id,
@@ -56,7 +54,7 @@ impl<B: BinaryClient> MessageClient for B {
),
)
.await?;
- mapper::map_polled_messages(response)
+ PolledMessages::from_bytes(response)
}
async fn send_messages(
@@ -64,12 +62,12 @@ impl<B: BinaryClient> MessageClient for B {
stream_id: &Identifier,
topic_id: &Identifier,
partitioning: &Partitioning,
- messages: &mut [Message],
+ messages: &mut [IggyMessage],
) -> Result<(), IggyError> {
fail_if_not_authenticated(self).await?;
self.send_raw_with_response(
SEND_MESSAGES_CODE,
- send_messages::as_bytes(stream_id, topic_id, partitioning, messages),
+ SendMessages::as_bytes(stream_id, topic_id, partitioning, messages),
)
.await?;
Ok(())
diff --git a/sdk/src/bytes_serializable.rs b/sdk/src/bytes_serializable.rs
index 3f747b58..ed5233d9 100644
--- a/sdk/src/bytes_serializable.rs
+++ b/sdk/src/bytes_serializable.rs
@@ -16,9 +16,8 @@
* under the License.
*/
-use bytes::Bytes;
-
use crate::error::IggyError;
+use bytes::{Bytes, BytesMut};
/// The trait represents the logic responsible for serializing and deserializing the struct to and from bytes.
pub trait BytesSerializable {
@@ -29,4 +28,14 @@ pub trait BytesSerializable {
fn from_bytes(bytes: Bytes) -> Result<Self, IggyError>
where
Self: Sized;
+
+ /// Write the struct to a buffer.
+ fn write_to_buffer(&self, _buf: &mut BytesMut) {
+ unimplemented!();
+ }
+
+ /// Get the byte-size of the struct.
+ fn get_buffer_size(&self) -> usize {
+ unimplemented!();
+ }
}
diff --git a/sdk/src/cli/message/poll_messages.rs b/sdk/src/cli/message/poll_messages.rs
index de104a21..ee7f011f 100644
--- a/sdk/src/cli/message/poll_messages.rs
+++ b/sdk/src/cli/message/poll_messages.rs
@@ -21,18 +21,15 @@ use crate::cli_command::{CliCommand, PRINT_TARGET};
use crate::client::Client;
use crate::consumer::Consumer;
use crate::identifier::Identifier;
-use crate::messages::poll_messages::{PollMessages, PollingStrategy};
-use crate::messages::send_messages::Message;
-use crate::models::header::{HeaderKey, HeaderKind};
-use crate::models::messages::PolledMessages;
-use crate::utils::sizeable::Sizeable;
+use crate::messages::{PollMessages, PollingStrategy};
+use crate::models::messaging::HeaderKind;
+use crate::prelude::{HeaderKey, HeaderValue, IggyMessage, Sizeable};
use crate::utils::timestamp::IggyTimestamp;
use crate::utils::{byte_size::IggyByteSize, duration::IggyDuration};
use anyhow::Context;
use async_trait::async_trait;
use comfy_table::{Cell, CellAlignment, Row, Table};
-use std::collections::HashSet;
-use std::mem::size_of_val;
+use std::collections::{HashMap, HashSet};
use tokio::io::AsyncWriteExt;
use tracing::{event, Level};
@@ -82,19 +79,24 @@ impl PollMessagesCmd {
fn create_message_header_keys(
&self,
- polled_messages: &PolledMessages,
+ polled_messages: &[IggyMessage],
) -> HashSet<(HeaderKey, HeaderKind)> {
if !self.show_headers {
return HashSet::new();
}
polled_messages
- .messages
.iter()
- .flat_map(|m| match m.headers.as_ref() {
- Some(h) => h
- .iter()
- .map(|(k, v)| (k.clone(), v.kind))
- .collect::<Vec<_>>(),
+ .flat_map(|m| match m.user_headers.as_ref() {
+ Some(h) => match HashMap::<HeaderKey, HeaderValue>::from_bytes(h.clone()) {
+ Ok(headers) => headers
+ .iter()
+ .map(|(k, v)| (k.clone(), v.kind))
+ .collect::<Vec<_>>(),
+ Err(e) => {
+ tracing::error!("Failed to parse user headers, error: {e}");
+ vec![]
+ }
+ },
None => vec![],
})
.collect::<HashSet<_>>()
@@ -120,17 +122,17 @@ impl PollMessagesCmd {
}
fn create_table_content(
- polled_messages: &PolledMessages,
+ polled_messages: &[IggyMessage],
message_header_keys: &HashSet<(HeaderKey, HeaderKind)>,
) -> Vec<Row> {
polled_messages
- .messages
.iter()
.map(|message| {
let mut row = vec![
- format!("{}", message.offset),
- IggyTimestamp::from(message.timestamp).to_local_string("%Y-%m-%d %H:%M:%S%.6f"),
- format!("{}", message.id),
+ format!("{}", message.header.offset),
+ IggyTimestamp::from(message.header.timestamp)
+ .to_local_string("%Y-%m-%d %H:%M:%S%.6f"),
+ format!("{}", message.header.id),
format!("{}", message.payload.len()),
String::from_utf8_lossy(&message.payload).to_string(),
];
@@ -139,7 +141,8 @@ impl PollMessagesCmd {
.iter()
.map(|(key, kind)| {
message
- .headers
+ .user_headers_map()
+ .expect("Failed to parse user headers")
.as_ref()
.map(|h| {
h.get(key)
@@ -168,7 +171,7 @@ impl CliCommand for PollMessagesCmd {
async fn execute_cmd(&mut self, client: &dyn Client) -> anyhow::Result<(), anyhow::Error> {
let start = std::time::Instant::now();
- let messages = client
+ let polled_messages = client
.poll_messages(
&self.poll_messages.stream_id,
&self.poll_messages.topic_id,
@@ -191,18 +194,18 @@ impl CliCommand for PollMessagesCmd {
"Polled messages from topic with ID: {} and stream with ID: {} (from partition with ID: {})",
self.poll_messages.topic_id,
self.poll_messages.stream_id,
- messages.partition_id,
+ polled_messages.partition_id,
);
let polled_size = IggyByteSize::from(
- messages
+ polled_messages
.messages
.iter()
- .map(|m| size_of_val(m) as u64)
+ .map(|m| m.get_size_bytes().as_bytes_u64())
.sum::<u64>(),
);
- let message_count_message = match messages.messages.len() {
+ let message_count_message = match polled_messages.messages.len() {
1 => "1 message".into(),
count => format!("{} messages", count),
};
@@ -219,15 +222,10 @@ impl CliCommand for PollMessagesCmd {
.await
.with_context(|| format!("Problem opening file for writing: {output_file}"))?;
- for message in messages.messages.iter() {
- let message = Message::new(
- Some(message.id),
- message.payload.clone(),
- message.headers.clone(),
- );
- saved_size += message.get_size_bytes();
-
- file.write_all(&message.to_bytes())
+ for message in polled_messages.messages.iter() {
+ let message = message.to_bytes();
+ saved_size += IggyByteSize::from(message.len() as u64);
+ file.write_all(&message)
.await
.with_context(|| format!("Problem writing message to file: {output_file}"))?;
}
@@ -235,11 +233,12 @@ impl CliCommand for PollMessagesCmd {
let saved_size_str = saved_size.as_human_string();
event!(target: PRINT_TARGET, Level::INFO, "Stored {message_count_message} of total size {saved_size_str} to {output_file} binary file");
} else {
- let message_header_keys = self.create_message_header_keys(&messages);
+ let message_header_keys = self.create_message_header_keys(&polled_messages.messages);
let mut table = Table::new();
let table_header = Self::create_table_header(&message_header_keys);
- let table_content = Self::create_table_content(&messages, &message_header_keys);
+ let table_content =
+ Self::create_table_content(&polled_messages.messages, &message_header_keys);
table.set_header(table_header);
table.add_rows(table_content);
diff --git a/sdk/src/cli/message/send_messages.rs b/sdk/src/cli/message/send_messages.rs
index 61cb2540..11da9738 100644
--- a/sdk/src/cli/message/send_messages.rs
+++ b/sdk/src/cli/message/send_messages.rs
@@ -20,8 +20,8 @@ use crate::bytes_serializable::BytesSerializable;
use crate::cli_command::{CliCommand, PRINT_TARGET};
use crate::client::Client;
use crate::identifier::Identifier;
-use crate::messages::send_messages::{Message, Partitioning};
-use crate::models::header::{HeaderKey, HeaderValue};
+use crate::prelude::{HeaderKey, IggyMessage};
+use crate::prelude::{HeaderValue, Partitioning};
use crate::utils::sizeable::Sizeable;
use anyhow::Context;
use async_trait::async_trait;
@@ -113,13 +113,13 @@ impl CliCommand for SendMessagesCmd {
"Read {} bytes from {} file", buffer.len(), input_file,
);
- let mut messages: Vec<Message> = Vec::new();
+ let mut messages: Vec<IggyMessage> = Vec::new();
let mut bytes_read = 0usize;
let all_messages_bytes: Bytes = buffer.into();
while bytes_read < all_messages_bytes.len() {
let message_bytes = all_messages_bytes.slice(bytes_read..);
- let message = Message::from_bytes(message_bytes);
+ let message = IggyMessage::from_bytes(message_bytes);
match message {
Ok(message) => {
let message_size = message.get_size_bytes().as_bytes_usize();
@@ -140,18 +140,31 @@ impl CliCommand for SendMessagesCmd {
messages
} else {
+ let headers = self.get_headers();
match &self.messages {
Some(messages) => messages
.iter()
- .map(|s| Message::new(None, s.clone().into(), self.get_headers()))
- .collect::<Vec<_>>(),
+ .map(|s| {
+ IggyMessage::builder()
+ .payload(Bytes::from(s.clone()))
+ .headers(headers.clone().unwrap_or_default())
+ .build()
+ })
+ .collect::<Result<Vec<_>, _>>()
+ .with_context(|| "Failed to create messages from provided strings")?,
None => {
let input = self.read_message_from_stdin()?;
input
.lines()
- .map(|m| Message::new(None, String::from(m).into(), self.get_headers()))
- .collect()
+ .map(|m| {
+ IggyMessage::builder()
+ .payload(m.to_owned())
+ .headers(headers.clone().unwrap_or_default())
+ .build()
+ })
+ .collect::<Result<Vec<_>, _>>()
+ .with_context(|| "Failed to create messages from stdin")?
}
}
};
diff --git a/sdk/src/cli/segments/mod.rs b/sdk/src/cli/segments/mod.rs
index 766ab72a..0367bb5b 100644
--- a/sdk/src/cli/segments/mod.rs
+++ b/sdk/src/cli/segments/mod.rs
@@ -1 +1,19 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
pub mod delete_segments;
diff --git a/sdk/src/client.rs b/sdk/src/client.rs
index 19aaf5e9..0ed24c6c 100644
--- a/sdk/src/client.rs
+++ b/sdk/src/client.rs
@@ -21,13 +21,10 @@ use crate::consumer::Consumer;
use crate::diagnostic::DiagnosticEvent;
use crate::error::IggyError;
use crate::identifier::Identifier;
-use crate::messages::poll_messages::PollingStrategy;
-use crate::messages::send_messages::{Message, Partitioning};
use crate::models::client_info::{ClientInfo, ClientInfoDetails};
use crate::models::consumer_group::{ConsumerGroup, ConsumerGroupDetails};
use crate::models::consumer_offset_info::ConsumerOffsetInfo;
use crate::models::identity_info::IdentityInfo;
-use crate::models::messages::PolledMessages;
use crate::models::permissions::Permissions;
use crate::models::personal_access_token::{PersonalAccessTokenInfo, RawPersonalAccessToken};
use crate::models::snapshot::Snapshot;
@@ -36,6 +33,7 @@ use crate::models::stream::{Stream, StreamDetails};
use crate::models::topic::{Topic, TopicDetails};
use crate::models::user_info::{UserInfo, UserInfoDetails};
use crate::models::user_status::UserStatus;
+use crate::prelude::*;
use crate::snapshot::{SnapshotCompression, SystemSnapshotType};
use crate::tcp::config::{TcpClientConfig, TcpClientReconnectionConfig};
use crate::utils::duration::IggyDuration;
@@ -366,6 +364,7 @@ pub trait MessageClient {
count: u32,
auto_commit: bool,
) -> Result<PolledMessages, IggyError>;
+
/// Send messages using specified partitioning strategy to the given stream and topic by unique IDs or names.
///
/// Authentication is required, and the permission to send the messages.
@@ -374,8 +373,9 @@ pub trait MessageClient {
stream_id: &Identifier,
topic_id: &Identifier,
partitioning: &Partitioning,
- messages: &mut [Message],
+ messages: &mut [IggyMessage],
) -> Result<(), IggyError>;
+
/// Force flush of the `unsaved_messages` buffer to disk, optionally fsyncing the data.
#[allow(clippy::too_many_arguments)]
async fn flush_unsaved_buffer(
diff --git a/sdk/src/clients/client.rs b/sdk/src/clients/client.rs
index d7706666..cea8b0bd 100644
--- a/sdk/src/clients/client.rs
+++ b/sdk/src/clients/client.rs
@@ -30,13 +30,12 @@ use crate::error::IggyError;
use crate::identifier::Identifier;
use crate::locking::IggySharedMut;
use crate::locking::IggySharedMutFn;
-use crate::messages::poll_messages::PollingStrategy;
-use crate::messages::send_messages::{Message, Partitioning};
+use crate::messages::PollingStrategy;
use crate::models::client_info::{ClientInfo, ClientInfoDetails};
use crate::models::consumer_group::{ConsumerGroup, ConsumerGroupDetails};
use crate::models::consumer_offset_info::ConsumerOffsetInfo;
use crate::models::identity_info::IdentityInfo;
-use crate::models::messages::PolledMessages;
+use crate::models::messaging::IggyMessage;
use crate::models::permissions::Permissions;
use crate::models::personal_access_token::{PersonalAccessTokenInfo, RawPersonalAccessToken};
use crate::models::snapshot::Snapshot;
@@ -46,9 +45,9 @@ use crate::models::topic::{Topic, TopicDetails};
use crate::models::user_info::{UserInfo, UserInfoDetails};
use crate::models::user_status::UserStatus;
use crate::partitioner::Partitioner;
+use crate::prelude::{Partitioning, PolledMessages};
use crate::snapshot::{SnapshotCompression, SystemSnapshotType};
use crate::tcp::client::TcpClient;
-use crate::utils::byte_size::IggyByteSize;
use crate::utils::crypto::EncryptorKind;
use crate::utils::duration::IggyDuration;
use crate::utils::expiry::IggyExpiry;
@@ -602,7 +601,7 @@ impl MessageClient for IggyClient {
for message in &mut polled_messages.messages {
let payload = encryptor.decrypt(&message.payload)?;
message.payload = Bytes::from(payload);
- message.length = IggyByteSize::from(message.payload.len() as u64);
+ message.header.payload_length = message.payload.len() as u32;
}
}
@@ -614,7 +613,7 @@ impl MessageClient for IggyClient {
stream_id: &Identifier,
topic_id: &Identifier,
partitioning: &Partitioning,
- messages: &mut [Message],
+ messages: &mut [IggyMessage],
) -> Result<(), IggyError> {
if messages.is_empty() {
return Err(IggyError::InvalidMessagesCount);
@@ -623,7 +622,7 @@ impl MessageClient for IggyClient {
if let Some(encryptor) = &self.encryptor {
for message in &mut *messages {
message.payload = Bytes::from(encryptor.encrypt(&message.payload)?);
- message.length = message.payload.len() as u32;
+ message.header.payload_length = message.payload.len() as u32;
}
}
diff --git a/sdk/src/clients/consumer.rs b/sdk/src/clients/consumer.rs
index 5911bb86..5823bf14 100644
--- a/sdk/src/clients/consumer.rs
+++ b/sdk/src/clients/consumer.rs
@@ -22,9 +22,8 @@ use crate::diagnostic::DiagnosticEvent;
use crate::error::IggyError;
use crate::identifier::{IdKind, Identifier};
use crate::locking::{IggySharedMut, IggySharedMutFn};
-use crate::messages::poll_messages::{PollingKind, PollingStrategy};
-use crate::models::messages::{PolledMessage, PolledMessages};
-use crate::utils::byte_size::IggyByteSize;
+use crate::messages::PollingStrategy;
+use crate::prelude::{IggyMessage, PolledMessages, PollingKind};
use crate::utils::crypto::EncryptorKind;
use crate::utils::duration::IggyDuration;
use crate::utils::timestamp::IggyTimestamp;
@@ -43,8 +42,6 @@ use tokio::time;
use tokio::time::sleep;
use tracing::{error, info, trace, warn};
-const EMPTY_MESSAGES: Vec<PolledMessage> = Vec::new();
-
const ORDERING: std::sync::atomic::Ordering = std::sync::atomic::Ordering::SeqCst;
type PollMessagesFuture = Pin<Box<dyn Future<Output = Result<PolledMessages, IggyError>>>>;
@@ -120,7 +117,7 @@ pub struct IggyConsumer {
last_consumed_offsets: Arc<DashMap<u32, AtomicU64>>,
current_offsets: Arc<DashMap<u32, AtomicU64>>,
poll_future: Option<PollMessagesFuture>,
- buffered_messages: VecDeque<PolledMessage>,
+ buffered_messages: VecDeque<IggyMessage>,
encryptor: Option<Arc<EncryptorKind>>,
store_offset_sender: flume::Sender<(u32, u64)>,
store_offset_after_each_message: bool,
@@ -650,13 +647,9 @@ impl IggyConsumer {
if !allow_replay && has_consumed_offset {
polled_messages
.messages
- .retain(|message| message.offset > consumed_offset);
+ .retain(|message| message.header.offset > consumed_offset);
if polled_messages.messages.is_empty() {
- return Ok(PolledMessages {
- messages: EMPTY_MESSAGES,
- current_offset: polled_messages.current_offset,
- partition_id,
- });
+ return Ok(PolledMessages::empty());
}
}
@@ -708,9 +701,10 @@ impl IggyConsumer {
}
return Ok(PolledMessages {
- messages: EMPTY_MESSAGES,
+ messages: vec![],
current_offset: polled_messages.current_offset,
partition_id,
+ count: 0,
});
}
@@ -806,13 +800,13 @@ impl IggyConsumer {
}
pub struct ReceivedMessage {
- pub message: PolledMessage,
+ pub message: IggyMessage,
pub current_offset: u64,
pub partition_id: u32,
}
impl ReceivedMessage {
- pub fn new(message: PolledMessage, current_offset: u64, partition_id: u32) -> Self {
+ pub fn new(message: IggyMessage, current_offset: u64, partition_id: u32) -> Self {
Self {
message,
current_offset,
@@ -831,27 +825,27 @@ impl Stream for IggyConsumer {
if let Some(last_consumed_offset_entry) =
self.last_consumed_offsets.get(&partition_id)
{
- last_consumed_offset_entry.store(message.offset, ORDERING);
+ last_consumed_offset_entry.store(message.header.offset, ORDERING);
} else {
self.last_consumed_offsets
- .insert(partition_id, AtomicU64::new(message.offset));
+ .insert(partition_id, AtomicU64::new(message.header.offset));
}
if (self.store_after_every_nth_message > 0
- && message.offset % self.store_after_every_nth_message == 0)
+ && message.header.offset % self.store_after_every_nth_message == 0)
|| self.store_offset_after_each_message
{
- self.send_store_offset(partition_id, message.offset);
+ self.send_store_offset(partition_id, message.header.offset);
}
}
if self.buffered_messages.is_empty() {
if self.polling_strategy.kind == PollingKind::Offset {
- self.polling_strategy = PollingStrategy::offset(message.offset + 1);
+ self.polling_strategy = PollingStrategy::offset(message.header.offset + 1);
}
if self.store_offset_after_all_messages {
- self.send_store_offset(partition_id, message.offset);
+ self.send_store_offset(partition_id, message.header.offset);
}
}
@@ -887,14 +881,14 @@ impl Stream for IggyConsumer {
let payload = encryptor.decrypt(&message.payload);
if payload.is_err() {
self.poll_future = None;
- error!("Failed to decrypt the message payload at offset: {}, partition ID: {}", message.offset, partition_id);
+ error!("Failed to decrypt the message payload at offset: {}, partition ID: {}", message.header.offset, partition_id);
let error = payload.unwrap_err();
return Poll::Ready(Some(Err(error)));
}
let payload = payload.unwrap();
message.payload = Bytes::from(payload);
- message.length = IggyByteSize::from(message.payload.len() as u64);
+ message.header.payload_length = message.payload.len() as u32;
}
}
@@ -912,25 +906,29 @@ impl Stream for IggyConsumer {
self.buffered_messages.extend(polled_messages.messages);
if self.polling_strategy.kind == PollingKind::Offset {
- self.polling_strategy = PollingStrategy::offset(message.offset + 1);
+ self.polling_strategy =
+ PollingStrategy::offset(message.header.offset + 1);
}
if let Some(last_consumed_offset_entry) =
self.last_consumed_offsets.get(&partition_id)
{
- last_consumed_offset_entry.store(message.offset, ORDERING);
+ last_consumed_offset_entry.store(message.header.offset, ORDERING);
} else {
self.last_consumed_offsets
- .insert(partition_id, AtomicU64::new(message.offset));
+ .insert(partition_id, AtomicU64::new(message.header.offset));
}
if (self.store_after_every_nth_message > 0
- && message.offset % self.store_after_every_nth_message == 0)
+ && message.header.offset % self.store_after_every_nth_message == 0)
|| self.store_offset_after_each_message
|| (self.store_offset_after_all_messages
&& self.buffered_messages.is_empty())
{
- self.send_store_offset(polled_messages.partition_id, message.offset);
+ self.send_store_offset(
+ polled_messages.partition_id,
+ message.header.offset,
+ );
}
self.poll_future = None;
diff --git a/sdk/src/clients/producer.rs b/sdk/src/clients/producer.rs
index 4936c9bb..47a2b1a0 100644
--- a/sdk/src/clients/producer.rs
+++ b/sdk/src/clients/producer.rs
@@ -22,8 +22,9 @@ use crate::diagnostic::DiagnosticEvent;
use crate::error::IggyError;
use crate::identifier::{IdKind, Identifier};
use crate::locking::{IggySharedMut, IggySharedMutFn};
-use crate::messages::send_messages::{Message, Partitioning};
use crate::partitioner::Partitioner;
+use crate::prelude::IggyMessage;
+use crate::prelude::Partitioning;
use crate::utils::crypto::EncryptorKind;
use crate::utils::duration::IggyDuration;
use crate::utils::expiry::IggyExpiry;
@@ -230,7 +231,7 @@ impl IggyProducer {
});
}
- pub async fn send(&self, messages: Vec<Message>) -> Result<(), IggyError> {
+ pub async fn send(&self, messages: Vec<IggyMessage>) -> Result<(), IggyError> {
if messages.is_empty() {
trace!("No messages to send.");
return Ok(());
@@ -251,13 +252,13 @@ impl IggyProducer {
.await
}
- pub async fn send_one(&self, message: Message) -> Result<(), IggyError> {
+ pub async fn send_one(&self, message: IggyMessage) -> Result<(), IggyError> {
self.send(vec![message]).await
}
pub async fn send_with_partitioning(
&self,
- messages: Vec<Message>,
+ messages: Vec<IggyMessage>,
partitioning: Option<Arc<Partitioning>>,
) -> Result<(), IggyError> {
if messages.is_empty() {
@@ -284,7 +285,7 @@ impl IggyProducer {
&self,
stream: Arc<Identifier>,
topic: Arc<Identifier>,
- messages: Vec<Message>,
+ messages: Vec<IggyMessage>,
partitioning: Option<Arc<Partitioning>>,
) -> Result<(), IggyError> {
if messages.is_empty() {
@@ -306,7 +307,7 @@ impl IggyProducer {
&self,
stream: Arc<Identifier>,
topic: Arc<Identifier>,
- mut messages: Vec<Message>,
+ mut messages: Vec<IggyMessage>,
partitioning: Option<Arc<Partitioning>>,
) -> Result<(), IggyError> {
self.encrypt_messages(&mut messages)?;
@@ -342,7 +343,7 @@ impl IggyProducer {
&self,
stream: &Identifier,
topic: &Identifier,
- mut messages: Vec<Message>,
+ mut messages: Vec<IggyMessage>,
partitioning: Option<Arc<Partitioning>>,
) -> Result<(), IggyError> {
trace!("No batch size specified, sending messages immediately.");
@@ -383,11 +384,11 @@ impl IggyProducer {
sleep(Duration::from_micros(remaining)).await;
}
- fn encrypt_messages(&self, messages: &mut [Message]) -> Result<(), IggyError> {
+ fn encrypt_messages(&self, messages: &mut [IggyMessage]) -> Result<(), IggyError> {
if let Some(encryptor) = &self.encryptor {
for message in messages {
message.payload = Bytes::from(encryptor.encrypt(&message.payload)?);
- message.length = message.payload.len() as u32;
+ message.header.payload_length = message.payload.len() as u32;
}
}
Ok(())
@@ -398,7 +399,7 @@ impl IggyProducer {
stream: &Identifier,
topic: &Identifier,
partitioning: &Arc<Partitioning>,
- messages: &mut [Message],
+ messages: &mut [IggyMessage],
) -> Result<(), IggyError> {
let client = self.client.read().await;
let Some(max_retries) = self.send_retries_count else {
@@ -474,7 +475,7 @@ impl IggyProducer {
stream: &Identifier,
topic: &Identifier,
partitioning: &Arc<Partitioning>,
- messages: &mut [Message],
+ messages: &mut [IggyMessage],
timer: &mut Option<Interval>,
) -> Result<(), IggyError> {
let client = self.client.read().await;
@@ -516,7 +517,7 @@ impl IggyProducer {
&self,
stream: &Identifier,
topic: &Identifier,
- messages: &[Message],
+ messages: &[IggyMessage],
partitioning: Option<Arc<Partitioning>>,
) -> Result<Arc<Partitioning>, IggyError> {
if let Some(partitioner) = &self.partitioner {
diff --git a/sdk/src/consumer_ext/consumer_message_ext.rs b/sdk/src/consumer_ext/consumer_message_ext.rs
index 0edf8c25..48767b0f 100644
--- a/sdk/src/consumer_ext/consumer_message_ext.rs
+++ b/sdk/src/consumer_ext/consumer_message_ext.rs
@@ -88,7 +88,7 @@ impl IggyConsumerMessageExt for IggyConsumer {
Some(Ok(received_message)) => {
let partition_id = received_message.partition_id;
let current_offset = received_message.current_offset;
- let message_offset = received_message.message.offset;
+ let message_offset = received_message.message.header.offset;
if let Err(err) = message_consumer.consume(received_message).await {
error!("Error while handling message at offset: {message_offset}/{current_offset}, partition: {partition_id} for consumer: {name} on topic: {topic} and stream: {stream} due to error: {err}",
name = self.name(), topic = self.topic(), stream = self.stream());
diff --git a/sdk/src/consumer_ext/mod.rs b/sdk/src/consumer_ext/mod.rs
index aa9680b7..49b9443c 100644
--- a/sdk/src/consumer_ext/mod.rs
+++ b/sdk/src/consumer_ext/mod.rs
@@ -19,8 +19,7 @@
mod consumer_message_ext;
mod consumer_message_trait;
-use crate::clients::consumer::ReceivedMessage;
-use crate::error::IggyError;
+use crate::{clients::consumer::ReceivedMessage, error::IggyError};
pub use consumer_message_trait::IggyConsumerMessageExt;
/// Trait for message consumer
diff --git a/sdk/src/error.rs b/sdk/src/error.rs
index 60bd86f4..4e8d8081 100644
--- a/sdk/src/error.rs
+++ b/sdk/src/error.rs
@@ -21,7 +21,7 @@ use crate::utils::topic_size::MaxTopicSize;
use strum::{EnumDiscriminants, FromRepr, IntoStaticStr};
use thiserror::Error;
-#[derive(Debug, Error, EnumDiscriminants, IntoStaticStr, FromRepr)]
+#[derive(Clone, Debug, Error, EnumDiscriminants, IntoStaticStr, FromRepr)]
#[repr(u32)]
#[strum(serialize_all = "snake_case")]
#[strum_discriminants(
@@ -315,7 +315,7 @@ pub enum IggyError {
#[error("Cannot read headers payload")]
CannotReadHeadersPayload = 4016,
#[error("Too big headers payload")]
- TooBigHeadersPayload = 4017,
+ TooBigUserHeaders = 4017,
#[error("Invalid header key")]
InvalidHeaderKey = 4018,
#[error("Invalid header value")]
@@ -335,13 +335,27 @@ pub enum IggyError {
#[error("Cannot read message checksum")]
CannotReadMessageChecksum = 4026,
#[error("Invalid message checksum: {0}, expected: {1}, for offset: {2}")]
- InvalidMessageChecksum(u32, u32, u64) = 4027,
+ InvalidMessageChecksum(u64, u64, u64) = 4027,
#[error("Invalid key value length")]
InvalidKeyValueLength = 4028,
#[error("Command length error: {0}")]
CommandLengthError(String) = 4029,
#[error("Incorrect Segments Count size: {0}")]
InvalidSegmentsCount(u32) = 4030,
+ #[error("Non-zero offset: {0} at index: {1}")]
+ NonZeroOffset(u64, u32) = 4031,
+ #[error("Non-zero timestamp: {0} at index: {1}")]
+ NonZeroTimestamp(u64, u32) = 4032,
+ #[error("Missing index: {0}")]
+ MissingIndex(u32) = 4033,
+ #[error("Invalid indexes byte size: {0}B, should be divisible by 16")]
+ InvalidIndexesByteSize(u32) = 4034,
+ #[error("Invalid indexes count: {0}, expected: {1}")]
+ InvalidIndexesCount(u32, u32) = 4035,
+ #[error("Invalid messages byte size: {0}B, expected: {1}B")]
+ InvalidMessagesSize(u32, u32) = 4036,
+ #[error("Too small message: {0}B, expected: {1}B")]
+ TooSmallMessage(u32, u32) = 4037,
#[error("Cannot sed messages due to client disconnection")]
CannotSendMessagesDueToClientDisconnection = 4050,
#[error("Invalid offset: {0}")]
diff --git a/sdk/src/http/messages.rs b/sdk/src/http/messages.rs
index a23cdc61..22fd3ede 100644
--- a/sdk/src/http/messages.rs
+++ b/sdk/src/http/messages.rs
@@ -22,10 +22,9 @@ use crate::error::IggyError;
use crate::http::client::HttpClient;
use crate::http::HttpTransport;
use crate::identifier::Identifier;
-use crate::messages::flush_unsaved_buffer::FlushUnsavedBuffer;
-use crate::messages::poll_messages::{PollMessages, PollingStrategy};
-use crate::messages::send_messages::{Message, Partitioning, SendMessages};
-use crate::models::messages::PolledMessages;
+use crate::messages::{Partitioning, PollingStrategy};
+use crate::models::messaging::IggyMessagesBatch;
+use crate::prelude::{FlushUnsavedBuffer, IggyMessage, PollMessages, PolledMessages, SendMessages};
use async_trait::async_trait;
#[async_trait]
@@ -66,15 +65,16 @@ impl MessageClient for HttpClient {
stream_id: &Identifier,
topic_id: &Identifier,
partitioning: &Partitioning,
- messages: &mut [Message],
+ messages: &mut [IggyMessage],
) -> Result<(), IggyError> {
+ let batch = IggyMessagesBatch::from(&*messages);
self.post(
&get_path(&stream_id.as_cow_str(), &topic_id.as_cow_str()),
&SendMessages {
stream_id: stream_id.clone(),
topic_id: topic_id.clone(),
partitioning: partitioning.clone(),
- messages: messages.to_vec(),
+ batch,
},
)
.await?;
diff --git a/sdk/src/identifier.rs b/sdk/src/identifier.rs
index 5a094474..e66d0059 100644
--- a/sdk/src/identifier.rs
+++ b/sdk/src/identifier.rs
@@ -182,6 +182,24 @@ impl Identifier {
value: value.as_bytes().to_vec(),
})
}
+
+ /// Creates identifier from raw bytes
+ pub fn from_raw_bytes(bytes: &[u8]) -> Result<Self, IggyError> {
+ let kind = IdKind::from_code(bytes[0])?;
+ let length = bytes[1];
+ let value = bytes[2..2 + length as usize].to_vec();
+ if value.len() != length as usize {
+ return Err(IggyError::InvalidIdentifier);
+ }
+
+ let identifier = Identifier {
+ kind,
+ length,
+ value,
+ };
+ identifier.validate()?;
+ Ok(identifier)
+ }
}
impl Sizeable for Identifier {
@@ -222,6 +240,16 @@ impl BytesSerializable for Identifier {
identifier.validate()?;
Ok(identifier)
}
+
+ fn write_to_buffer(&self, bytes: &mut BytesMut) {
+ bytes.put_u8(self.kind.as_code());
+ bytes.put_u8(self.length);
+ bytes.put_slice(&self.value);
+ }
+
+ fn get_buffer_size(&self) -> usize {
+ 2 + self.length as usize
+ }
}
impl IdKind {
diff --git a/sdk/src/lib.rs b/sdk/src/lib.rs
index f5b246d6..21c248ad 100644
--- a/sdk/src/lib.rs
+++ b/sdk/src/lib.rs
@@ -46,6 +46,7 @@ pub mod models;
pub mod partitioner;
pub mod partitions;
pub mod personal_access_tokens;
+pub mod prelude;
pub mod quic;
pub mod segments;
pub mod snapshot;
diff --git a/sdk/src/messages/flush_unsaved_buffer.rs b/sdk/src/messages/flush_unsaved_buffer.rs
index 5d5ff881..81097fb0 100644
--- a/sdk/src/messages/flush_unsaved_buffer.rs
+++ b/sdk/src/messages/flush_unsaved_buffer.rs
@@ -16,11 +16,6 @@
* under the License.
*/
-use std::fmt::Display;
-
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-
use crate::{
bytes_serializable::BytesSerializable,
command::{Command, FLUSH_UNSAVED_BUFFER_CODE},
@@ -28,6 +23,9 @@ use crate::{
identifier::Identifier,
validatable::Validatable,
};
+use bytes::{BufMut, Bytes, BytesMut};
+use serde::{Deserialize, Serialize};
+use std::fmt::Display;
/// `FlushUnsavedBuffer` command is used to force a flush of `unsaved_buffer` to disk for specific stream -> topic -> partition.
/// - `stream_id` - stream identifier
diff --git a/sdk/src/messages/mod.rs b/sdk/src/messages/mod.rs
index 556f9e90..daa001d1 100644
--- a/sdk/src/messages/mod.rs
+++ b/sdk/src/messages/mod.rs
@@ -16,9 +16,23 @@
* under the License.
*/
-pub mod flush_unsaved_buffer;
-pub mod poll_messages;
-pub mod send_messages;
+mod flush_unsaved_buffer;
+mod partitioning;
+mod partitioning_kind;
+mod poll_messages;
+mod polled_messages;
+mod polling_kind;
+mod polling_strategy;
+mod send_messages;
-const MAX_HEADERS_SIZE: u32 = 100 * 1000;
+pub const MAX_USER_HEADERS_SIZE: u32 = 100 * 1000;
pub const MAX_PAYLOAD_SIZE: u32 = 10 * 1000 * 1000;
+
+pub use flush_unsaved_buffer::FlushUnsavedBuffer;
+pub use partitioning::Partitioning;
+pub use partitioning_kind::PartitioningKind;
+pub use poll_messages::PollMessages;
+pub use polled_messages::PolledMessages;
+pub use polling_kind::PollingKind;
+pub use polling_strategy::PollingStrategy;
+pub use send_messages::SendMessages;
diff --git a/sdk/src/messages/partitioning.rs b/sdk/src/messages/partitioning.rs
new file mode 100644
index 00000000..8e454b38
--- /dev/null
+++ b/sdk/src/messages/partitioning.rs
@@ -0,0 +1,220 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+use super::PartitioningKind;
+use crate::{
+ error::IggyError,
+ prelude::{BytesSerializable, IggyByteSize, Sizeable},
+};
+use bytes::{BufMut, Bytes, BytesMut};
+use serde::{Deserialize, Serialize};
+use serde_with::base64::Base64;
+use serde_with::serde_as;
+use std::{
+ fmt::Display,
+ hash::{Hash, Hasher},
+};
+
+/// `Partitioning` is used to specify to which partition the messages should be sent.
+/// It has the following kinds:
+/// - `Balanced` - the partition ID is calculated by the server using the round-robin algorithm.
+/// - `PartitionId` - the partition ID is provided by the client.
+/// - `MessagesKey` - the partition ID is calculated by the server using the hash of the provided messages key.
+#[serde_as]
+#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
+pub struct Partitioning {
+ /// The kind of partitioning.
+ pub kind: PartitioningKind,
+ #[serde(skip)]
+ /// The length of the value payload.
+ pub length: u8,
+ #[serde_as(as = "Base64")]
+ /// The binary value payload.
+ pub value: Vec<u8>,
+}
+
+impl Display for Partitioning {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self.kind {
+ PartitioningKind::Balanced => write!(f, "{}|0", self.kind),
+ PartitioningKind::PartitionId => write!(
+ f,
+ "{}|{}",
+ self.kind,
+ u32::from_le_bytes(self.value[..4].try_into().unwrap())
+ ),
+ PartitioningKind::MessagesKey => {
+ write!(f, "{}|{}", self.kind, String::from_utf8_lossy(&self.value))
+ }
+ }
+ }
+}
+
+impl Partitioning {
+ /// Partition the messages using the balanced round-robin algorithm on the server.
+ pub fn balanced() -> Self {
+ Partitioning {
+ kind: PartitioningKind::Balanced,
+ length: 0,
+ value: vec![],
+ }
+ }
+
+ /// Partition the messages using the provided partition ID.
+ pub fn partition_id(partition_id: u32) -> Self {
+ Partitioning {
+ kind: PartitioningKind::PartitionId,
+ length: 4,
+ value: partition_id.to_le_bytes().to_vec(),
+ }
+ }
+
+ /// Partition the messages using the provided messages key.
+ pub fn messages_key(value: &[u8]) -> Result<Self, IggyError> {
+ let length = value.len();
+ if length == 0 || length > 255 {
+ return Err(IggyError::InvalidCommand);
+ }
+
+ Ok(Partitioning {
+ kind: PartitioningKind::MessagesKey,
+ #[allow(clippy::cast_possible_truncation)]
+ length: length as u8,
+ value: value.to_vec(),
+ })
+ }
+
+ /// Partition the messages using the provided messages key as str.
+ pub fn messages_key_str(value: &str) -> Result<Self, IggyError> {
+ Self::messages_key(value.as_bytes())
+ }
+
+ /// Partition the messages using the provided messages key as u32.
+ pub fn messages_key_u32(value: u32) -> Self {
+ Partitioning {
+ kind: PartitioningKind::MessagesKey,
+ length: 4,
+ value: value.to_le_bytes().to_vec(),
+ }
+ }
+
+ /// Partition the messages using the provided messages key as u64.
+ pub fn messages_key_u64(value: u64) -> Self {
+ Partitioning {
+ kind: PartitioningKind::MessagesKey,
+ length: 8,
+ value: value.to_le_bytes().to_vec(),
+ }
+ }
+
+ /// Partition the messages using the provided messages key as u128.
+ pub fn messages_key_u128(value: u128) -> Self {
+ Partitioning {
+ kind: PartitioningKind::MessagesKey,
+ length: 16,
+ value: value.to_le_bytes().to_vec(),
+ }
+ }
+
+ /// Create the partitioning from the provided partitioning.
+ pub fn from_partitioning(partitioning: &Partitioning) -> Self {
+ Partitioning {
+ kind: partitioning.kind,
+ length: partitioning.length,
+ value: partitioning.value.clone(),
+ }
+ }
+
+ /// Create the partitioning from BytesMut.
+ pub fn from_raw_bytes(bytes: &[u8]) -> Result<Self, IggyError> {
+ let kind = PartitioningKind::from_code(bytes[0])?;
+ let length = bytes[1];
+ let value = bytes[2..2 + length as usize].to_vec();
+ if value.len() != length as usize {
+ return Err(IggyError::InvalidCommand);
+ }
+
+ Ok(Partitioning {
+ kind,
+ length,
+ value,
+ })
+ }
+}
+
+impl Hash for Partitioning {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.kind.hash(state);
+ self.length.hash(state);
+ self.value.hash(state);
+ }
+}
+
+impl Default for Partitioning {
+ fn default() -> Self {
+ Partitioning::balanced()
+ }
+}
+
+impl Sizeable for Partitioning {
+ fn get_size_bytes(&self) -> IggyByteSize {
+ IggyByteSize::from(u64::from(self.length) + 2)
+ }
+}
+
+impl BytesSerializable for Partitioning {
+ fn to_bytes(&self) -> Bytes {
+ let mut bytes = BytesMut::with_capacity(2 + self.length as usize);
+ bytes.put_u8(self.kind.as_code());
+ bytes.put_u8(self.length);
+ bytes.put_slice(&self.value);
+ bytes.freeze()
+ }
+
+ fn from_bytes(bytes: Bytes) -> Result<Self, IggyError>
+ where
+ Self: Sized,
+ {
+ if bytes.len() < 2 {
+ return Err(IggyError::InvalidCommand);
+ }
+
+ let kind = PartitioningKind::from_code(bytes[0])?;
+ let length = bytes[1];
+ let value = bytes[2..2 + length as usize].to_vec();
+ if value.len() != length as usize {
+ return Err(IggyError::InvalidCommand);
+ }
+
+ Ok(Partitioning {
+ kind,
+ length,
+ value,
+ })
+ }
+
+ fn write_to_buffer(&self, bytes: &mut BytesMut) {
+ bytes.put_u8(self.kind.as_code());
+ bytes.put_u8(self.length);
+ bytes.put_slice(&self.value);
+ }
+
+ fn get_buffer_size(&self) -> usize {
+ 2 + self.length as usize
+ }
+}
diff --git a/sdk/src/messages/partitioning_kind.rs b/sdk/src/messages/partitioning_kind.rs
new file mode 100644
index 00000000..2df5398f
--- /dev/null
+++ b/sdk/src/messages/partitioning_kind.rs
@@ -0,0 +1,74 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
+use std::{
+ fmt::Display,
+ hash::{Hash, Hasher},
+};
+
+/// `PartitioningKind` is an enum which specifies the kind of partitioning and is used by `Partitioning`.
+#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Default, Copy, Clone)]
+#[serde(rename_all = "snake_case")]
+pub enum PartitioningKind {
+ /// The partition ID is calculated by the server using the round-robin algorithm.
+ #[default]
+ Balanced,
+ /// The partition ID is provided by the client.
+ PartitionId,
+ /// The partition ID is calculated by the server using the hash of the provided messages key.
+ MessagesKey,
+}
+
+impl Hash for PartitioningKind {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.as_code().hash(state);
+ }
+}
+
+impl PartitioningKind {
+ /// Get the code of the partitioning kind.
+ pub fn as_code(&self) -> u8 {
+ match self {
+ PartitioningKind::Balanced => 1,
+ PartitioningKind::PartitionId => 2,
+ PartitioningKind::MessagesKey => 3,
+ }
+ }
+
+ /// Get the partitioning kind from the provided code.
+ pub fn from_code(code: u8) -> Result<Self, IggyError> {
+ match code {
+ 1 => Ok(PartitioningKind::Balanced),
+ 2 => Ok(PartitioningKind::PartitionId),
+ 3 => Ok(PartitioningKind::MessagesKey),
+ _ => Err(IggyError::InvalidCommand),
+ }
+ }
+}
+
+impl Display for PartitioningKind {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ PartitioningKind::Balanced => write!(f, "balanced"),
+ PartitioningKind::PartitionId => write!(f, "partition_id"),
+ PartitioningKind::MessagesKey => write!(f, "messages_key"),
+ }
+ }
+}
diff --git a/sdk/src/messages/poll_messages.rs b/sdk/src/messages/poll_messages.rs
index 697348a8..09e14a56 100644
--- a/sdk/src/messages/poll_messages.rs
+++ b/sdk/src/messages/poll_messages.rs
@@ -16,19 +16,20 @@
* under the License.
*/
+use super::{PollingKind, PollingStrategy};
use crate::bytes_serializable::BytesSerializable;
use crate::command::{Command, POLL_MESSAGES_CODE};
use crate::consumer::{Consumer, ConsumerKind};
use crate::error::IggyError;
use crate::identifier::Identifier;
use crate::utils::sizeable::Sizeable;
-use crate::utils::timestamp::IggyTimestamp;
use crate::validatable::Validatable;
use bytes::{BufMut, Bytes, BytesMut};
use serde::{Deserialize, Serialize};
-use serde_with::{serde_as, DisplayFromStr};
use std::fmt::Display;
-use std::str::FromStr;
+
+pub const DEFAULT_PARTITION_ID: u32 = 1;
+pub const DEFAULT_NUMBER_OF_MESSAGES_TO_POLL: u32 = 10;
/// `PollMessages` command is used to poll messages from a topic in a stream.
/// It has additional payload:
@@ -51,54 +52,65 @@ pub struct PollMessages {
#[serde(skip)]
pub topic_id: Identifier,
/// Partition ID from which messages will be polled. Has to be specified for the regular consumer. For consumer group it is ignored (use `None`).
- #[serde(default = "default_partition_id")]
+ #[serde(default = "PollMessages::default_partition_id")]
pub partition_id: Option<u32>,
/// Polling strategy which specifies from where to start polling messages.
- #[serde(default = "default_strategy", flatten)]
+ #[serde(default = "PollingStrategy::default", flatten)]
pub strategy: PollingStrategy,
- #[serde(default = "default_count")]
/// Number of messages to poll.
+ #[serde(default = "PollMessages::default_number_of_messages_to_poll")]
pub count: u32,
- #[serde(default)]
/// Whether to commit offset on the server automatically after polling the messages.
+ #[serde(default)]
pub auto_commit: bool,
}
-/// `PollingStrategy` specifies from where to start polling messages.
-/// It has the following kinds:
-/// - `Offset` - start polling from the specified offset.
-/// - `Timestamp` - start polling from the specified timestamp.
-/// - `First` - start polling from the first message in the partition.
-/// - `Last` - start polling from the last message in the partition.
-/// - `Next` - start polling from the next message after the last polled message based on the stored consumer offset.
-#[serde_as]
-#[derive(Debug, Serialize, Deserialize, PartialEq, Copy, Clone)]
-pub struct PollingStrategy {
- /// Kind of the polling strategy.
- #[serde_as(as = "DisplayFromStr")]
- #[serde(default = "default_kind")]
- pub kind: PollingKind,
- /// Value of the polling strategy.
- #[serde_as(as = "DisplayFromStr")]
- #[serde(default = "default_value")]
- pub value: u64,
-}
+impl PollMessages {
+ pub(crate) fn as_bytes(
+ stream_id: &Identifier,
+ topic_id: &Identifier,
+ partition_id: Option<u32>,
+ consumer: &Consumer,
+ strategy: &PollingStrategy,
+ count: u32,
+ auto_commit: bool,
+ ) -> Bytes {
+ let consumer_bytes = consumer.to_bytes();
+ let stream_id_bytes = stream_id.to_bytes();
+ let topic_id_bytes = topic_id.to_bytes();
+ let strategy_bytes = strategy.to_bytes();
+ let mut bytes = BytesMut::with_capacity(
+ 9 + consumer_bytes.len()
+ + stream_id_bytes.len()
+ + topic_id_bytes.len()
+ + strategy_bytes.len(),
+ );
+ bytes.put_slice(&consumer_bytes);
+ bytes.put_slice(&stream_id_bytes);
+ bytes.put_slice(&topic_id_bytes);
+ if let Some(partition_id) = partition_id {
+ bytes.put_u32_le(partition_id);
+ } else {
+ bytes.put_u32_le(0);
+ }
+ bytes.put_slice(&strategy_bytes);
+ bytes.put_u32_le(count);
+ if auto_commit {
+ bytes.put_u8(1);
+ } else {
+ bytes.put_u8(0);
+ }
-/// `PollingKind` is an enum which specifies from where to start polling messages and is used by `PollingStrategy`.
-#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Copy, Clone)]
-#[serde(rename_all = "snake_case")]
-pub enum PollingKind {
- #[default]
- /// Start polling from the specified offset.
- Offset,
- /// Start polling from the specified timestamp.
- Timestamp,
- /// Start polling from the first message in the partition.
- First,
- /// Start polling from the last message in the partition.
- Last,
- /// Start polling from the next message after the last polled message based on the stored consumer offset. Should be used with `auto_commit` set to `true`.
- Next,
+ bytes.freeze()
+ }
+
+ pub fn default_number_of_messages_to_poll() -> u32 {
+ DEFAULT_NUMBER_OF_MESSAGES_TO_POLL
+ }
+
+ pub fn default_partition_id() -> Option<u32> {
+ Some(DEFAULT_PARTITION_ID)
+ }
}
impl Default for PollMessages {
@@ -107,158 +119,29 @@ impl Default for PollMessages {
consumer: Consumer::default(),
stream_id: Identifier::numeric(1).unwrap(),
topic_id: Identifier::numeric(1).unwrap(),
- partition_id: default_partition_id(),
- strategy: default_strategy(),
- count: default_count(),
+ partition_id: PollMessages::default_partition_id(),
+ strategy: PollingStrategy::default(),
+ count: PollMessages::default_number_of_messages_to_poll(),
auto_commit: false,
}
}
}
-impl Default for PollingStrategy {
- fn default() -> Self {
- Self {
- kind: PollingKind::Offset,
- value: 0,
- }
- }
-}
-
impl Command for PollMessages {
fn code(&self) -> u32 {
POLL_MESSAGES_CODE
}
}
-fn default_partition_id() -> Option<u32> {
- Some(1)
-}
-
-fn default_kind() -> PollingKind {
- PollingKind::Offset
-}
-
-fn default_value() -> u64 {
- 0
-}
-
-fn default_strategy() -> PollingStrategy {
- PollingStrategy::default()
-}
-
-fn default_count() -> u32 {
- 10
-}
-
impl Validatable<IggyError> for PollMessages {
fn validate(&self) -> Result<(), IggyError> {
Ok(())
}
}
-impl PollingStrategy {
- /// Poll messages from the specified offset.
- pub fn offset(value: u64) -> Self {
- Self {
- kind: PollingKind::Offset,
- value,
- }
- }
-
- /// Poll messages from the specified timestamp.
- pub fn timestamp(value: IggyTimestamp) -> Self {
- Self {
- kind: PollingKind::Timestamp,
- value: value.into(),
- }
- }
-
- /// Poll messages from the first message in the partition.
- pub fn first() -> Self {
- Self {
- kind: PollingKind::First,
- value: 0,
- }
- }
-
- /// Poll messages from the last message in the partition.
- pub fn last() -> Self {
- Self {
- kind: PollingKind::Last,
- value: 0,
- }
- }
-
- /// Poll messages from the next message after the last polled message based on the stored consumer offset. Should be used with `auto_commit` set to `true`.
- pub fn next() -> Self {
- Self {
- kind: PollingKind::Next,
- value: 0,
- }
- }
-
- /// Change the value of the polling strategy, affects only `Offset` and `Timestamp` kinds.
- pub fn set_value(&mut self, value: u64) {
- if self.kind == PollingKind::Offset || self.kind == PollingKind::Timestamp {
- self.value = value;
- }
- }
-}
-
-impl PollingKind {
- /// Returns code of the polling kind.
- pub fn as_code(&self) -> u8 {
- match self {
- PollingKind::Offset => 1,
- PollingKind::Timestamp => 2,
- PollingKind::First => 3,
- PollingKind::Last => 4,
- PollingKind::Next => 5,
- }
- }
-
- /// Returns polling kind from the specified code.
- pub fn from_code(code: u8) -> Result<Self, IggyError> {
- match code {
- 1 => Ok(PollingKind::Offset),
- 2 => Ok(PollingKind::Timestamp),
- 3 => Ok(PollingKind::First),
- 4 => Ok(PollingKind::Last),
- 5 => Ok(PollingKind::Next),
- _ => Err(IggyError::InvalidCommand),
- }
- }
-}
-
-impl FromStr for PollingKind {
- type Err = IggyError;
- fn from_str(input: &str) -> Result<Self, Self::Err> {
- match input {
- "o" | "offset" => Ok(PollingKind::Offset),
- "t" | "timestamp" => Ok(PollingKind::Timestamp),
- "f" | "first" => Ok(PollingKind::First),
- "l" | "last" => Ok(PollingKind::Last),
- "n" | "next" => Ok(PollingKind::Next),
- _ => Err(IggyError::InvalidCommand),
- }
- }
-}
-
-impl Display for PollingKind {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- PollingKind::Offset => write!(f, "offset"),
- PollingKind::Timestamp => write!(f, "timestamp"),
- PollingKind::First => write!(f, "first"),
- PollingKind::Last => write!(f, "last"),
- PollingKind::Next => write!(f, "next"),
- }
- }
-}
-
impl BytesSerializable for PollMessages {
fn to_bytes(&self) -> Bytes {
- as_bytes(
+ PollMessages::as_bytes(
&self.stream_id,
&self.topic_id,
self.partition_id,
@@ -326,45 +209,6 @@ impl BytesSerializable for PollMessages {
}
}
-// This method is used by the new version of `IggyClient` to serialize `PollMessages` without cloning the args.
-pub(crate) fn as_bytes(
- stream_id: &Identifier,
- topic_id: &Identifier,
- partition_id: Option<u32>,
- consumer: &Consumer,
- strategy: &PollingStrategy,
- count: u32,
- auto_commit: bool,
-) -> Bytes {
- let consumer_bytes = consumer.to_bytes();
- let stream_id_bytes = stream_id.to_bytes();
- let topic_id_bytes = topic_id.to_bytes();
- let strategy_bytes = strategy.to_bytes();
- let mut bytes = BytesMut::with_capacity(
- 9 + consumer_bytes.len()
- + stream_id_bytes.len()
- + topic_id_bytes.len()
- + strategy_bytes.len(),
- );
- bytes.put_slice(&consumer_bytes);
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- if let Some(partition_id) = partition_id {
- bytes.put_u32_le(partition_id);
- } else {
- bytes.put_u32_le(0);
- }
- bytes.put_slice(&strategy_bytes);
- bytes.put_u32_le(count);
- if auto_commit {
- bytes.put_u8(1);
- } else {
- bytes.put_u8(0);
- }
-
- bytes.freeze()
-}
-
impl Display for PollMessages {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
@@ -381,12 +225,6 @@ impl Display for PollMessages {
}
}
-impl Display for PollingStrategy {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}|{}", self.kind, self.value)
- }
-}
-
fn auto_commit_to_string(auto_commit: bool) -> &'static str {
if auto_commit {
"a"
@@ -395,30 +233,6 @@ fn auto_commit_to_string(auto_commit: bool) -> &'static str {
}
}
-impl BytesSerializable for PollingStrategy {
- fn to_bytes(&self) -> Bytes {
- let mut bytes = BytesMut::with_capacity(9);
- bytes.put_u8(self.kind.as_code());
- bytes.put_u64_le(self.value);
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<Self, IggyError> {
- if bytes.len() != 9 {
- return Err(IggyError::InvalidCommand);
- }
-
- let kind = PollingKind::from_code(bytes[0])?;
- let value = u64::from_le_bytes(
- bytes[1..9]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let strategy = PollingStrategy { kind, value };
- Ok(strategy)
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/sdk/src/messages/polled_messages.rs b/sdk/src/messages/polled_messages.rs
new file mode 100644
index 00000000..f8d246c3
--- /dev/null
+++ b/sdk/src/messages/polled_messages.rs
@@ -0,0 +1,129 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+use crate::{
+ error::IggyError,
+ prelude::{BytesSerializable, IggyMessage, IggyMessageHeader, IGGY_MESSAGE_HEADER_SIZE},
+};
+use bytes::Bytes;
+use serde::{Deserialize, Serialize};
+use tracing::error;
+
+/// The wrapper on top of the collection of messages that are polled from the partition.
+/// It consists of the following fields:
+/// - `partition_id`: the identifier of the partition.
+/// - `current_offset`: the current offset of the partition.
+/// - `messages`: the collection of messages.
+#[derive(Debug, Serialize, Deserialize)]
+pub struct PolledMessages {
+ /// The identifier of the partition. If it's '0', then there's no partition assigned to the consumer group member.
+ pub partition_id: u32,
+ /// The current offset of the partition.
+ pub current_offset: u64,
+ /// The count of messages.
+ pub count: u32,
+ /// The collection of messages.
+ pub messages: Vec<IggyMessage>,
+}
+
+impl PolledMessages {
+ pub fn empty() -> Self {
+ Self {
+ partition_id: 0,
+ current_offset: 0,
+ count: 0,
+ messages: Vec::new(),
+ }
+ }
+}
+
+impl BytesSerializable for PolledMessages {
+ fn to_bytes(&self) -> Bytes {
+ panic!("should not be used")
+ }
+
+ fn from_bytes(bytes: Bytes) -> Result<Self, IggyError> {
+ let partition_id = u32::from_le_bytes(
+ bytes[0..4]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+ let current_offset = u64::from_le_bytes(
+ bytes[4..12]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+ let count = u32::from_le_bytes(
+ bytes[12..16]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ let messages = messages_from_bytes_and_count(bytes.slice(16..), count)?;
+
+ Ok(Self {
+ partition_id,
+ current_offset,
+ count,
+ messages,
+ })
+ }
+}
+
+/// Convert Bytes to messages
+fn messages_from_bytes_and_count(buffer: Bytes, count: u32) -> Result<Vec<IggyMessage>, IggyError> {
+ let mut messages = Vec::with_capacity(count as usize);
+ let mut position = 0;
+ let buf_len = buffer.len();
+ while position < buf_len {
+ if position + IGGY_MESSAGE_HEADER_SIZE > buf_len {
+ break;
+ }
+ let header_bytes = buffer.slice(position..position + IGGY_MESSAGE_HEADER_SIZE);
+ let header = match IggyMessageHeader::from_bytes(header_bytes) {
+ Ok(h) => h,
+ Err(e) => {
+ error!("Failed to deserialize message header: {}", e);
+ return Err(e);
+ }
+ };
+ position += IGGY_MESSAGE_HEADER_SIZE;
+
+ let payload_end = position + header.payload_length as usize;
+ if payload_end > buf_len {
+ break;
+ }
+ let payload = buffer.slice(position..payload_end);
+ position = payload_end;
+
+ let headers: Option<Bytes> = if header.user_headers_length > 0 {
+ Some(buffer.slice(position..position + header.user_headers_length as usize))
+ } else {
+ None
+ };
+ position += header.user_headers_length as usize;
+
+ messages.push(IggyMessage {
+ header,
+ payload,
+ user_headers: headers,
+ });
+ }
+
+ Ok(messages)
+}
diff --git a/sdk/src/messages/polling_kind.rs b/sdk/src/messages/polling_kind.rs
new file mode 100644
index 00000000..cc406bda
--- /dev/null
+++ b/sdk/src/messages/polling_kind.rs
@@ -0,0 +1,90 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
+use std::fmt::Display;
+use std::str::FromStr;
+
+/// `PollingKind` is an enum which specifies from where to start polling messages and is used by `PollingStrategy`.
+#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Copy, Clone)]
+#[serde(rename_all = "snake_case")]
+pub enum PollingKind {
+ #[default]
+ /// Start polling from the specified offset.
+ Offset,
+ /// Start polling from the specified timestamp.
+ Timestamp,
+ /// Start polling from the first message in the partition.
+ First,
+ /// Start polling from the last message in the partition.
+ Last,
+ /// Start polling from the next message after the last polled message based on the stored consumer offset. Should be used with `auto_commit` set to `true`.
+ Next,
+}
+
+impl PollingKind {
+ /// Returns code of the polling kind.
+ pub fn as_code(&self) -> u8 {
+ match self {
+ PollingKind::Offset => 1,
+ PollingKind::Timestamp => 2,
+ PollingKind::First => 3,
+ PollingKind::Last => 4,
+ PollingKind::Next => 5,
+ }
+ }
+
+ /// Returns polling kind from the specified code.
+ pub fn from_code(code: u8) -> Result<Self, IggyError> {
+ match code {
+ 1 => Ok(PollingKind::Offset),
+ 2 => Ok(PollingKind::Timestamp),
+ 3 => Ok(PollingKind::First),
+ 4 => Ok(PollingKind::Last),
+ 5 => Ok(PollingKind::Next),
+ _ => Err(IggyError::InvalidCommand),
+ }
+ }
+}
+
+impl FromStr for PollingKind {
+ type Err = IggyError;
+ fn from_str(input: &str) -> Result<Self, Self::Err> {
+ match input {
+ "o" | "offset" => Ok(PollingKind::Offset),
+ "t" | "timestamp" => Ok(PollingKind::Timestamp),
+ "f" | "first" => Ok(PollingKind::First),
+ "l" | "last" => Ok(PollingKind::Last),
+ "n" | "next" => Ok(PollingKind::Next),
+ _ => Err(IggyError::InvalidCommand),
+ }
+ }
+}
+
+impl Display for PollingKind {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ PollingKind::Offset => write!(f, "offset"),
+ PollingKind::Timestamp => write!(f, "timestamp"),
+ PollingKind::First => write!(f, "first"),
+ PollingKind::Last => write!(f, "last"),
+ PollingKind::Next => write!(f, "next"),
+ }
+ }
+}
diff --git a/sdk/src/messages/polling_strategy.rs b/sdk/src/messages/polling_strategy.rs
new file mode 100644
index 00000000..6ffe8279
--- /dev/null
+++ b/sdk/src/messages/polling_strategy.rs
@@ -0,0 +1,147 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+use super::polling_kind::PollingKind;
+use crate::bytes_serializable::BytesSerializable;
+use crate::error::IggyError;
+use crate::utils::timestamp::IggyTimestamp;
+use bytes::{BufMut, Bytes, BytesMut};
+use serde::{Deserialize, Serialize};
+use serde_with::{serde_as, DisplayFromStr};
+use std::fmt::Display;
+
+/// Default value for the polling strategy.
+const DEFAULT_POLLING_STRATEGY_VALUE: u64 = 0;
+
+/// `PollingStrategy` specifies from where to start polling messages.
+/// It has the following kinds:
+/// - `Offset` - start polling from the specified offset.
+/// - `Timestamp` - start polling from the specified timestamp.
+/// - `First` - start polling from the first message in the partition.
+/// - `Last` - start polling from the last message in the partition.
+/// - `Next` - start polling from the next message after the last polled message based on the stored consumer offset.
+#[serde_as]
+#[derive(Debug, Serialize, Deserialize, PartialEq, Copy, Clone)]
+pub struct PollingStrategy {
+ /// Kind of the polling strategy.
+ #[serde_as(as = "DisplayFromStr")]
+ #[serde(default = "PollingStrategy::default_kind")]
+ pub kind: PollingKind,
+ /// Value of the polling strategy.
+ #[serde_as(as = "DisplayFromStr")]
+ #[serde(default = "PollingStrategy::default_value")]
+ pub value: u64,
+}
+
+impl Default for PollingStrategy {
+ fn default() -> Self {
+ Self {
+ kind: PollingKind::Offset,
+ value: 0,
+ }
+ }
+}
+
+impl Display for PollingStrategy {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}|{}", self.kind, self.value)
+ }
+}
+
+impl PollingStrategy {
+ /// Poll messages from the specified offset.
+ pub fn offset(value: u64) -> Self {
+ Self {
+ kind: PollingKind::Offset,
+ value,
+ }
+ }
+
+ /// Poll messages from the specified timestamp.
+ pub fn timestamp(value: IggyTimestamp) -> Self {
+ Self {
+ kind: PollingKind::Timestamp,
+ value: value.into(),
+ }
+ }
+
+ /// Poll messages from the first message in the partition.
+ pub fn first() -> Self {
+ Self {
+ kind: PollingKind::First,
+ value: 0,
+ }
+ }
+
+ /// Poll messages from the last message in the partition.
+ pub fn last() -> Self {
+ Self {
+ kind: PollingKind::Last,
+ value: 0,
+ }
+ }
+
+ /// Poll messages from the next message after the last polled message based on the stored consumer offset. Should be used with `auto_commit` set to `true`.
+ pub fn next() -> Self {
+ Self {
+ kind: PollingKind::Next,
+ value: 0,
+ }
+ }
+
+ /// Change the value of the polling strategy, affects only `Offset` and `Timestamp` kinds.
+ pub fn set_value(&mut self, value: u64) {
+ if self.kind == PollingKind::Offset || self.kind == PollingKind::Timestamp {
+ self.value = value;
+ }
+ }
+
+ /// Returns default value of the polling strategy.
+ pub fn default_value() -> u64 {
+ DEFAULT_POLLING_STRATEGY_VALUE
+ }
+
+ /// Returns default kind of the polling strategy.
+ pub fn default_kind() -> PollingKind {
+ PollingKind::default()
+ }
+}
+
+impl BytesSerializable for PollingStrategy {
+ fn to_bytes(&self) -> Bytes {
+ let mut bytes = BytesMut::with_capacity(9);
+ bytes.put_u8(self.kind.as_code());
+ bytes.put_u64_le(self.value);
+ bytes.freeze()
+ }
+
+ fn from_bytes(bytes: Bytes) -> Result<Self, IggyError> {
+ if bytes.len() != 9 {
+ return Err(IggyError::InvalidCommand);
+ }
+
+ let kind = PollingKind::from_code(bytes[0])?;
+ let value = u64::from_le_bytes(
+ bytes[1..9]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+ let strategy = PollingStrategy { kind, value };
+ Ok(strategy)
+ }
+}
diff --git a/sdk/src/messages/send_messages.rs b/sdk/src/messages/send_messages.rs
index 2f7880d8..22a219b9 100644
--- a/sdk/src/messages/send_messages.rs
+++ b/sdk/src/messages/send_messages.rs
@@ -20,112 +20,102 @@ use crate::bytes_serializable::BytesSerializable;
use crate::command::{Command, SEND_MESSAGES_CODE};
use crate::error::IggyError;
use crate::identifier::Identifier;
-use crate::messages::{MAX_HEADERS_SIZE, MAX_PAYLOAD_SIZE};
-use crate::models::header;
-use crate::models::header::{HeaderKey, HeaderValue};
-use crate::utils::byte_size::IggyByteSize;
+use crate::models::messaging::{IggyMessage, IggyMessagesBatch, INDEX_SIZE};
+use crate::prelude::IggyMessageView;
use crate::utils::sizeable::Sizeable;
use crate::validatable::Validatable;
+use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use serde_with::base64::Base64;
-use serde_with::serde_as;
+use serde::de::{self, MapAccess, Visitor};
+use serde::ser::SerializeStruct;
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
+use serde_json;
use std::collections::HashMap;
-use std::fmt::Display;
-use std::hash::{Hash, Hasher};
-use std::str::FromStr;
-use uuid::Uuid;
+use std::fmt::{Display, Formatter};
-const EMPTY_KEY_VALUE: Vec<u8> = vec![];
+use super::{Partitioning, PartitioningKind};
/// `SendMessages` command is used to send messages to a topic in a stream.
/// It has additional payload:
/// - `stream_id` - unique stream ID (numeric or name).
/// - `topic_id` - unique topic ID (numeric or name).
/// - `partitioning` - to which partition the messages should be sent - either provided by the client or calculated by the server.
-/// - `messages` - collection of messages to be sent.
-#[derive(Debug, Serialize, Deserialize, PartialEq)]
+/// - `batch` - collection of messages to be sent.
+#[derive(Debug, PartialEq)]
pub struct SendMessages {
/// Unique stream ID (numeric or name).
- #[serde(skip)]
pub stream_id: Identifier,
/// Unique topic ID (numeric or name).
- #[serde(skip)]
pub topic_id: Identifier,
/// To which partition the messages should be sent - either provided by the client or calculated by the server.
pub partitioning: Partitioning,
- /// Collection of messages to be sent.
- pub messages: Vec<Message>,
+ /// Messages collection
+ pub batch: IggyMessagesBatch,
}
-/// `Partitioning` is used to specify to which partition the messages should be sent.
-/// It has the following kinds:
-/// - `Balanced` - the partition ID is calculated by the server using the round-robin algorithm.
-/// - `PartitionId` - the partition ID is provided by the client.
-/// - `MessagesKey` - the partition ID is calculated by the server using the hash of the provided messages key.
-#[serde_as]
-#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
-pub struct Partitioning {
- /// The kind of partitioning.
- pub kind: PartitioningKind,
- #[serde(skip)]
- /// The length of the value payload.
- pub length: u8,
- #[serde_as(as = "Base64")]
- /// The binary value payload.
- pub value: Vec<u8>,
-}
+impl SendMessages {
+ pub fn as_bytes(
+ stream_id: &Identifier,
+ topic_id: &Identifier,
+ partitioning: &Partitioning,
+ messages: &[IggyMessage],
+ ) -> Bytes {
+ let stream_id_size = stream_id.get_buffer_size();
+ let topic_id_size = topic_id.get_buffer_size();
+ let partitioning_size = partitioning.get_buffer_size();
+ let messages_count = messages.len();
+ let messages_count_size = std::mem::size_of::<u32>();
+ let indexes_size = messages_count * INDEX_SIZE;
+
+ let total_size = stream_id_size
+ + topic_id_size
+ + partitioning_size
+ + messages_count_size
+ + indexes_size
+ + messages
+ .iter()
+ .map(|m| m.get_size_bytes().as_bytes_usize())
+ .sum::<usize>();
-impl Hash for Partitioning {
- fn hash<H: Hasher>(&self, state: &mut H) {
- self.kind.hash(state);
- self.length.hash(state);
- self.value.hash(state);
- }
-}
+ let mut bytes = BytesMut::with_capacity(total_size);
-/// The single message to be sent. It has the following payload:
-/// - `id` - unique message ID, if not specified by the client (has value = 0), it will be generated by the server.
-/// - `length` - length of the payload.
-/// - `payload` - binary message payload.
-/// - `headers` - optional collection of headers.
-#[serde_as]
-#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
-pub struct Message {
- /// Unique message ID, if not specified by the client (has value = 0), it will be generated by the server.
- #[serde(default = "default_message_id")]
- pub id: u128,
- #[serde(skip)]
- /// Length of the payload.
- pub length: u32,
- #[serde_as(as = "Base64")]
- /// Binary message payload.
- pub payload: Bytes,
- /// Optional collection of headers.
- pub headers: Option<HashMap<HeaderKey, HeaderValue>>,
-}
+ stream_id.write_to_buffer(&mut bytes);
+ topic_id.write_to_buffer(&mut bytes);
+ partitioning.write_to_buffer(&mut bytes);
+ bytes.put_u32_le(messages_count as u32);
-/// `PartitioningKind` is an enum which specifies the kind of partitioning and is used by `Partitioning`.
-#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Default, Copy, Clone)]
-#[serde(rename_all = "snake_case")]
-pub enum PartitioningKind {
- /// The partition ID is calculated by the server using the round-robin algorithm.
- #[default]
- Balanced,
- /// The partition ID is provided by the client.
- PartitionId,
- /// The partition ID is calculated by the server using the hash of the provided messages key.
- MessagesKey,
-}
+ let mut current_position = bytes.len();
+
+ bytes.put_bytes(0, indexes_size);
+
+ let mut msgs_size: u32 = 0;
+ for message in messages.iter() {
+ message.write_to_buffer(&mut bytes);
+ msgs_size += message.get_size_bytes().as_bytes_u64() as u32;
+ write_value_at(&mut bytes, 0u64.to_le_bytes(), current_position);
+ write_value_at(&mut bytes, msgs_size.to_le_bytes(), current_position + 4);
+ write_value_at(&mut bytes, 0u64.to_le_bytes(), current_position + 8);
+ current_position += INDEX_SIZE;
+ }
+
+ let out = bytes.freeze();
-impl Hash for PartitioningKind {
- fn hash<H: Hasher>(&self, state: &mut H) {
- self.as_code().hash(state);
+ debug_assert_eq!(
+ total_size,
+ out.len(),
+ "Calculated SendMessages command byte size doesn't match actual command size",
+ );
+
+ out
}
}
-fn default_message_id() -> u128 {
- 0
+fn write_value_at<const N: usize>(slice: &mut [u8], value: [u8; N], position: usize) {
+ let slice = &mut slice[position..position + N];
+ let ptr = slice.as_mut_ptr();
+ unsafe {
+ std::ptr::copy_nonoverlapping(value.as_ptr(), ptr, N);
+ }
}
impl Default for SendMessages {
@@ -134,99 +124,11 @@ impl Default for SendMessages {
stream_id: Identifier::default(),
topic_id: Identifier::default(),
partitioning: Partitioning::default(),
- messages: vec![Message::default()],
- }
- }
-}
-
-impl Default for Partitioning {
- fn default() -> Self {
- Partitioning::balanced()
- }
-}
-
-impl Partitioning {
- /// Partition the messages using the balanced round-robin algorithm on the server.
- pub fn balanced() -> Self {
- Partitioning {
- kind: PartitioningKind::Balanced,
- length: 0,
- value: EMPTY_KEY_VALUE,
- }
- }
-
- /// Partition the messages using the provided partition ID.
- pub fn partition_id(partition_id: u32) -> Self {
- Partitioning {
- kind: PartitioningKind::PartitionId,
- length: 4,
- value: partition_id.to_le_bytes().to_vec(),
- }
- }
-
- /// Partition the messages using the provided messages key.
- pub fn messages_key(value: &[u8]) -> Result<Self, IggyError> {
- let length = value.len();
- if length == 0 || length > 255 {
- return Err(IggyError::InvalidCommand);
- }
-
- Ok(Partitioning {
- kind: PartitioningKind::MessagesKey,
- #[allow(clippy::cast_possible_truncation)]
- length: length as u8,
- value: value.to_vec(),
- })
- }
-
- /// Partition the messages using the provided messages key as str.
- pub fn messages_key_str(value: &str) -> Result<Self, IggyError> {
- Self::messages_key(value.as_bytes())
- }
-
- /// Partition the messages using the provided messages key as u32.
- pub fn messages_key_u32(value: u32) -> Self {
- Partitioning {
- kind: PartitioningKind::MessagesKey,
- length: 4,
- value: value.to_le_bytes().to_vec(),
- }
- }
-
- /// Partition the messages using the provided messages key as u64.
- pub fn messages_key_u64(value: u64) -> Self {
- Partitioning {
- kind: PartitioningKind::MessagesKey,
- length: 8,
- value: value.to_le_bytes().to_vec(),
- }
- }
-
- /// Partition the messages using the provided messages key as u128.
- pub fn messages_key_u128(value: u128) -> Self {
- Partitioning {
- kind: PartitioningKind::MessagesKey,
- length: 16,
- value: value.to_le_bytes().to_vec(),
- }
- }
-
- /// Create the partitioning from the provided partitioning.
- pub fn from_partitioning(partitioning: &Partitioning) -> Self {
- Partitioning {
- kind: partitioning.kind,
- length: partitioning.length,
- value: partitioning.value.clone(),
+ batch: IggyMessagesBatch::empty(),
}
}
}
-impl Sizeable for Partitioning {
- fn get_size_bytes(&self) -> IggyByteSize {
- IggyByteSize::from(u64::from(self.length) + 2)
- }
-}
-
impl Command for SendMessages {
fn code(&self) -> u32 {
SEND_MESSAGES_CODE
@@ -235,347 +137,209 @@ impl Command for SendMessages {
impl Validatable<IggyError> for SendMessages {
fn validate(&self) -> Result<(), IggyError> {
- if self.messages.is_empty() {
- return Err(IggyError::InvalidMessagesCount);
- }
-
- let key_value_length = self.partitioning.value.len();
- if key_value_length > 255
- || (self.partitioning.kind != PartitioningKind::Balanced && key_value_length == 0)
+ if self.partitioning.value.len() > 255
+ || (self.partitioning.kind != PartitioningKind::Balanced
+ && self.partitioning.value.is_empty())
{
return Err(IggyError::InvalidKeyValueLength);
}
- let mut headers_size = 0;
- let mut payload_size = 0;
- for message in &self.messages {
- if let Some(headers) = &message.headers {
- for value in headers.values() {
- headers_size += value.value.len() as u32;
- if headers_size > MAX_HEADERS_SIZE {
- return Err(IggyError::TooBigHeadersPayload);
- }
- }
- }
- payload_size += message.payload.len() as u32;
- if payload_size > MAX_PAYLOAD_SIZE {
- return Err(IggyError::TooBigMessagePayload);
- }
- }
-
- if payload_size == 0 {
- return Err(IggyError::EmptyMessagePayload);
- }
+ self.batch.validate()?;
Ok(())
}
}
-impl PartitioningKind {
- /// Get the code of the partitioning kind.
- pub fn as_code(&self) -> u8 {
- match self {
- PartitioningKind::Balanced => 1,
- PartitioningKind::PartitionId => 2,
- PartitioningKind::MessagesKey => 3,
- }
- }
-
- /// Get the partitioning kind from the provided code.
- pub fn from_code(code: u8) -> Result<Self, IggyError> {
- match code {
- 1 => Ok(PartitioningKind::Balanced),
- 2 => Ok(PartitioningKind::PartitionId),
- 3 => Ok(PartitioningKind::MessagesKey),
- _ => Err(IggyError::InvalidCommand),
- }
- }
-}
-
-impl Message {
- /// Create a new message with the optional ID, payload and headers.
- pub fn new(
- id: Option<u128>,
- payload: Bytes,
- headers: Option<HashMap<HeaderKey, HeaderValue>>,
- ) -> Self {
- Message {
- id: id.unwrap_or(0),
- #[allow(clippy::cast_possible_truncation)]
- length: payload.len() as u32,
- payload,
- headers,
- }
- }
-}
-
-impl Sizeable for Message {
- fn get_size_bytes(&self) -> IggyByteSize {
- // ID + Length + Payload + Headers
- header::get_headers_size_bytes(&self.headers) + (16 + 4 + self.payload.len() as u64).into()
+impl BytesSerializable for SendMessages {
+ fn to_bytes(&self) -> Bytes {
+ panic!("should not be used")
}
-}
-impl Default for Message {
- fn default() -> Self {
- let payload = Bytes::from("hello world");
- Message {
- id: 1,
- length: payload.len() as u32,
- payload,
- headers: None,
- }
+ fn from_bytes(_bytes: Bytes) -> Result<SendMessages, IggyError> {
+ panic!("should not be used")
}
}
-impl Display for Message {
+impl Display for SendMessages {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let len = self.payload.len();
-
- if len > 40 {
- write!(
- f,
- "{}|{}...{}",
- self.id,
- String::from_utf8_lossy(&self.payload[..20]),
- String::from_utf8_lossy(&self.payload[len - 20..])
- )
- } else {
- write!(f, "{}|{}", self.id, String::from_utf8_lossy(&self.payload))
- }
+ let messages_count = self.batch.count();
+ let messages_size = self.batch.size();
+ write!(
+ f,
+ "{}|{}|{}|messages_count:{}|messages_size:{}",
+ self.stream_id, self.topic_id, self.partitioning, messages_count, messages_size
+ )
}
}
-impl BytesSerializable for Partitioning {
- fn to_bytes(&self) -> Bytes {
- let mut bytes = BytesMut::with_capacity(2 + self.length as usize);
- bytes.put_u8(self.kind.as_code());
- bytes.put_u8(self.length);
- bytes.put_slice(&self.value);
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<Self, IggyError>
+impl Serialize for SendMessages {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
- Self: Sized,
+ S: Serializer,
{
- if bytes.len() < 3 {
- return Err(IggyError::InvalidCommand);
- }
+ // In HTTP API, we expose:
+ // - partitioning (kind, value)
+ // - messages as an array of {id, payload, headers}
+ // We don't expose stream_id and topic_id via JSON as they're in URL path
- let kind = PartitioningKind::from_code(bytes[0])?;
- let length = bytes[1];
- let value = bytes[2..2 + length as usize].to_vec();
- if value.len() != length as usize {
- return Err(IggyError::InvalidCommand);
- }
+ let messages: Vec<HashMap<&str, serde_json::Value>> = self
+ .batch
+ .iter()
+ .map(|msg_view: IggyMessageView<'_>| {
+ let mut map = HashMap::with_capacity(self.batch.count() as usize);
+ map.insert("id", serde_json::to_value(msg_view.header().id()).unwrap());
- Ok(Partitioning {
- kind,
- length,
- value,
- })
- }
-}
+ let payload_base64 = BASE64.encode(msg_view.payload());
+ map.insert("payload", serde_json::to_value(payload_base64).unwrap());
-impl BytesSerializable for Message {
- fn to_bytes(&self) -> Bytes {
- let mut bytes = BytesMut::with_capacity(self.get_size_bytes().as_bytes_usize());
- bytes.put_u128_le(self.id);
- if let Some(headers) = &self.headers {
- let headers_bytes = headers.to_bytes();
- bytes.put_u32_le(headers_bytes.len() as u32);
- bytes.put_slice(&headers_bytes);
- } else {
- bytes.put_u32_le(0);
- }
- bytes.put_u32_le(self.length);
- bytes.put_slice(&self.payload);
- bytes.freeze()
- }
+ if let Ok(Some(headers)) = msg_view.user_headers_map() {
+ map.insert("headers", serde_json::to_value(&headers).unwrap());
+ }
- fn from_bytes(bytes: Bytes) -> Result<Self, IggyError> {
- if bytes.len() < 24 {
- return Err(IggyError::InvalidCommand);
- }
+ map
+ })
+ .collect();
- let mut id = u128::from_le_bytes(
- bytes[..16]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- if id == 0 {
- id = Uuid::now_v7().to_u128_le();
- }
- let headers_length = u32::from_le_bytes(
- bytes[16..20]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let headers = if headers_length > 0 {
- Some(HashMap::from_bytes(
- bytes.slice(20..20 + headers_length as usize),
- )?)
- } else {
- None
- };
-
- let payload_length = u32::from_le_bytes(
- bytes[20 + headers_length as usize..24 + headers_length as usize]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- if payload_length == 0 {
- return Err(IggyError::EmptyMessagePayload);
- }
+ let mut state = serializer.serialize_struct("SendMessages", 2)?;
+ state.serialize_field("partitioning", &self.partitioning)?;
+ state.serialize_field("messages", &messages)?;
+ state.end()
+ }
+}
- let payload = bytes.slice(
- 24 + headers_length as usize..24 + headers_length as usize + payload_length as usize,
- );
- if payload.len() != payload_length as usize {
- return Err(IggyError::InvalidMessagePayloadLength);
+impl<'de> Deserialize<'de> for SendMessages {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ enum Field {
+ Partitioning,
+ Messages,
}
- Ok(Message {
- id,
- length: payload_length,
- payload,
- headers,
- })
- }
-}
+ impl<'de> Deserialize<'de> for Field {
+ fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ struct FieldVisitor;
-// This method is used by the new version of `IggyClient` to serialize `SendMessages` without copying the messages.
-pub(crate) fn as_bytes(
- stream_id: &Identifier,
- topic_id: &Identifier,
- partitioning: &Partitioning,
- messages: &[Message],
-) -> Bytes {
- let messages_size = messages
- .iter()
- .map(Message::get_size_bytes)
- .sum::<IggyByteSize>();
- let key_bytes = partitioning.to_bytes();
- let stream_id_bytes = stream_id.to_bytes();
- let topic_id_bytes = topic_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(
- stream_id_bytes.len()
- + topic_id_bytes.len()
- + key_bytes.len()
- + messages_size.as_bytes_usize(),
- );
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_slice(&key_bytes);
- for message in messages {
- bytes.put_slice(&message.to_bytes());
- }
+ impl Visitor<'_> for FieldVisitor {
+ type Value = Field;
- bytes.freeze()
-}
+ fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
+ formatter.write_str("`partitioning` or `messages`")
+ }
+
+ fn visit_str<E>(self, value: &str) -> Result<Field, E>
+ where
+ E: de::Error,
+ {
+ match value {
+ "partitioning" => Ok(Field::Partitioning),
+ "messages" => Ok(Field::Messages),
+ _ => Err(de::Error::unknown_field(
+ value,
+ &["partitioning", "messages"],
+ )),
+ }
+ }
+ }
-impl FromStr for Message {
- type Err = IggyError;
- fn from_str(input: &str) -> Result<Self, Self::Err> {
- let id = default_message_id();
- let payload = Bytes::from(input.as_bytes().to_vec());
- let length = payload.len() as u32;
- if length == 0 {
- return Err(IggyError::EmptyMessagePayload);
+ deserializer.deserialize_identifier(FieldVisitor)
+ }
}
- Ok(Message {
- id,
- length,
- payload,
- headers: None,
- })
- }
-}
+ struct SendMessagesVisitor;
-impl BytesSerializable for SendMessages {
- fn to_bytes(&self) -> Bytes {
- as_bytes(
- &self.stream_id,
- &self.topic_id,
- &self.partitioning,
- &self.messages,
- )
- }
+ impl<'de> Visitor<'de> for SendMessagesVisitor {
+ type Value = SendMessages;
- fn from_bytes(bytes: Bytes) -> Result<SendMessages, IggyError> {
- if bytes.len() < 11 {
- return Err(IggyError::InvalidCommand);
- }
+ fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
+ formatter.write_str("struct SendMessages")
+ }
- let mut position = 0;
- let stream_id = Identifier::from_bytes(bytes.clone())?;
- position += stream_id.get_size_bytes().as_bytes_usize();
- let topic_id = Identifier::from_bytes(bytes.slice(position..))?;
- position += topic_id.get_size_bytes().as_bytes_usize();
- let key = Partitioning::from_bytes(bytes.slice(position..))?;
- position += key.get_size_bytes().as_bytes_usize();
- let messages_payloads = bytes.slice(position..);
- position = 0;
- let mut messages = Vec::new();
- while position < messages_payloads.len() {
- let message = Message::from_bytes(messages_payloads.slice(position..))?;
- position += message.get_size_bytes().as_bytes_usize();
- messages.push(message);
- }
+ fn visit_map<V>(self, mut map: V) -> Result<SendMessages, V::Error>
+ where
+ V: MapAccess<'de>,
+ {
+ let mut partitioning = None;
+ let mut messages = None;
+
+ while let Some(key) = map.next_key()? {
+ match key {
+ Field::Partitioning => {
+ if partitioning.is_some() {
+ return Err(de::Error::duplicate_field("partitioning"));
+ }
+ partitioning = Some(map.next_value()?);
+ }
+ Field::Messages => {
+ if messages.is_some() {
+ return Err(de::Error::duplicate_field("messages"));
+ }
+
+ let message_data: Vec<serde_json::Value> = map.next_value()?;
+ let mut iggy_messages = Vec::new();
+
+ for msg in message_data {
+ let id =
+ msg.get("id").and_then(|v| v.as_u64()).unwrap_or(0) as u128;
+
+ let payload = msg
+ .get("payload")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| de::Error::missing_field("payload"))?;
+ let payload_bytes = BASE64
+ .decode(payload)
+ .map_err(|_| de::Error::custom("Invalid base64 payload"))?;
+
+ let headers_map = if let Some(headers) = msg.get("headers") {
+ if headers.is_null() {
+ None
+ } else {
+ Some(serde_json::from_value(headers.clone()).map_err(
+ |_| de::Error::custom("Invalid headers format"),
+ )?)
+ }
+ } else {
+ None
+ };
+
+ let iggy_message = if let Some(headers) = headers_map {
+ IggyMessage::with_id_and_headers(id, payload_bytes, headers)
+ } else {
+ IggyMessage::with_id(id, payload_bytes)
+ };
+
+ iggy_messages.push(iggy_message);
+ }
+
+ messages = Some(iggy_messages);
+ }
+ }
+ }
- let command = SendMessages {
- stream_id,
- topic_id,
- partitioning: key,
- messages,
- };
- Ok(command)
- }
-}
+ let partitioning =
+ partitioning.ok_or_else(|| de::Error::missing_field("partitioning"))?;
+ let messages = messages.ok_or_else(|| de::Error::missing_field("messages"))?;
-impl Display for SendMessages {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "{}|{}|{}|batch_len:{}|batch_size:{}",
- self.stream_id,
- self.topic_id,
- self.partitioning,
- self.messages.len(),
- self.messages
- .iter()
- .map(Message::get_size_bytes)
- .sum::<IggyByteSize>(),
- )
- }
-}
+ let batch = IggyMessagesBatch::from(&messages);
-impl Display for Partitioning {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self.kind {
- PartitioningKind::Balanced => write!(f, "{}|0", self.kind),
- PartitioningKind::PartitionId => write!(
- f,
- "{}|{}",
- self.kind,
- u32::from_le_bytes(self.value[..4].try_into().unwrap())
- ),
- PartitioningKind::MessagesKey => {
- write!(f, "{}|{}", self.kind, String::from_utf8_lossy(&self.value))
+ Ok(SendMessages {
+ stream_id: Identifier::default(),
+ topic_id: Identifier::default(),
+ partitioning,
+ batch,
+ })
}
}
- }
-}
-impl Display for PartitioningKind {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- PartitioningKind::Balanced => write!(f, "balanced"),
- PartitioningKind::PartitionId => write!(f, "partition_id"),
- PartitioningKind::MessagesKey => write!(f, "messages_key"),
- }
+ deserializer.deserialize_struct(
+ "SendMessages",
+ &["partitioning", "messages"],
+ SendMessagesVisitor,
+ )
}
}
@@ -583,101 +347,12 @@ impl Display for PartitioningKind {
mod tests {
use super::*;
- #[test]
- fn should_be_serialized_as_bytes() {
- let message_1 = Message::from_str("hello 1").unwrap();
- let message_2 = Message::new(Some(2), "hello 2".into(), None);
- let message_3 = Message::new(Some(3), "hello 3".into(), None);
- let messages = vec![message_1, message_2, message_3];
- let command = SendMessages {
- stream_id: Identifier::numeric(1).unwrap(),
- topic_id: Identifier::numeric(2).unwrap(),
- partitioning: Partitioning::partition_id(4),
- messages,
- };
-
- let bytes = command.to_bytes();
-
- let mut position = 0;
- let stream_id = Identifier::from_bytes(bytes.clone()).unwrap();
- position += stream_id.get_size_bytes().as_bytes_usize();
- let topic_id = Identifier::from_bytes(bytes.slice(position..)).unwrap();
- position += topic_id.get_size_bytes().as_bytes_usize();
- let key = Partitioning::from_bytes(bytes.slice(position..)).unwrap();
- position += key.get_size_bytes().as_bytes_usize();
- let messages = bytes.slice(position..);
- let command_messages = command
- .messages
- .iter()
- .fold(BytesMut::new(), |mut bytes_mut, message| {
- bytes_mut.put(message.to_bytes());
- bytes_mut
- })
- .freeze();
-
- assert!(!bytes.is_empty());
- assert_eq!(stream_id, command.stream_id);
- assert_eq!(topic_id, command.topic_id);
- assert_eq!(key, command.partitioning);
- assert_eq!(messages, command_messages);
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let stream_id = Identifier::numeric(1).unwrap();
- let topic_id = Identifier::numeric(2).unwrap();
- let key = Partitioning::partition_id(4);
-
- let message_1 = Message::from_str("hello 1").unwrap();
- let message_2 = Message::new(Some(2), "hello 2".into(), None);
- let message_3 = Message::new(Some(3), "hello 3".into(), None);
- let messages = [
- message_1.to_bytes(),
- message_2.to_bytes(),
- message_3.to_bytes(),
- ]
- .concat();
-
- let key_bytes = key.to_bytes();
- let stream_id_bytes = stream_id.to_bytes();
- let topic_id_bytes = topic_id.to_bytes();
- let current_position = stream_id_bytes.len() + topic_id_bytes.len() + key_bytes.len();
- let mut bytes = BytesMut::with_capacity(current_position);
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_slice(&key_bytes);
- bytes.put_slice(&messages);
- let bytes = bytes.freeze();
- let command = SendMessages::from_bytes(bytes.clone());
- assert!(command.is_ok());
-
- let messages_payloads = bytes.slice(current_position..);
- let mut position = 0;
- let mut messages = Vec::new();
- while position < messages_payloads.len() {
- let message = Message::from_bytes(messages_payloads.slice(position..)).unwrap();
- position += message.get_size_bytes().as_bytes_usize();
- messages.push(message);
- }
-
- let command = command.unwrap();
- assert_eq!(command.stream_id, stream_id);
- assert_eq!(command.topic_id, topic_id);
- assert_eq!(command.partitioning, key);
- for (index, message) in command.messages.iter().enumerate() {
- let command_message = &command.messages[index];
- assert_eq!(command_message.id, message.id);
- assert_eq!(command_message.length, message.length);
- assert_eq!(command_message.payload, message.payload);
- }
- }
-
#[test]
fn key_of_type_balanced_should_have_empty_value() {
let key = Partitioning::balanced();
assert_eq!(key.kind, PartitioningKind::Balanced);
assert_eq!(key.length, 0);
- assert_eq!(key.value, EMPTY_KEY_VALUE);
+ assert!(key.value.is_empty());
assert_eq!(
PartitioningKind::from_code(1).unwrap(),
PartitioningKind::Balanced
diff --git a/sdk/src/models/messages.rs b/sdk/src/models/messages.rs
deleted file mode 100644
index 444c4f7d..00000000
--- a/sdk/src/models/messages.rs
+++ /dev/null
@@ -1,200 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-use crate::bytes_serializable::BytesSerializable;
-use crate::error::IggyError;
-use crate::models::header;
-use crate::models::header::{HeaderKey, HeaderValue};
-use crate::utils::byte_size::IggyByteSize;
-use crate::utils::sizeable::Sizeable;
-use crate::utils::timestamp::IggyTimestamp;
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use serde_with::base64::Base64;
-use serde_with::serde_as;
-use std::collections::HashMap;
-use std::fmt::{Display, Formatter};
-use std::str::FromStr;
-
-pub const POLLED_MESSAGE_METADATA: u32 = 8 + 1 + 8 + 4;
-
-/// The wrapper on top of the collection of messages that are polled from the partition.
-/// It consists of the following fields:
-/// - `partition_id`: the identifier of the partition.
-/// - `current_offset`: the current offset of the partition.
-/// - `messages`: the collection of messages.
-#[derive(Debug, Serialize, Deserialize)]
-pub struct PolledMessages {
- /// The identifier of the partition. If it's '0', then there's no partition assigned to the consumer group member.
- pub partition_id: u32,
- /// The current offset of the partition.
- pub current_offset: u64,
- /// The collection of messages.
- pub messages: Vec<PolledMessage>,
-}
-
-/// The single message that is polled from the partition.
-/// It consists of the following fields:
-/// - `offset`: the offset of the message.
-/// - `state`: the state of the message.
-/// - `timestamp`: the timestamp of the message.
-/// - `id`: the identifier of the message.
-/// - `checksum`: the checksum of the message, can be used to verify the integrity of the message.
-/// - `headers`: the optional headers of the message.
-/// - `length`: the length of the payload.
-/// - `payload`: the binary payload of the message.
-#[serde_as]
-#[derive(Debug, Serialize, Deserialize)]
-pub struct PolledMessage {
- /// The offset of the message.
- pub offset: u64,
- /// The state of the message.
- pub state: MessageState,
- /// The timestamp of the message.
- pub timestamp: u64,
- /// The identifier of the message.
- pub id: u128,
- /// The checksum of the message, can be used to verify the integrity of the message.
- pub checksum: u32,
- /// The optional headers of the message.
- pub headers: Option<HashMap<HeaderKey, HeaderValue>>,
- /// The length of the payload.
- #[serde(skip)]
- pub length: IggyByteSize,
- /// The binary payload of the message.
- #[serde_as(as = "Base64")]
- pub payload: Bytes,
-}
-
-/// The state of the message, currently only the `Available` state is used.
-#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum MessageState {
- /// The message is available.
- Available,
- /// The message is unavailable.
- Unavailable,
- /// The message is poisoned.
- Poisoned,
- /// The message is marked for deletion.
- MarkedForDeletion,
-}
-
-impl MessageState {
- /// Returns the code of the message state.
- pub fn as_code(&self) -> u8 {
- match self {
- MessageState::Available => 1,
- MessageState::Unavailable => 10,
- MessageState::Poisoned => 20,
- MessageState::MarkedForDeletion => 30,
- }
- }
-
- /// Returns the message state from the code.
- pub fn from_code(code: u8) -> Result<Self, IggyError> {
- match code {
- 1 => Ok(MessageState::Available),
- 10 => Ok(MessageState::Unavailable),
- 20 => Ok(MessageState::Poisoned),
- 30 => Ok(MessageState::MarkedForDeletion),
- _ => Err(IggyError::InvalidCommand),
- }
- }
-}
-
-impl Display for MessageState {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- match self {
- MessageState::Available => write!(f, "available"),
- MessageState::Unavailable => write!(f, "unavailable"),
- MessageState::Poisoned => write!(f, "poisoned"),
- MessageState::MarkedForDeletion => write!(f, "marked_for_deletion"),
- }
- }
-}
-
-impl FromStr for MessageState {
- type Err = IggyError;
- fn from_str(s: &str) -> Result<Self, Self::Err> {
- match s {
- "available" => Ok(MessageState::Available),
- "unavailable" => Ok(MessageState::Unavailable),
- "poisoned" => Ok(MessageState::Poisoned),
- "marked_for_deletion" => Ok(MessageState::MarkedForDeletion),
- _ => Err(IggyError::InvalidCommand),
- }
- }
-}
-
-impl PolledMessage {
- /// Creates a new message with a specified offset.
- pub fn create(
- offset: u64,
- state: MessageState,
- timestamp: IggyTimestamp,
- id: u128,
- payload: Bytes,
- checksum: u32,
- headers: Option<HashMap<HeaderKey, HeaderValue>>,
- ) -> Self {
- PolledMessage {
- offset,
- state,
- timestamp: timestamp.as_micros(),
- id,
- checksum,
- length: IggyByteSize::from(payload.len() as u64),
- payload,
- headers,
- }
- }
-
- /// Returns the timestamp of the message as `IggyTimestamp`.
- pub fn timestamp(&self) -> IggyTimestamp {
- self.timestamp.into()
- }
-
- /// Extends the provided bytes with the message.
- pub fn extend(&self, bytes: &mut BytesMut) {
- bytes.put_u64_le(self.offset);
- bytes.put_u8(self.state.as_code());
- bytes.put_u64_le(self.timestamp);
- bytes.put_u128_le(self.id);
- bytes.put_u32_le(self.checksum);
- if let Some(headers) = &self.headers {
- let headers_bytes = headers.to_bytes();
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u32_le(headers_bytes.len() as u32);
- bytes.put_slice(&headers_bytes);
- } else {
- bytes.put_u32_le(0u32);
- }
- bytes.put_u32_le(self.length.as_bytes_u64() as u32);
- bytes.put_slice(&self.payload);
- }
-}
-
-impl Sizeable for PolledMessage {
- fn get_size_bytes(&self) -> IggyByteSize {
- // Offset + State + Timestamp + ID + Checksum + Length + Payload + Headers
- header::get_headers_size_bytes(&self.headers)
- + self.length
- + IggyByteSize::from(8 + 1 + 8 + 16 + 4 + 4)
- }
-}
diff --git a/server/src/streaming/models/mod.rs b/sdk/src/models/messaging/index.rs
similarity index 84%
rename from server/src/streaming/models/mod.rs
rename to sdk/src/models/messaging/index.rs
index 2c7de6a2..211c1b27 100644
--- a/server/src/streaming/models/mod.rs
+++ b/sdk/src/models/messaging/index.rs
@@ -16,6 +16,9 @@
* under the License.
*/
-pub mod messages;
-
-pub const COMPONENT: &str = "STREAMING_MODELS";
+#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
+pub struct IggyIndex {
+ pub offset: u32,
+ pub position: u32,
+ pub timestamp: u64,
+}
diff --git a/sdk/src/models/messaging/index_view.rs b/sdk/src/models/messaging/index_view.rs
new file mode 100644
index 00000000..80280ce1
--- /dev/null
+++ b/sdk/src/models/messaging/index_view.rs
@@ -0,0 +1,80 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+use crate::models::messaging::INDEX_SIZE;
+use bytes::Buf;
+
+use super::IggyIndex;
+
+/// View into a single index entry in a binary buffer.
+/// Provides zero-copy access to index data.
+#[derive(Debug, Clone, Copy)]
+pub struct IggyIndexView<'a> {
+ data: &'a [u8],
+}
+
+impl<'a> IggyIndexView<'a> {
+ /// Creates a new index view from a byte slice
+ /// Slice must be exactly INDEX_SIZE (16 bytes) long
+ pub fn new(data: &'a [u8]) -> Self {
+ debug_assert!(
+ data.len() == INDEX_SIZE,
+ "Index data must be exactly {INDEX_SIZE} bytes"
+ );
+ Self { data }
+ }
+
+ /// Gets the offset value from the view
+ pub fn offset(&self) -> u32 {
+ let mut buf = &self.data[0..4];
+ buf.get_u32_le()
+ }
+
+ /// Gets the position value from the view
+ pub fn position(&self) -> u32 {
+ let mut buf = &self.data[4..8];
+ buf.get_u32_le()
+ }
+
+ /// Gets the timestamp value from the view
+ pub fn timestamp(&self) -> u64 {
+ let mut buf = &self.data[8..16];
+ buf.get_u64_le()
+ }
+
+ /// Converts the view into an `IggyIndex`
+ pub fn to_index(&self) -> IggyIndex {
+ IggyIndex {
+ offset: self.offset(),
+ position: self.position(),
+ timestamp: self.timestamp(),
+ }
+ }
+}
+
+impl std::fmt::Display for IggyIndexView<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "offset: {}, position: {}, timestamp: {}",
+ self.offset(),
+ self.position(),
+ self.timestamp()
+ )
+ }
+}
diff --git a/sdk/src/models/messaging/indexes.rs b/sdk/src/models/messaging/indexes.rs
new file mode 100644
index 00000000..d9617868
--- /dev/null
+++ b/sdk/src/models/messaging/indexes.rs
@@ -0,0 +1,203 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+use super::{index_view::IggyIndexView, INDEX_SIZE};
+use bytes::Bytes;
+use serde::{Deserialize, Serialize};
+use serde_with::base64::Base64;
+use serde_with::serde_as;
+use std::ops::{Deref, Index as StdIndex};
+
+/// A container for binary-encoded index data.
+/// Optimized for efficient storage and I/O operations.
+#[serde_as]
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct IggyIndexes {
+ #[serde(skip)]
+ base_position: u32,
+ #[serde_as(as = "Base64")]
+ buffer: Bytes,
+}
+
+impl IggyIndexes {
+ /// Creates a new empty container
+ pub fn new(indexes: Bytes, base_position: u32) -> Self {
+ Self {
+ buffer: indexes,
+ base_position,
+ }
+ }
+
+ /// Creates a new empty container
+ pub fn empty() -> Self {
+ Self {
+ buffer: Bytes::new(),
+ base_position: 0,
+ }
+ }
+
+ /// Gets the number of indexes in the container
+ pub fn count(&self) -> u32 {
+ self.buffer.len() as u32 / INDEX_SIZE as u32
+ }
+
+ /// Gets the size of the buffer in bytes
+ pub fn size(&self) -> u32 {
+ self.buffer.len() as u32
+ }
+
+ /// Gets the size of all indexes messages
+ pub fn messages_size(&self) -> u32 {
+ self.last_position() - self.base_position
+ }
+
+ /// Gets a view of the index at the specified position
+ pub fn get(&self, position: u32) -> Option<IggyIndexView> {
+ if position >= self.count() {
+ return None;
+ }
+
+ let start = position as usize * INDEX_SIZE;
+ let end = start + INDEX_SIZE;
+
+ if end <= self.buffer.len() {
+ Some(IggyIndexView::new(&self.buffer[start..end]))
+ } else {
+ None
+ }
+ }
+
+ /// Gets a slice of the container
+ pub fn slice_by_offset(&self, relative_start_offset: u32, count: u32) -> Option<IggyIndexes> {
+ if self.count() == 0 || relative_start_offset >= self.count() {
+ return None;
+ }
+
+ let available_count = self.count().saturating_sub(relative_start_offset);
+ let actual_count = std::cmp::min(count, available_count);
+
+ if actual_count == 0 {
+ return None;
+ }
+
+ let end_pos = relative_start_offset + actual_count;
+ let start_byte = relative_start_offset as usize * INDEX_SIZE;
+ let end_byte = end_pos as usize * INDEX_SIZE;
+
+ if end_byte > self.buffer.len() {
+ return None;
+ }
+
+ let slice = self.buffer.slice(start_byte..end_byte);
+
+ let base_position = if relative_start_offset > 0 {
+ match self.get(relative_start_offset - 1) {
+ Some(index) => index.position(),
+ None => self.base_position,
+ }
+ } else {
+ self.base_position
+ };
+
+ Some(IggyIndexes::new(slice, base_position))
+ }
+
+ /// Finds an index by timestamp using binary search
+ /// If an exact match isn't found, returns the index with the nearest timestamp
+ /// that is greater than or equal to the requested timestamp
+ pub fn find_by_timestamp(&self, timestamp: u64) -> Option<IggyIndexView> {
+ if self.count() == 0 {
+ return None;
+ }
+
+ let first_idx = self.get(0)?;
+ if timestamp <= first_idx.timestamp() {
+ tracing::trace!(
+ "Requested timestamp {} is less than any available",
+ timestamp
+ );
+ return Some(first_idx);
+ }
+
+ let last_saved_idx = self.get(self.count() - 1)?;
+ if timestamp > last_saved_idx.timestamp() {
+ return None;
+ }
+
+ let mut left = 0;
+ let mut right = self.count() as isize - 1;
+ let mut result: Option<IggyIndexView> = None;
+
+ while left <= right {
+ let mid = left + (right - left) / 2;
+ let view = self.get(mid as u32).unwrap();
+ let current_timestamp = view.timestamp();
+
+ match current_timestamp.cmp(×tamp) {
+ std::cmp::Ordering::Equal => {
+ result = Some(view);
+ right = mid - 1;
+ }
+ std::cmp::Ordering::Less => {
+ left = mid + 1;
+ }
+ std::cmp::Ordering::Greater => {
+ result = Some(view);
+ right = mid - 1;
+ }
+ }
+ }
+
+ result
+ }
+
+ /// Gets the base position of the container
+ pub fn base_position(&self) -> u32 {
+ self.base_position
+ }
+
+ /// Helper method to get the last index position
+ pub fn last_position(&self) -> u32 {
+ self.get(self.count() - 1)
+ .map(|idx| idx.position())
+ .unwrap_or(0)
+ }
+
+ /// Decompose the container into its components
+ pub fn decompose(self) -> (u32, Bytes) {
+ (self.base_position, self.buffer)
+ }
+}
+
+impl StdIndex<usize> for IggyIndexes {
+ type Output = [u8];
+
+ fn index(&self, index: usize) -> &Self::Output {
+ let start = index * INDEX_SIZE;
+ let end = start + INDEX_SIZE;
+ &self.buffer[start..end]
+ }
+}
+
+impl Deref for IggyIndexes {
+ type Target = [u8];
+
+ fn deref(&self) -> &Self::Target {
+ &self.buffer
+ }
+}
diff --git a/sdk/src/models/messaging/message.rs b/sdk/src/models/messaging/message.rs
new file mode 100644
index 00000000..06567274
--- /dev/null
+++ b/sdk/src/models/messaging/message.rs
@@ -0,0 +1,591 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+use super::message_header::{IggyMessageHeader, IGGY_MESSAGE_HEADER_SIZE};
+use super::user_headers::get_headers_size_bytes;
+use crate::bytes_serializable::BytesSerializable;
+use crate::error::IggyError;
+use crate::models::messaging::user_headers::{HeaderKey, HeaderValue};
+use crate::utils::byte_size::IggyByteSize;
+use crate::utils::sizeable::Sizeable;
+use crate::utils::timestamp::IggyTimestamp;
+use bytes::{BufMut, Bytes, BytesMut};
+use serde::{Deserialize, Serialize};
+use serde_with::base64::Base64;
+use serde_with::serde_as;
+use std::collections::HashMap;
+use std::convert::TryFrom;
+use std::str::FromStr;
+use tracing::warn;
+
+/// A message stored in the Iggy messaging system.
+///
+/// `IggyMessage` represents a single message that can be sent to or received from
+/// a stream. Each message consists of:
+/// * A header with message metadata
+/// * A payload (the actual content)
+/// * Optional user-defined headers for additional context
+///
+/// # Examples
+///
+/// ```
+/// // Create a simple text message
+/// let message = IggyMessage::create("Hello world!");
+///
+/// // Create a message with custom ID
+/// let message = IggyMessage::with_id(42, "Custom message".into());
+///
+/// // Create a message with headers
+/// let mut headers = HashMap::new();
+/// headers.insert(HeaderKey::new("content-type")?, HeaderValue::from_str("text/plain")?);
+/// let message = IggyMessage::with_headers("Message with metadata".into(), headers);
+/// ```
+#[serde_as]
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+pub struct IggyMessage {
+ /// Message metadata
+ pub header: IggyMessageHeader,
+
+ /// Message content
+ #[serde_as(as = "Base64")]
+ pub payload: Bytes,
+
+ /// Optional user-defined headers
+ pub user_headers: Option<Bytes>,
+}
+
+impl IggyMessage {
+ /// Creates a new message with the given payload.
+ ///
+ /// This is the simplest way to create a message when you don't need
+ /// custom IDs or headers.
+ ///
+ /// # Arguments
+ ///
+ /// * `payload` - The message content
+ ///
+ /// # Returns
+ ///
+ /// A new `IggyMessage` with the provided payload
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let message = IggyMessage::create("Hello world!");
+ /// ```
+ pub fn create<T: Into<Bytes>>(payload: T) -> Self {
+ Self::builder()
+ .payload(payload)
+ .build()
+ .expect("Failed to create message with valid payload")
+ }
+
+ /// Creates a new message with a specific ID and payload.
+ ///
+ /// Use this when you need to control the message ID.
+ ///
+ /// # Arguments
+ ///
+ /// * `id` - Custom message ID
+ /// * `payload` - The message content
+ ///
+ /// # Returns
+ ///
+ /// A new `IggyMessage` with the provided ID and payload
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let message = IggyMessage::with_id(42, "My message".into());
+ /// ```
+ pub fn with_id<T: Into<Bytes>>(id: u128, payload: T) -> Self {
+ Self::builder()
+ .id(id)
+ .payload(payload)
+ .build()
+ .expect("Failed to create message with valid payload")
+ }
+
+ /// Creates a new message with payload and user-defined headers.
+ ///
+ /// # Arguments
+ ///
+ /// * `payload` - The message content
+ /// * `headers` - Key-value headers to attach to the message
+ ///
+ /// # Returns
+ ///
+ /// A new `IggyMessage` with the provided payload and headers
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let mut headers = HashMap::new();
+ /// headers.insert(HeaderKey::new("content-type")?, HeaderValue::from_str("text/plain")?);
+ ///
+ /// let message = IggyMessage::with_headers("My message".into(), headers);
+ /// ```
+ pub fn with_headers<T: Into<Bytes>>(
+ payload: T,
+ headers: HashMap<HeaderKey, HeaderValue>,
+ ) -> Self {
+ Self::builder()
+ .payload(payload)
+ .headers(headers)
+ .build()
+ .expect("Failed to create message with valid payload and headers")
+ }
+
+ /// Creates a new message with a specific ID, payload, and user-defined headers.
+ ///
+ /// This is the most flexible way to create a message with full control.
+ ///
+ /// # Arguments
+ ///
+ /// * `id` - Custom message ID
+ /// * `payload` - The message content
+ /// * `headers` - Key-value headers to attach to the message
+ ///
+ /// # Returns
+ ///
+ /// A new `IggyMessage` with all provided parameters
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let mut headers = HashMap::new();
+ /// headers.insert(HeaderKey::new("content-type")?, HeaderValue::from_str("text/plain")?);
+ ///
+ /// let message = IggyMessage::with_id_and_headers(42, "My message".into(), headers);
+ /// ```
+ pub fn with_id_and_headers<T: Into<Bytes>>(
+ id: u128,
+ payload: T,
+ headers: HashMap<HeaderKey, HeaderValue>,
+ ) -> Self {
+ Self::builder()
+ .id(id)
+ .payload(payload)
+ .headers(headers)
+ .build()
+ .expect("Failed to create message with valid payload and headers")
+ }
+
+ /// Creates a message builder for advanced configuration.
+ ///
+ /// Use the builder when you need fine-grained control over message creation.
+ ///
+ /// # Returns
+ ///
+ /// A new `IggyMessageBuilder` instance
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let message = IggyMessage::builder()
+ /// .id(123)
+ /// .payload("Hello")
+ /// .header("content-type", "text/plain")
+ /// .build()?;
+ /// ```
+ pub fn builder() -> IggyMessageBuilder {
+ IggyMessageBuilder::new()
+ }
+
+ /// Gets the user headers as a typed HashMap.
+ ///
+ /// This method parses the binary header data into a typed HashMap for easy access.
+ ///
+ /// # Returns
+ ///
+ /// * `Ok(Some(HashMap))` - Successfully parsed headers
+ /// * `Ok(None)` - No headers present
+ /// * `Err(IggyError)` - Error parsing headers
+ pub fn user_headers_map(&self) -> Result<Option<HashMap<HeaderKey, HeaderValue>>, IggyError> {
+ match &self.user_headers {
+ Some(headers) => {
+ let headers_bytes = Bytes::copy_from_slice(headers);
+ match HashMap::<HeaderKey, HeaderValue>::from_bytes(headers_bytes) {
+ Ok(h) => Ok(Some(h)),
+ Err(e) => {
+ warn!(
+ "Failed to deserialize user headers: {e}, user_headers_length: {}, skipping field...",
+ self.header.user_headers_length
+ );
+ Ok(None)
+ }
+ }
+ }
+ None => Ok(None),
+ }
+ }
+
+ /// Retrieves a specific user header value by key.
+ ///
+ /// This is a convenience method to get a specific header without handling the full map.
+ ///
+ /// # Arguments
+ ///
+ /// * `key` - The header key to look up
+ ///
+ /// # Returns
+ ///
+ /// * `Ok(Some(HeaderValue))` - Header found with its value
+ /// * `Ok(None)` - Header not found or headers couldn't be parsed
+ /// * `Err(IggyError)` - Error accessing headers
+ pub fn get_header(&self, key: &HeaderKey) -> Result<Option<HeaderValue>, IggyError> {
+ Ok(self
+ .user_headers_map()?
+ .and_then(|map| map.get(key).cloned()))
+ }
+
+ /// Checks if this message contains a specific header key.
+ ///
+ /// # Arguments
+ ///
+ /// * `key` - The header key to check for
+ ///
+ /// # Returns
+ ///
+ /// * `Ok(true)` - Header exists
+ /// * `Ok(false)` - Header doesn't exist or headers couldn't be parsed
+ /// * `Err(IggyError)` - Error accessing headers
+ pub fn has_header(&self, key: &HeaderKey) -> Result<bool, IggyError> {
+ Ok(self
+ .user_headers_map()?
+ .is_some_and(|map| map.contains_key(key)))
+ }
+
+ /// Gets the payload as a UTF-8 string, if valid.
+ ///
+ /// # Returns
+ ///
+ /// * `Ok(String)` - Successfully converted payload to string
+ /// * `Err(IggyError)` - Payload is not valid UTF-8
+ pub fn payload_as_string(&self) -> Result<String, IggyError> {
+ String::from_utf8(self.payload.to_vec()).map_err(|_| IggyError::InvalidUtf8)
+ }
+}
+
+impl Default for IggyMessage {
+ fn default() -> Self {
+ Self::create("hello world")
+ }
+}
+
+impl FromStr for IggyMessage {
+ type Err = IggyError;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ Ok(Self::create(Bytes::from(s.to_owned())))
+ }
+}
+
+impl std::fmt::Display for IggyMessage {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match String::from_utf8(self.payload.to_vec()) {
+ Ok(payload) => {
+ let preview = if payload.len() > 50 {
+ format!("{}... ({}B)", &payload[..47], self.payload.len())
+ } else {
+ payload
+ };
+ write!(
+ f,
+ "[{}] ID:{} '{}'",
+ self.header.offset, self.header.id, preview
+ )
+ }
+ Err(_) => {
+ write!(
+ f,
+ "[{}] ID:{} <binary {}B>",
+ self.header.offset,
+ self.header.id,
+ self.payload.len()
+ )
+ }
+ }
+ }
+}
+
+impl Sizeable for IggyMessage {
+ fn get_size_bytes(&self) -> IggyByteSize {
+ let payload_len = self.payload.len() as u64;
+ let headers_len = self.user_headers.as_ref().map_or(0, |h| h.len() as u64);
+ let message_header_len = IGGY_MESSAGE_HEADER_SIZE as u64;
+
+ IggyByteSize::from(payload_len + headers_len + message_header_len)
+ }
+}
+
+impl BytesSerializable for IggyMessage {
+ fn to_bytes(&self) -> Bytes {
+ let mut bytes = BytesMut::with_capacity(self.get_size_bytes().as_bytes_usize());
+ let message_header = self.header.to_bytes();
+ bytes.put_slice(&message_header);
+ bytes.put_slice(&self.payload);
+ if let Some(headers) = &self.user_headers {
+ bytes.put_slice(headers);
+ }
+ bytes.freeze()
+ }
+
+ fn from_bytes(bytes: Bytes) -> Result<Self, IggyError> {
+ if bytes.len() < IGGY_MESSAGE_HEADER_SIZE {
+ return Err(IggyError::InvalidCommand);
+ }
+
+ let mut position = 0;
+ let header = IggyMessageHeader::from_bytes(bytes.slice(0..IGGY_MESSAGE_HEADER_SIZE))?;
+
+ position += IGGY_MESSAGE_HEADER_SIZE;
+ let payload_end = position + header.payload_length as usize;
+
+ if payload_end > bytes.len() {
+ return Err(IggyError::InvalidMessagePayloadLength);
+ }
+
+ let payload = bytes.slice(position..payload_end);
+ position = payload_end;
+
+ let user_headers = if header.user_headers_length > 0 {
+ let headers_end = position + header.user_headers_length as usize;
+ if headers_end > bytes.len() {
+ return Err(IggyError::InvalidHeaderValue);
+ }
+ Some(bytes.slice(position..headers_end))
+ } else {
+ None
+ };
+
+ Ok(IggyMessage {
+ header,
+ payload,
+ user_headers,
+ })
+ }
+
+ fn write_to_buffer(&self, buf: &mut BytesMut) {
+ buf.put_slice(&self.header.to_bytes());
+ buf.put_slice(&self.payload);
+ if let Some(headers) = &self.user_headers {
+ buf.put_slice(headers);
+ }
+ }
+}
+
+/// Builder for creating `IggyMessage` instances with flexible configuration.
+///
+/// The builder pattern allows for clear, step-by-step construction of complex
+/// message configurations, with better error handling than chained constructors.
+#[derive(Debug, Default)]
+pub struct IggyMessageBuilder {
+ id: Option<u128>,
+ payload: Option<Bytes>,
+ headers: Option<HashMap<HeaderKey, HeaderValue>>,
+}
+
+impl IggyMessageBuilder {
+ /// Creates a new empty message builder.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Sets the message ID.
+ ///
+ /// If not specified, a default ID (0) will be used.
+ pub fn id(mut self, id: u128) -> Self {
+ self.id = Some(id);
+ self
+ }
+
+ /// Sets the message payload.
+ ///
+ /// This method accepts any type that can be converted into `Bytes`,
+ /// including strings, byte slices, and vectors.
+ pub fn payload<T: Into<Bytes>>(mut self, payload: T) -> Self {
+ self.payload = Some(payload.into());
+ self
+ }
+
+ /// Adds a single header key-value pair to the message.
+ ///
+ /// Multiple calls will add multiple headers.
+ pub fn header(mut self, key: HeaderKey, value: HeaderValue) -> Self {
+ let headers = self.headers.get_or_insert_with(HashMap::new);
+ headers.insert(key, value);
+ self
+ }
+
+ /// Adds a string header with the given key and value.
+ ///
+ /// This is a convenience method for adding string headers without
+ /// manually creating HeaderValue objects.
+ pub fn string_header(mut self, key: &str, value: &str) -> Result<Self, IggyError> {
+ let key = HeaderKey::new(key)?;
+ let value = HeaderValue::from_str(value)?;
+ let headers = self.headers.get_or_insert_with(HashMap::new);
+ headers.insert(key, value);
+ Ok(self)
+ }
+
+ /// Sets all headers at once from a HashMap.
+ ///
+ /// This replaces any headers previously added.
+ pub fn headers(mut self, headers: HashMap<HeaderKey, HeaderValue>) -> Self {
+ self.headers = Some(headers);
+ self
+ }
+
+ /// Builds the final IggyMessage from the configured parameters.
+ ///
+ /// # Returns
+ ///
+ /// * `Ok(IggyMessage)` - Successfully built message
+ /// * `Err(IggyError)` - Error during message construction
+ pub fn build(self) -> Result<IggyMessage, IggyError> {
+ let payload = self.payload.unwrap_or_default();
+ let id = self.id.unwrap_or(0);
+ let headers_length = get_headers_size_bytes(&self.headers).as_bytes_u64() as u32;
+
+ let header = IggyMessageHeader {
+ checksum: 0, // Checksum is calculated on server side
+ id,
+ offset: 0,
+ timestamp: 0,
+ origin_timestamp: IggyTimestamp::now().as_micros(),
+ user_headers_length: headers_length,
+ payload_length: payload.len() as u32,
+ };
+
+ let user_headers = self.headers.map(|headers| headers.to_bytes());
+
+ Ok(IggyMessage {
+ header,
+ payload,
+ user_headers,
+ })
+ }
+}
+
+// Clean implementations of conversion traits
+
+impl From<IggyMessage> for Bytes {
+ fn from(message: IggyMessage) -> Self {
+ message.to_bytes()
+ }
+}
+
+impl From<String> for IggyMessage {
+ fn from(s: String) -> Self {
+ Self::create(s)
+ }
+}
+
+impl From<&str> for IggyMessage {
+ fn from(s: &str) -> Self {
+ Self::create(Bytes::from(s.to_owned()))
+ }
+}
+
+impl From<Vec<u8>> for IggyMessage {
+ fn from(v: Vec<u8>) -> Self {
+ Self::create(v)
+ }
+}
+
+impl From<&[u8]> for IggyMessage {
+ fn from(bytes: &[u8]) -> Self {
+ Self::create(Bytes::copy_from_slice(bytes))
+ }
+}
+
+impl TryFrom<Bytes> for IggyMessage {
+ type Error = IggyError;
+
+ fn try_from(bytes: Bytes) -> Result<Self, Self::Error> {
+ Self::from_bytes(bytes)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_create_simple_message() {
+ let message = IggyMessage::create("test message");
+ assert_eq!(message.payload, Bytes::from("test message"));
+ assert_eq!(message.header.id, 0);
+ assert!(message.user_headers.is_none());
+ }
+
+ #[test]
+ fn test_create_with_id() {
+ let message = IggyMessage::with_id(42, "test with id");
+ assert_eq!(message.payload, Bytes::from("test with id"));
+ assert_eq!(message.header.id, 42);
+ }
+
+ #[test]
+ fn test_create_with_headers() {
+ let mut headers = HashMap::new();
+ headers.insert(
+ HeaderKey::new("content-type").unwrap(),
+ HeaderValue::from_str("text/plain").unwrap(),
+ );
+
+ let message = IggyMessage::with_headers("test with headers", headers);
+ assert_eq!(message.payload, Bytes::from("test with headers"));
+ assert!(message.user_headers.is_some());
+
+ let headers_map = message.user_headers_map().unwrap().unwrap();
+ assert_eq!(headers_map.len(), 1);
+ assert!(headers_map.contains_key(&HeaderKey::new("content-type").unwrap()));
+ }
+
+ #[test]
+ fn test_empty_payload() {
+ let message = IggyMessage::create(Bytes::new());
+ assert_eq!(message.payload.len(), 0);
+ assert_eq!(message.header.payload_length, 0);
+ }
+
+ #[test]
+ fn test_from_string() {
+ let message: IggyMessage = "simple message".into();
+ assert_eq!(message.payload, Bytes::from("simple message"));
+ }
+
+ #[test]
+ fn test_payload_as_string() {
+ let message = IggyMessage::create("test message");
+ assert_eq!(message.payload_as_string().unwrap(), "test message");
+ }
+
+ #[test]
+ fn test_serialization_roundtrip() {
+ let original = IggyMessage::with_id(123, "serialization test");
+ let bytes = original.to_bytes();
+ let decoded = IggyMessage::from_bytes(bytes).unwrap();
+
+ assert_eq!(original.header.id, decoded.header.id);
+ assert_eq!(original.payload, decoded.payload);
+ }
+}
diff --git a/sdk/src/models/messaging/message_header.rs b/sdk/src/models/messaging/message_header.rs
new file mode 100644
index 00000000..cbb6a836
--- /dev/null
+++ b/sdk/src/models/messaging/message_header.rs
@@ -0,0 +1,172 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+use crate::{
+ bytes_serializable::BytesSerializable,
+ error::IggyError,
+ utils::{byte_size::IggyByteSize, sizeable::Sizeable},
+};
+use bytes::{BufMut, Bytes, BytesMut};
+use serde::{Deserialize, Serialize};
+use std::ops::Range;
+
+pub const IGGY_MESSAGE_HEADER_SIZE: usize = 8 + 16 + 8 + 8 + 8 + 4 + 4;
+pub const IGGY_MESSAGE_HEADER_RANGE: Range<usize> = 0..IGGY_MESSAGE_HEADER_SIZE;
+
+pub const IGGY_MESSAGE_CHECKSUM_OFFSET_RANGE: Range<usize> = 0..8;
+pub const IGGY_MESSAGE_ID_OFFSET_RANGE: Range<usize> = 8..24;
+pub const IGGY_MESSAGE_OFFSET_OFFSET_RANGE: Range<usize> = 24..32;
+pub const IGGY_MESSAGE_TIMESTAMP_OFFSET_RANGE: Range<usize> = 32..40;
+pub const IGGY_MESSAGE_ORIGIN_TIMESTAMP_OFFSET_RANGE: Range<usize> = 40..48;
+pub const IGGY_MESSAGE_HEADERS_LENGTH_OFFSET_RANGE: Range<usize> = 48..52;
+pub const IGGY_MESSAGE_PAYLOAD_LENGTH_OFFSET_RANGE: Range<usize> = 52..56;
+
+#[derive(Debug, Serialize, Deserialize, PartialEq, Default)]
+pub struct IggyMessageHeader {
+ pub checksum: u64,
+ pub id: u128,
+ pub offset: u64,
+ pub timestamp: u64,
+ pub origin_timestamp: u64,
+ pub user_headers_length: u32,
+ pub payload_length: u32,
+}
+
+impl Sizeable for IggyMessageHeader {
+ fn get_size_bytes(&self) -> IggyByteSize {
+ IggyByteSize::from(IGGY_MESSAGE_HEADER_SIZE as u64)
+ }
+}
+
+impl IggyMessageHeader {
+ pub fn from_raw_bytes(bytes: &[u8]) -> Result<Self, IggyError> {
+ if bytes.len() != IGGY_MESSAGE_HEADER_SIZE {
+ return Err(IggyError::InvalidCommand);
+ }
+
+ Ok(IggyMessageHeader {
+ checksum: u64::from_le_bytes(
+ bytes[IGGY_MESSAGE_CHECKSUM_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ ),
+ id: u128::from_le_bytes(
+ bytes[IGGY_MESSAGE_ID_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ ),
+ offset: u64::from_le_bytes(
+ bytes[IGGY_MESSAGE_OFFSET_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ ),
+ timestamp: u64::from_le_bytes(
+ bytes[IGGY_MESSAGE_TIMESTAMP_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ ),
+ origin_timestamp: u64::from_le_bytes(
+ bytes[IGGY_MESSAGE_ORIGIN_TIMESTAMP_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ ),
+ user_headers_length: u32::from_le_bytes(
+ bytes[IGGY_MESSAGE_HEADERS_LENGTH_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ ),
+ payload_length: u32::from_le_bytes(
+ bytes[IGGY_MESSAGE_PAYLOAD_LENGTH_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ ),
+ })
+ }
+}
+
+impl BytesSerializable for IggyMessageHeader {
+ fn to_bytes(&self) -> Bytes {
+ let mut bytes = BytesMut::with_capacity(self.get_size_bytes().as_bytes_usize());
+ bytes.put_u64_le(self.checksum);
+ bytes.put_u128_le(self.id);
+ bytes.put_u64_le(self.offset);
+ bytes.put_u64_le(self.timestamp);
+ bytes.put_u64_le(self.origin_timestamp);
+ bytes.put_u32_le(self.user_headers_length);
+ bytes.put_u32_le(self.payload_length);
+ bytes.freeze()
+ }
+
+ fn from_bytes(bytes: Bytes) -> Result<Self, IggyError> {
+ if bytes.len() != IGGY_MESSAGE_HEADER_SIZE {
+ return Err(IggyError::InvalidCommand);
+ }
+
+ let checksum = u64::from_le_bytes(
+ bytes[IGGY_MESSAGE_CHECKSUM_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ let id = u128::from_le_bytes(
+ bytes[IGGY_MESSAGE_ID_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ let offset = u64::from_le_bytes(
+ bytes[IGGY_MESSAGE_OFFSET_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ let timestamp = u64::from_le_bytes(
+ bytes[IGGY_MESSAGE_TIMESTAMP_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ let origin_timestamp = u64::from_le_bytes(
+ bytes[IGGY_MESSAGE_ORIGIN_TIMESTAMP_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ let headers_length = u32::from_le_bytes(
+ bytes[IGGY_MESSAGE_HEADERS_LENGTH_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ let payload_length = u32::from_le_bytes(
+ bytes[IGGY_MESSAGE_PAYLOAD_LENGTH_OFFSET_RANGE]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ Ok(IggyMessageHeader {
+ checksum,
+ id,
+ offset,
+ timestamp,
+ origin_timestamp,
+ user_headers_length: headers_length,
+ payload_length,
+ })
+ }
+}
diff --git a/sdk/src/models/messaging/message_header_view.rs b/sdk/src/models/messaging/message_header_view.rs
new file mode 100644
index 00000000..ccc145ad
--- /dev/null
+++ b/sdk/src/models/messaging/message_header_view.rs
@@ -0,0 +1,117 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+use bytes::{Bytes, BytesMut};
+
+use crate::{error::IggyError, prelude::BytesSerializable};
+
+use super::message_header::*;
+
+/// A read-only, typed view into a message header in a raw buffer.
+///
+/// This wraps a `&[u8]` slice of at least `IGGY_MESSAGE_HEADER_SIZE` bytes.
+/// All accessor methods decode fields from the underlying buffer.
+#[derive(Debug)]
+pub struct IggyMessageHeaderView<'a> {
+ data: &'a [u8],
+}
+
+impl<'a> IggyMessageHeaderView<'a> {
+ /// Creates a new `IggyMessageHeaderView` over `data`.
+ pub fn new(data: &'a [u8]) -> Self {
+ debug_assert!(
+ data.len() >= IGGY_MESSAGE_HEADER_SIZE,
+ "Header view requires at least {} bytes",
+ IGGY_MESSAGE_HEADER_SIZE
+ );
+ Self { data }
+ }
+
+ /// The stored checksum at the start of the header
+ pub fn checksum(&self) -> u64 {
+ let bytes = &self.data[IGGY_MESSAGE_CHECKSUM_OFFSET_RANGE];
+ u64::from_le_bytes(bytes.try_into().unwrap())
+ }
+
+ /// The 128-bit ID (16 bytes)
+ pub fn id(&self) -> u128 {
+ let bytes = &self.data[IGGY_MESSAGE_ID_OFFSET_RANGE];
+ u128::from_le_bytes(bytes.try_into().unwrap())
+ }
+
+ /// The `offset` field (8 bytes)
+ pub fn offset(&self) -> u64 {
+ let bytes = &self.data[IGGY_MESSAGE_OFFSET_OFFSET_RANGE];
+ u64::from_le_bytes(bytes.try_into().unwrap())
+ }
+
+ /// The `timestamp` field (8 bytes)
+ pub fn timestamp(&self) -> u64 {
+ let bytes = &self.data[IGGY_MESSAGE_TIMESTAMP_OFFSET_RANGE];
+ u64::from_le_bytes(bytes.try_into().unwrap())
+ }
+
+ /// The `origin_timestamp` field (8 bytes)
+ pub fn origin_timestamp(&self) -> u64 {
+ let bytes = &self.data[IGGY_MESSAGE_ORIGIN_TIMESTAMP_OFFSET_RANGE];
+ u64::from_le_bytes(bytes.try_into().unwrap())
+ }
+
+ /// The size in bytes of the user headers
+ pub fn user_headers_length(&self) -> usize {
+ let bytes = &self.data[IGGY_MESSAGE_HEADERS_LENGTH_OFFSET_RANGE];
+ u32::from_le_bytes(bytes.try_into().unwrap()) as usize
+ }
+
+ /// The size in bytes of the message payload
+ pub fn payload_length(&self) -> usize {
+ let bytes = &self.data[IGGY_MESSAGE_PAYLOAD_LENGTH_OFFSET_RANGE];
+ u32::from_le_bytes(bytes.try_into().unwrap()) as usize
+ }
+
+ /// Convert this view to a full IggyMessageHeader struct
+ pub fn to_header(&self) -> IggyMessageHeader {
+ IggyMessageHeader {
+ checksum: self.checksum(),
+ id: self.id(),
+ offset: self.offset(),
+ timestamp: self.timestamp(),
+ origin_timestamp: self.origin_timestamp(),
+ user_headers_length: self.user_headers_length() as u32,
+ payload_length: self.payload_length() as u32,
+ }
+ }
+}
+
+impl BytesSerializable for IggyMessageHeaderView<'_> {
+ fn to_bytes(&self) -> Bytes {
+ panic!("should not be used")
+ }
+
+ fn from_bytes(_bytes: Bytes) -> Result<Self, IggyError> {
+ panic!("should not be used")
+ }
+
+ fn write_to_buffer(&self, buf: &mut BytesMut) {
+ buf.extend_from_slice(self.data);
+ }
+
+ fn get_buffer_size(&self) -> usize {
+ IGGY_MESSAGE_HEADER_SIZE
+ }
+}
diff --git a/sdk/src/models/messaging/message_view.rs b/sdk/src/models/messaging/message_view.rs
new file mode 100644
index 00000000..e1cbc683
--- /dev/null
+++ b/sdk/src/models/messaging/message_view.rs
@@ -0,0 +1,196 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+use super::message_header::*;
+use super::HeaderValue;
+use super::{message_header_view::IggyMessageHeaderView, HeaderKey};
+use crate::error::IggyError;
+use crate::prelude::BytesSerializable;
+use crate::prelude::IggyByteSize;
+use crate::prelude::Sizeable;
+use crate::utils::checksum;
+use bytes::{Bytes, BytesMut};
+use std::{collections::HashMap, iter::Iterator};
+
+/// A immutable view of a message.
+#[derive(Debug)]
+pub struct IggyMessageView<'a> {
+ buffer: &'a [u8],
+ payload_offset: usize,
+ user_headers_offset: usize,
+}
+
+impl<'a> IggyMessageView<'a> {
+ /// Creates a new immutable message view from a buffer.
+ pub fn new(buffer: &'a [u8]) -> Self {
+ let header_view = IggyMessageHeaderView::new(&buffer[IGGY_MESSAGE_HEADER_RANGE]);
+ let payload_len = header_view.payload_length();
+ let payload_offset = IGGY_MESSAGE_HEADER_SIZE;
+ let headers_offset = payload_offset + payload_len;
+
+ Self {
+ buffer,
+ payload_offset,
+ user_headers_offset: headers_offset,
+ }
+ }
+
+ /// Returns an immutable header view.
+ pub fn header(&self) -> IggyMessageHeaderView<'_> {
+ IggyMessageHeaderView::new(&self.buffer[0..IGGY_MESSAGE_HEADER_SIZE])
+ }
+
+ /// Returns an immutable slice of the user headers.
+ pub fn user_headers(&self) -> Option<&[u8]> {
+ if self.header().user_headers_length() > 0 {
+ let header_length = self.header().user_headers_length();
+ let end_offset = self.user_headers_offset + header_length;
+
+ if end_offset <= self.buffer.len() {
+ Some(&self.buffer[self.user_headers_offset..end_offset])
+ } else {
+ tracing::error!(
+ "Header length in message exceeds buffer bounds: length={}, buffer_remaining={}",
+ header_length,
+ self.buffer.len() - self.user_headers_offset
+ );
+ None
+ }
+ } else {
+ None
+ }
+ }
+
+ /// Return instantiated user headers map
+ pub fn user_headers_map(&self) -> Result<Option<HashMap<HeaderKey, HeaderValue>>, IggyError> {
+ if let Some(headers) = self.user_headers() {
+ let headers_bytes = Bytes::copy_from_slice(headers);
+
+ match HashMap::<HeaderKey, HeaderValue>::from_bytes(headers_bytes) {
+ Ok(h) => Ok(Some(h)),
+ Err(e) => {
+ tracing::error!(
+ "Error parsing headers: {}, header_length={}",
+ e,
+ self.header().user_headers_length()
+ );
+
+ Ok(None)
+ }
+ }
+ } else {
+ Ok(None)
+ }
+ }
+
+ /// Returns the size of the entire message.
+ pub fn size(&self) -> usize {
+ let header_view = self.header();
+ IGGY_MESSAGE_HEADER_SIZE + header_view.payload_length() + header_view.user_headers_length()
+ }
+
+ /// Returns a reference to the payload portion.
+ pub fn payload(&self) -> &[u8] {
+ let header_view = self.header();
+ let payload_len = header_view.payload_length();
+ &self.buffer[self.payload_offset..self.payload_offset + payload_len]
+ }
+
+ /// Validates that the message view is properly formatted and has valid data.
+ pub fn validate(&self) -> Result<(), IggyError> {
+ if self.buffer.len() < IGGY_MESSAGE_HEADER_SIZE {
+ return Err(IggyError::InvalidMessagePayloadLength);
+ }
+
+ let header = self.header();
+ let payload_len = header.payload_length();
+ let user_headers_len = header.user_headers_length();
+ let total_size = IGGY_MESSAGE_HEADER_SIZE + payload_len + user_headers_len;
+
+ if self.buffer.len() < total_size {
+ return Err(IggyError::InvalidMessagePayloadLength);
+ }
+ Ok(())
+ }
+
+ /// Validates that the message view has a valid checksum.
+ /// This should be called only on server side.
+ pub fn calculate_checksum(&self) -> u64 {
+ let checksum_field_size = size_of::<u64>(); // Skip checksum field for checksum calculation
+ let size = self.size() - checksum_field_size;
+ let data = &self.buffer[checksum_field_size..checksum_field_size + size];
+
+ // TODO(hubcio): field is 64 bits, but checksum is 32 bits (crc32fast)
+ // in future, we should change it to cryptographic safe hash
+ u64::from(checksum::calculate(data))
+ }
+}
+
+impl BytesSerializable for IggyMessageView<'_> {
+ fn to_bytes(&self) -> Bytes {
+ panic!("should not be used")
+ }
+
+ fn from_bytes(_bytes: Bytes) -> Result<Self, IggyError> {
+ panic!("should not be used")
+ }
+
+ fn write_to_buffer(&self, buf: &mut BytesMut) {
+ buf.extend_from_slice(self.buffer);
+ }
+
+ fn get_buffer_size(&self) -> usize {
+ self.buffer.len()
+ }
+}
+
+impl Sizeable for IggyMessageView<'_> {
+ fn get_size_bytes(&self) -> IggyByteSize {
+ IggyByteSize::from(self.buffer.len() as u64)
+ }
+}
+
+/// Iterator over immutable message views in a buffer.
+pub struct IggyMessageViewIterator<'a> {
+ buffer: &'a [u8],
+ position: usize,
+}
+
+impl<'a> IggyMessageViewIterator<'a> {
+ pub fn new(buffer: &'a [u8]) -> Self {
+ Self {
+ buffer,
+ position: 0,
+ }
+ }
+}
+
+impl<'a> Iterator for IggyMessageViewIterator<'a> {
+ type Item = IggyMessageView<'a>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.position >= self.buffer.len() {
+ return None;
+ }
+
+ let remaining = &self.buffer[self.position..];
+ let view = IggyMessageView::new(remaining);
+ self.position += view.size();
+ Some(view)
+ }
+}
diff --git a/sdk/src/models/messaging/messages_batch.rs b/sdk/src/models/messaging/messages_batch.rs
new file mode 100644
index 00000000..0a934744
--- /dev/null
+++ b/sdk/src/models/messaging/messages_batch.rs
@@ -0,0 +1,587 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+use super::{IggyIndexes, IggyMessage, IggyMessageView, IggyMessageViewIterator};
+use crate::{
+ error::IggyError,
+ messages::MAX_PAYLOAD_SIZE,
+ models::messaging::INDEX_SIZE,
+ prelude::{BytesSerializable, IggyByteSize, Sizeable, Validatable},
+};
+use bytes::{BufMut, Bytes, BytesMut};
+use std::ops::{Deref, Index};
+
+/// An immutable messages container that holds a buffer of messages
+#[derive(Clone, Debug, PartialEq)]
+pub struct IggyMessagesBatch {
+ /// The number of messages in the batch
+ count: u32,
+ /// The byte-indexes of messages in the buffer, represented as array of u32's. Offsets are relative.
+ /// Each index consists of offset, position (byte offset in the buffer) and timestamp.
+ indexes: IggyIndexes,
+ /// The buffer containing the messages
+ messages: Bytes,
+}
+
+impl IggyMessagesBatch {
+ /// Create a batch from indexes buffer and messages buffer
+ pub fn new(indexes: IggyIndexes, messages: Bytes, count: u32) -> Self {
+ Self {
+ count,
+ indexes,
+ messages,
+ }
+ }
+
+ /// Creates a empty messages batch
+ pub fn empty() -> Self {
+ Self::new(IggyIndexes::empty(), BytesMut::new().freeze(), 0)
+ }
+
+ /// Create iterator over messages
+ pub fn iter(&self) -> IggyMessageViewIterator {
+ IggyMessageViewIterator::new(&self.messages)
+ }
+
+ /// Get the number of messages
+ pub fn count(&self) -> u32 {
+ self.count
+ }
+
+ /// Check if the batch is empty
+ pub fn is_empty(&self) -> bool {
+ self.count() == 0
+ }
+
+ /// Get the total size of all messages in bytes
+ pub fn size(&self) -> u32 {
+ self.messages.len() as u32
+ }
+
+ /// Get access to the underlying buffer
+ pub fn buffer(&self) -> &[u8] {
+ &self.messages
+ }
+
+ /// Get the indexes slice
+ pub fn indexes_slice(&self) -> &[u8] {
+ &self.indexes
+ }
+
+ /// Take the indexes from the batch
+ pub fn take_indexes(&mut self) -> IggyIndexes {
+ std::mem::take(&mut self.indexes)
+ }
+
+ /// Decompose the batch into its components
+ pub fn decompose(self) -> (u32, IggyIndexes, Bytes) {
+ (self.count, self.indexes, self.messages)
+ }
+
+ /// Get index of first message
+ pub fn first_offset(&self) -> u64 {
+ self.iter()
+ .next()
+ .map(|msg| msg.header().offset())
+ .unwrap_or(0)
+ }
+
+ /// Get timestamp of first message
+ pub fn first_timestamp(&self) -> u64 {
+ self.iter()
+ .next()
+ .map(|msg| msg.header().timestamp())
+ .unwrap_or(0)
+ }
+
+ /// Get offset of last message
+ pub fn last_offset(&self) -> u64 {
+ self.iter()
+ .last()
+ .map(|msg| msg.header().offset())
+ .unwrap_or(0)
+ }
+
+ /// Get timestamp of last message
+ pub fn last_timestamp(&self) -> u64 {
+ self.iter()
+ .last()
+ .map(|msg| msg.header().timestamp())
+ .unwrap_or(0)
+ }
+
+ /// Calculates the start position of a message at the given index in the buffer
+ fn message_start_position(&self, index: usize) -> usize {
+ if index == 0 {
+ 0
+ } else {
+ self.position_at(index as u32 - 1) as usize - self.indexes.base_position() as usize
+ }
+ }
+
+ /// Calculates the end position of a message at the given index in the buffer
+ fn message_end_position(&self, index: usize) -> usize {
+ if index >= self.count as usize - 1 {
+ self.messages.len()
+ } else {
+ self.position_at(index as u32) as usize - self.indexes.base_position() as usize
+ }
+ }
+
+ /// Gets the byte range for a message at the given index
+ fn get_message_boundaries(&self, index: usize) -> Option<(usize, usize)> {
+ if index >= self.count as usize {
+ return None;
+ }
+
+ let start = self.message_start_position(index);
+ let end = self.message_end_position(index);
+
+ if start > self.messages.len() || end > self.messages.len() || start > end {
+ return None;
+ }
+
+ Some((start, end))
+ }
+
+ /// Helper method to read a position (u32) from the byte array at the given index
+ fn position_at(&self, position_index: u32) -> u32 {
+ if let Some(index) = self.indexes.get(position_index) {
+ index.position()
+ } else {
+ 0
+ }
+ }
+
+ /// Returns a contiguous slice (as a new `IggyMessagesBatch`) of up to `count` messages
+ /// whose message headers have an offset greater than or equal to the provided `start_offset`.
+ pub fn slice_by_offset(&self, start_offset: u64, count: u32) -> Option<Self> {
+ if self.is_empty() || count == 0 {
+ return None;
+ }
+
+ let first_offset = self.first_offset();
+
+ if start_offset < first_offset {
+ return self.slice_by_index(0, count);
+ }
+
+ let last_offset = self.last_offset();
+ if start_offset > last_offset {
+ return None;
+ }
+
+ let offset_diff = start_offset - first_offset;
+ let first_message_index = offset_diff as usize;
+
+ if first_message_index >= self.count() as usize {
+ return None;
+ }
+
+ self.slice_by_index(first_message_index as u32, count)
+ }
+
+ /// Helper method to slice the batch starting from a specific index
+ fn slice_by_index(&self, start_index: u32, count: u32) -> Option<Self> {
+ if start_index >= self.count() {
+ return None;
+ }
+
+ let last_message_index =
+ std::cmp::min((start_index + count) as usize, self.count() as usize);
+
+ let sub_indexes = self.indexes.slice_by_offset(
+ start_index,
+ (last_message_index - start_index as usize) as u32,
+ )?;
+
+ let first_message_position = self.message_start_position(start_index as usize);
+ let last_message_position = self.message_end_position(last_message_index - 1);
+
+ let sub_buffer = self
+ .messages
+ .slice(first_message_position..last_message_position);
+
+ Some(IggyMessagesBatch {
+ count: (last_message_index - start_index as usize) as u32,
+ indexes: sub_indexes,
+ messages: sub_buffer,
+ })
+ }
+
+ /// Returns a contiguous slice (as a new `IggyMessagesBatch`) of up to `count` messages
+ /// whose message headers have a timestamp greater than or equal to the provided `timestamp`.
+ ///
+ /// If no messages meet the criteria, returns `None`.
+ pub fn slice_by_timestamp(&self, timestamp: u64, count: u32) -> Option<Self> {
+ if self.is_empty() || count == 0 {
+ return None;
+ }
+
+ // Use binary search to find the first message with timestamp >= the target
+ let first_message_index = self.binary_search_timestamp(timestamp)?;
+
+ self.slice_by_index(first_message_index, count)
+ }
+
+ /// Find the position of the index with timestamp closest to (but not exceeding) the target
+ fn binary_search_timestamp(&self, target_timestamp: u64) -> Option<u32> {
+ if self.count() == 0 {
+ return None;
+ }
+
+ let last_timestamp = self.get(self.count() as usize - 1)?.header().timestamp();
+ if target_timestamp > last_timestamp {
+ return Some(self.count() - 1);
+ }
+
+ let first_timestamp = self.get(0)?.header().timestamp();
+ if target_timestamp <= first_timestamp {
+ return Some(0);
+ }
+
+ let mut low = 0;
+ let mut high = self.count() - 1;
+
+ while low <= high {
+ let mid = low + (high - low) / 2;
+ let mid_index = self.get(mid as usize)?;
+ let mid_timestamp = mid_index.header().timestamp();
+
+ match mid_timestamp.cmp(&target_timestamp) {
+ std::cmp::Ordering::Equal => return Some(mid),
+ std::cmp::Ordering::Less => low = mid + 1,
+ std::cmp::Ordering::Greater => {
+ if mid == 0 {
+ break;
+ }
+ high = mid - 1;
+ }
+ }
+ }
+
+ Some(low)
+ }
+
+ /// Get the message at the specified index.
+ /// Returns None if the index is out of bounds.
+ pub fn get(&self, index: usize) -> Option<IggyMessageView> {
+ if let Some((start, end)) = self.get_message_boundaries(index) {
+ Some(IggyMessageView::new(&self.messages[start..end]))
+ } else {
+ None
+ }
+ }
+
+ /// Consumes the batch and returns a vector of messages.
+ pub fn into_messages(self) -> Vec<IggyMessage> {
+ if self.is_empty() {
+ return Vec::new();
+ }
+
+ let mut result = Vec::with_capacity(self.count as usize);
+
+ for i in 0..self.count as usize {
+ if let Some((start, end)) = self.get_message_boundaries(i) {
+ if let Ok(message) = IggyMessage::from_bytes(self.messages.slice(start..end)) {
+ result.push(message);
+ }
+ }
+ }
+
+ result
+ }
+
+ /// Validates that all messages in batch have correct checksums.
+ pub fn validate_checksums(&self) -> Result<(), IggyError> {
+ for message in self.iter() {
+ let calculated_checksum = message.calculate_checksum();
+ let actual_checksum = message.header().checksum();
+ let offset = message.header().offset();
+ if calculated_checksum != actual_checksum {
+ return Err(IggyError::InvalidMessageChecksum(
+ actual_checksum,
+ calculated_checksum,
+ offset,
+ ));
+ }
... 17175 lines suppressed ...