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/03/10 01:54:57 UTC
(iggy) 01/03: send works
This is an automated email from the ASF dual-hosted git repository.
hgruszecki pushed a commit to branch zero-copy-no-batching
in repository https://gitbox.apache.org/repos/asf/iggy.git
commit b2089061bae1eb718fe4768d158e7aef37e6eeec
Author: Hubert Gruszecki <h....@gmail.com>
AuthorDate: Fri Mar 7 22:57:08 2025 +0100
send works
---
Cargo.lock | 20 +-
Cargo.toml | 2 +-
bench/src/actors/consumer.rs | 9 +-
bench/src/actors/producer.rs | 28 +-
bench/src/actors/producing_consumer.rs | 7 +-
bench/src/actors/utils.rs | 13 +-
bench/src/benchmarks/consumer_benchmark.rs | 2 +-
bench/src/benchmarks/consumer_group_benchmark.rs | 5 +-
.../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 +-
.../tests/cli/message/test_message_send_command.rs | 2 +-
sdk/Cargo.toml | 2 +-
sdk/src/binary/messages.rs | 88 ++-
sdk/src/bytes_serializable.rs | 3 +-
sdk/src/cli/message/poll_messages.rs | 9 +-
sdk/src/cli/message/send_messages.rs | 21 +-
sdk/src/client.rs | 10 +-
sdk/src/clients/client.rs | 13 +-
sdk/src/clients/consumer.rs | 24 +-
sdk/src/clients/producer.rs | 25 +-
sdk/src/consumer_ext/consumer_message_ext.rs | 4 +-
sdk/src/consumer_ext/mod.rs | 6 +-
sdk/src/http/messages.rs | 10 +-
sdk/src/identifier.rs | 18 +
sdk/src/lib.rs | 1 +
sdk/src/messages/flush_unsaved_buffer.rs | 8 +-
sdk/src/messages/mod.rs | 20 +-
sdk/src/messages/partitioning.rs | 192 ++++++
sdk/src/messages/partitioning_kind.rs | 62 ++
sdk/src/messages/poll_messages.rs | 209 +-----
sdk/src/messages/polling_kind.rs | 81 +++
sdk/src/messages/polling_strategy.rs | 135 ++++
.../{send_messages.rs => send_messages copy.rs} | 53 --
sdk/src/messages/send_messages.rs | 757 ++++++---------------
sdk/src/models/{batch.rs => batch copy.rs} | 0
sdk/src/models/header.rs | 2 -
sdk/src/models/message.rs | 60 --
sdk/src/models/messaging/message.rs | 210 ++++++
sdk/src/models/messaging/message_header.rs | 130 ++++
sdk/src/models/messaging/message_view.rs | 248 +++++++
sdk/src/models/messaging/message_view_mut.rs | 155 +++++
sdk/src/models/messaging/messages.rs | 91 +++
sdk/src/models/messaging/messages_mut.rs | 100 +++
sdk/src/models/messaging/mod.rs | 13 +
sdk/src/models/mod.rs | 9 +-
sdk/src/partitioner.rs | 4 +-
sdk/src/prelude.rs | 31 +
.../stream_builder/config/config_iggy_consumer.rs | 5 +-
.../stream_builder/config/config_iggy_producer.rs | 5 +-
sdk/src/tcp/client.rs | 18 +-
server/src/binary/command.rs | 5 +-
.../messages/flush_unsaved_buffer_handler.rs | 3 +-
.../handlers/messages/poll_messages_handler.rs | 79 ++-
.../handlers/messages/send_messages_handler.rs | 95 +--
server/src/http/messages.rs | 3 +-
.../streaming/batching/appendable_batch_info.rs | 16 -
server/src/streaming/batching/batch_accumulator.rs | 104 ---
server/src/streaming/batching/mod.rs | 2 -
server/src/streaming/mod.rs | 1 -
server/src/streaming/partitions/messages.rs | 81 ++-
server/src/streaming/partitions/mod.rs | 20 -
server/src/streaming/partitions/storage.rs | 1 -
server/src/streaming/segments/fetch_result.rs | 42 --
server/src/streaming/segments/logs/mod.rs | 7 -
.../log_reader.rs => messages/messages_reader.rs} | 172 ++---
.../log_writer.rs => messages/messages_writer.rs} | 54 +-
server/src/streaming/segments/messages/mod.rs | 7 +
.../segments/{logs => messages}/persister_task.rs | 50 +-
.../src/streaming/segments/messages_accumulator.rs | 94 +++
server/src/streaming/segments/mod.rs | 5 +-
server/src/streaming/segments/reading_messages.rs | 426 ++++++------
server/src/streaming/segments/segment.rs | 15 +-
server/src/streaming/segments/writing_messages.rs | 58 +-
server/src/streaming/systems/messages.rs | 16 +-
server/src/streaming/topics/messages.rs | 38 +-
server/src/tcp/connection_handler.rs | 3 -
78 files changed, 2546 insertions(+), 1783 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index ff8e0788..b848c698 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -834,9 +834,12 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "bytes"
-version = "1.10.0"
+version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f61dac84819c6588b558454b194026eb1f09c293b9036ae9b159e74e73ab6cf9"
+checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
+dependencies = [
+ "serde",
+]
[[package]]
name = "bzip2"
@@ -5362,19 +5365,6 @@ dependencies = [
"tracing",
]
-[[package]]
-name = "tools"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "clap",
- "iggy",
- "rand 0.9.0",
- "tokio",
- "tracing",
- "tracing-subscriber",
-]
-
[[package]]
name = "tower"
version = "0.4.13"
diff --git a/Cargo.toml b/Cargo.toml
index 4556b6af..788acfcc 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,7 +13,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 b3db565d..d0dc6d30 100644
--- a/bench/src/actors/consumer.rs
+++ b/bench/src/actors/consumer.rs
@@ -7,7 +7,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;
@@ -230,7 +231,7 @@ impl Consumer {
}
let batch = batch.unwrap();
- if batch.batch.is_empty() {
+ if batch.is_empty() {
// Store initial poll timestamp if this is the first attempt
if initial_poll_timestamp.is_none() {
initial_poll_timestamp = Some(before_poll);
@@ -295,8 +296,8 @@ 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 = batch.batch.len() as u64;
- batch_size_total_bytes = batch.batch.len() as u64;
+ batch_user_size_bytes = batch.len() as u64;
+ batch_size_total_bytes = batch.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 04d867c3..15fb7906 100644
--- a/bench/src/actors/producer.rs
+++ b/bench/src/actors/producer.rs
@@ -6,7 +6,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::models::IggyMessage;
+use iggy::prelude::Partitioning;
use iggy::utils::byte_size::IggyByteSize;
use iggy::utils::duration::IggyDuration;
use iggy::utils::sizeable::Sizeable;
@@ -91,8 +92,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);
}
@@ -136,7 +137,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;
@@ -150,6 +154,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;
@@ -182,6 +190,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 114aef50..e0cd55a8 100644
--- a/bench/src/actors/producing_consumer.rs
+++ b/bench/src/actors/producing_consumer.rs
@@ -8,8 +8,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;
@@ -104,8 +103,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);
}
diff --git a/bench/src/actors/utils.rs b/bench/src/actors/utils.rs
index 90dce53d..6fa2c5fe 100644
--- a/bench/src/actors/utils.rs
+++ b/bench/src/actors/utils.rs
@@ -1,30 +1,21 @@
-use std::time::Duration;
-
use bytes::Bytes;
-use iggy::messages::send_messages::Message;
+use iggy::models::IggyMessage;
//TODO: Fix me
-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);
}
diff --git a/bench/src/benchmarks/consumer_benchmark.rs b/bench/src/benchmarks/consumer_benchmark.rs
index 59574cf9..33c92521 100644
--- a/bench/src/benchmarks/consumer_benchmark.rs
+++ b/bench/src/benchmarks/consumer_benchmark.rs
@@ -3,7 +3,7 @@ use crate::args::common::IggyBenchArgs;
use crate::benchmarks::benchmark::{BenchmarkFutures, Benchmarkable};
use crate::rate_limiter::RateLimiter;
use async_trait::async_trait;
-use iggy::messages::poll_messages::PollingKind;
+use iggy::messages::PollingKind;
use iggy_bench_report::benchmark_kind::BenchmarkKind;
use integration::test_server::ClientFactory;
use std::sync::atomic::AtomicI64;
diff --git a/bench/src/benchmarks/consumer_group_benchmark.rs b/bench/src/benchmarks/consumer_group_benchmark.rs
index daa67f33..d2ca0051 100644
--- a/bench/src/benchmarks/consumer_group_benchmark.rs
+++ b/bench/src/benchmarks/consumer_group_benchmark.rs
@@ -6,10 +6,7 @@ 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::{client::ConsumerGroupClient, clients::client::IggyClient, error::IggyError, messages::PollingKind};
use iggy_bench_report::benchmark_kind::BenchmarkKind;
use integration::test_server::{login_root, ClientFactory};
use std::sync::{atomic::AtomicI64, Arc};
diff --git a/bench/src/benchmarks/producer_and_consumer_benchmark.rs b/bench/src/benchmarks/producer_and_consumer_benchmark.rs
index b26f5a7b..1c4a3fd8 100644
--- a/bench/src/benchmarks/producer_and_consumer_benchmark.rs
+++ b/bench/src/benchmarks/producer_and_consumer_benchmark.rs
@@ -4,7 +4,7 @@ use crate::args::common::IggyBenchArgs;
use crate::benchmarks::benchmark::{BenchmarkFutures, Benchmarkable};
use crate::rate_limiter::RateLimiter;
use async_trait::async_trait;
-use iggy::messages::poll_messages::PollingKind;
+use iggy::messages::PollingKind;
use iggy_bench_report::benchmark_kind::BenchmarkKind;
use integration::test_server::ClientFactory;
use std::sync::atomic::AtomicI64;
diff --git a/bench/src/benchmarks/producer_and_consumer_group_benchmark.rs b/bench/src/benchmarks/producer_and_consumer_group_benchmark.rs
index 9117cb1a..00f46eca 100644
--- a/bench/src/benchmarks/producer_and_consumer_group_benchmark.rs
+++ b/bench/src/benchmarks/producer_and_consumer_group_benchmark.rs
@@ -6,10 +6,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;
use integration::test_server::{login_root, ClientFactory};
use std::sync::{atomic::AtomicI64, Arc};
diff --git a/bench/src/benchmarks/producing_consumer_benchmark.rs b/bench/src/benchmarks/producing_consumer_benchmark.rs
index 1f4b9d67..8909636f 100644
--- a/bench/src/benchmarks/producing_consumer_benchmark.rs
+++ b/bench/src/benchmarks/producing_consumer_benchmark.rs
@@ -3,7 +3,7 @@ use crate::args::common::IggyBenchArgs;
use crate::benchmarks::benchmark::{BenchmarkFutures, Benchmarkable};
use crate::rate_limiter::RateLimiter;
use async_trait::async_trait;
-use iggy::messages::poll_messages::PollingKind;
+use iggy::messages::PollingKind;
use iggy_bench_report::benchmark_kind::BenchmarkKind;
use integration::test_server::ClientFactory;
use std::sync::atomic::AtomicI64;
diff --git a/bench/src/benchmarks/producing_consumer_group_benchmark.rs b/bench/src/benchmarks/producing_consumer_group_benchmark.rs
index 6553ce7f..81b8f52b 100644
--- a/bench/src/benchmarks/producing_consumer_group_benchmark.rs
+++ b/bench/src/benchmarks/producing_consumer_group_benchmark.rs
@@ -7,7 +7,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 integration::test_server::{login_root, ClientFactory};
use std::sync::atomic::AtomicI64;
diff --git a/integration/tests/cli/message/test_message_send_command.rs b/integration/tests/cli/message/test_message_send_command.rs
index 69694225..2310c317 100644
--- a/integration/tests/cli/message/test_message_send_command.rs
+++ b/integration/tests/cli/message/test_message_send_command.rs
@@ -218,7 +218,7 @@ impl IggyCmdTestCase for TestMessageSendCmd {
assert!(polled_messages.is_ok());
let polled_messages = polled_messages.unwrap();
- assert_eq!(polled_messages.messages.len(), self.messages.len());
+ assert_eq!(polled_messages.batch., self.messages.len());
assert_eq!(
polled_messages
.messages
diff --git a/sdk/Cargo.toml b/sdk/Cargo.toml
index ce008add..e0bc3a49 100644
--- a/sdk/Cargo.toml
+++ b/sdk/Cargo.toml
@@ -25,7 +25,7 @@ byte-unit = { version = "5.1.6", default-features = false, features = [
"byte",
"std",
] }
-bytes = "1.10.0"
+bytes = { version = "1.10.1", features = ["serde"] }
chrono = { version = "0.4.39" }
clap = { version = "4.5.30", features = ["derive"] }
comfy-table = { version = "7.1.4", optional = true }
diff --git a/sdk/src/binary/messages.rs b/sdk/src/binary/messages.rs
index bbffecd2..058de839 100644
--- a/sdk/src/binary/messages.rs
+++ b/sdk/src/binary/messages.rs
@@ -5,11 +5,9 @@ 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::batch::{IggyBatch, IggyHeader, IGGY_BATCH_OVERHEAD};
+use crate::messages::{FlushUnsavedBuffer, PollingStrategy};
+use crate::models::{IggyMessage, IggyMessages, IggyMessagesMut};
+use crate::prelude::{BytesSerializable, IggyByteSize, Partitioning, SendMessages, Sizeable};
#[async_trait::async_trait]
impl<B: BinaryClient> MessageClient for B {
@@ -22,28 +20,29 @@ impl<B: BinaryClient> MessageClient for B {
strategy: &PollingStrategy,
count: u32,
auto_commit: bool,
- ) -> Result<IggyBatch, IggyError> {
- fail_if_not_authenticated(self).await?;
- let response = self
- .send_raw_with_response(
- POLL_MESSAGES_CODE,
- poll_messages::as_bytes(
- stream_id,
- topic_id,
- partition_id,
- consumer,
- strategy,
- count,
- auto_commit,
- ),
- )
- .await?;
- let mut position = 0;
- let header = IggyHeader::from_bytes(&response[..IGGY_BATCH_OVERHEAD as usize]);
- position += IGGY_BATCH_OVERHEAD as usize;
- let bytes = response.slice(position..);
- let batch = IggyBatch::new(header, bytes);
- Ok(batch)
+ ) -> Result<Vec<IggyMessage>, IggyError> {
+ todo!()
+ // fail_if_not_authenticated(self).await?;
+ // let response = self
+ // .send_raw_with_response(
+ // POLL_MESSAGES_CODE,
+ // poll_messages::as_bytes(
+ // stream_id,
+ // topic_id,
+ // partition_id,
+ // consumer,
+ // strategy,
+ // count,
+ // auto_commit,
+ // ),
+ // )
+ // .await?;
+ // let mut position = 0;
+ // let header = IggyHeader::from_bytes(&response[..IGGY_BATCH_OVERHEAD as usize]);
+ // position += IGGY_BATCH_OVERHEAD as usize;
+ // let bytes = response.slice(position..);
+ // let batch = IggyBatch::new(header, bytes);
+ // Ok(batch)
}
async fn send_messages(
@@ -51,14 +50,37 @@ 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),
- )
- .await?;
+
+ // let send_messages = SendMessages {
+ // stream_id: stream_id.clone(),
+ // topic_id: topic_id.clone(),
+ // partitioning: partitioning.clone(),
+ // messages_count: messages.len() as u32,
+ // messages: IggyMessagesMut::from_messages(messages, messages.len() as u32),
+ // };
+
+ let now = std::time::Instant::now();
+ let send_messages = SendMessages::as_bytes(stream_id, topic_id, partitioning, messages);
+ tracing::trace!(
+ "SendMessages::as_bytes took {} us, len {}",
+ now.elapsed().as_micros(),
+ send_messages.len()
+ );
+ // tracing::error!("Sending messages stream {} topic {}, partitioning: {:?}, messages_count: {}, messages_size: {}",
+ // stream_id, topic_id, partitioning, messages.len(), send_messages.messages.size());
+
+ // let request = send_messages.to_bytes();
+ // tracing::error!("Sending SendMessages request of size: {}", request.len());
+ let now = std::time::Instant::now();
+ self.send_raw_with_response(SEND_MESSAGES_CODE, send_messages)
+ .await?;
+ tracing::trace!(
+ "send_raw_with_response took {} us",
+ now.elapsed().as_micros()
+ );
Ok(())
}
diff --git a/sdk/src/bytes_serializable.rs b/sdk/src/bytes_serializable.rs
index 60e1721f..0ba88326 100644
--- a/sdk/src/bytes_serializable.rs
+++ b/sdk/src/bytes_serializable.rs
@@ -1,6 +1,5 @@
-use bytes::Bytes;
-
use crate::error::IggyError;
+use bytes::Bytes;
/// The trait represents the logic responsible for serializing and deserializing the struct to and from bytes.
pub trait BytesSerializable {
diff --git a/sdk/src/cli/message/poll_messages.rs b/sdk/src/cli/message/poll_messages.rs
index 5ffeccfb..a9c2f3b0 100644
--- a/sdk/src/cli/message/poll_messages.rs
+++ b/sdk/src/cli/message/poll_messages.rs
@@ -3,10 +3,9 @@ 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::batch::IggyBatch;
+use crate::messages::{PollMessages, PollingStrategy};
use crate::models::header::{HeaderKey, HeaderKind};
+use crate::models::IggyMessage;
use crate::utils::sizeable::Sizeable;
use crate::utils::timestamp::IggyTimestamp;
use crate::utils::{byte_size::IggyByteSize, duration::IggyDuration};
@@ -64,7 +63,7 @@ impl PollMessagesCmd {
fn create_message_header_keys(
&self,
- polled_messages: &IggyBatch,
+ polled_messages: &Vec<IggyMessage>,
) -> HashSet<(HeaderKey, HeaderKind)> {
//TODO: Fix me
/*
@@ -106,7 +105,7 @@ impl PollMessagesCmd {
}
fn create_table_content(
- polled_messages: &IggyBatch,
+ polled_messages: &Vec<IggyMessage>,
message_header_keys: &HashSet<(HeaderKey, HeaderKind)>,
) -> Vec<Row> {
//TODO: Fix me
diff --git a/sdk/src/cli/message/send_messages.rs b/sdk/src/cli/message/send_messages.rs
index 68e4d192..6b2155d6 100644
--- a/sdk/src/cli/message/send_messages.rs
+++ b/sdk/src/cli/message/send_messages.rs
@@ -2,8 +2,9 @@ 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::models::IggyMessage;
+use crate::prelude::Partitioning;
use crate::utils::sizeable::Sizeable;
use anyhow::Context;
use async_trait::async_trait;
@@ -95,13 +96,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();
@@ -125,14 +126,24 @@ impl CliCommand for SendMessagesCmd {
match &self.messages {
Some(messages) => messages
.iter()
- .map(|s| Message::new(None, s.clone().into(), self.get_headers()))
+ .map(|s| {
+ IggyMessage::builder()
+ .payload(Bytes::from(s.clone()))
+ .headers(self.get_headers().clone())
+ .build()
+ })
.collect::<Vec<_>>(),
None => {
let input = self.read_message_from_stdin()?;
input
.lines()
- .map(|m| Message::new(None, String::from(m).into(), self.get_headers()))
+ .map(|m| {
+ IggyMessage::builder()
+ .payload(String::from(m).into())
+ .headers(self.get_headers().clone())
+ .build()
+ })
.collect()
}
}
diff --git a/sdk/src/client.rs b/sdk/src/client.rs
index 977931dd..3f861bfb 100644
--- a/sdk/src/client.rs
+++ b/sdk/src/client.rs
@@ -3,9 +3,6 @@ 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::batch::IggyBatch;
use crate::models::client_info::{ClientInfo, ClientInfoDetails};
use crate::models::consumer_group::{ConsumerGroup, ConsumerGroupDetails};
use crate::models::consumer_offset_info::ConsumerOffsetInfo;
@@ -18,6 +15,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;
@@ -329,7 +327,8 @@ pub trait MessageClient {
strategy: &PollingStrategy,
count: u32,
auto_commit: bool,
- ) -> Result<IggyBatch, IggyError>;
+ ) -> Result<Vec<IggyMessage>, 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.
@@ -338,8 +337,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 5e2f359b..d3e1b24e 100644
--- a/sdk/src/clients/client.rs
+++ b/sdk/src/clients/client.rs
@@ -12,9 +12,7 @@ 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::models::batch::IggyBatch;
+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;
@@ -27,10 +25,11 @@ 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::models::IggyMessage;
use crate::partitioner::Partitioner;
+use crate::prelude::Partitioning;
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;
@@ -543,7 +542,7 @@ impl MessageClient for IggyClient {
strategy: &PollingStrategy,
count: u32,
auto_commit: bool,
- ) -> Result<IggyBatch, IggyError> {
+ ) -> Result<Vec<IggyMessage>, IggyError> {
if count == 0 {
return Err(IggyError::InvalidMessagesCount);
}
@@ -581,7 +580,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);
@@ -590,7 +589,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 da93d8c9..3ee78759 100644
--- a/sdk/src/clients/consumer.rs
+++ b/sdk/src/clients/consumer.rs
@@ -4,8 +4,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::batch::IggyBatch;
+use crate::messages::PollingStrategy;
+use crate::models::IggyMessage;
use crate::utils::byte_size::IggyByteSize;
use crate::utils::crypto::EncryptorKind;
use crate::utils::duration::IggyDuration;
@@ -28,7 +28,7 @@ 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<IggyBatch, IggyError>>>>;
+type PollMessagesFuture = Pin<Box<dyn Future<Output = Result<Vec<IggyMessage>, IggyError>>>>;
/// The auto-commit configuration for storing the offset on the server.
#[derive(Debug, PartialEq, Copy, Clone)]
@@ -102,7 +102,7 @@ pub struct IggyConsumer {
last_consumed_offsets: Arc<DashMap<u32, AtomicU64>>,
current_offsets: Arc<DashMap<u32, AtomicU64>>,
poll_future: Option<PollMessagesFuture>,
- buffered_messages: VecDeque<IggyBatch>,
+ buffered_messages: VecDeque<Vec<IggyMessage>>,
encryptor: Option<Arc<EncryptorKind>>,
store_offset_sender: flume::Sender<(u32, u64)>,
store_offset_after_each_message: bool,
@@ -566,7 +566,9 @@ impl IggyConsumer {
});
}
- fn create_poll_messages_future(&self) -> impl Future<Output = Result<IggyBatch, IggyError>> {
+ fn create_poll_messages_future(
+ &self,
+ ) -> impl Future<Output = Result<Vec<IggyMessage>, IggyError>> {
let stream_id = self.stream_id.clone();
let topic_id = self.topic_id.clone();
let partition_id = self.partition_id;
@@ -789,16 +791,16 @@ impl IggyConsumer {
}
}
-pub struct ReceivedMessage {
- pub message: IggyBatch,
+pub struct ReceivedBatch {
+ pub messages: Vec<IggyMessage>,
pub current_offset: u64,
pub partition_id: u32,
}
-impl ReceivedMessage {
- pub fn new(message: IggyBatch, current_offset: u64, partition_id: u32) -> Self {
+impl ReceivedBatch {
+ pub fn new(messages: Vec<IggyMessage>, current_offset: u64, partition_id: u32) -> Self {
Self {
- message,
+ messages,
current_offset,
partition_id,
}
@@ -806,7 +808,7 @@ impl ReceivedMessage {
}
impl Stream for IggyConsumer {
- type Item = Result<ReceivedMessage, IggyError>;
+ type Item = Result<ReceivedBatch, IggyError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let partition_id = self.current_partition_id.load(ORDERING);
diff --git a/sdk/src/clients/producer.rs b/sdk/src/clients/producer.rs
index 645ac430..05ed42b9 100644
--- a/sdk/src/clients/producer.rs
+++ b/sdk/src/clients/producer.rs
@@ -4,8 +4,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::models::IggyMessage;
use crate::partitioner::Partitioner;
+use crate::prelude::Partitioning;
use crate::utils::crypto::EncryptorKind;
use crate::utils::duration::IggyDuration;
use crate::utils::expiry::IggyExpiry;
@@ -212,7 +213,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(());
@@ -233,13 +234,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() {
@@ -266,7 +267,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() {
@@ -288,7 +289,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)?;
@@ -324,7 +325,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.");
@@ -365,11 +366,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(())
@@ -380,7 +381,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 {
@@ -456,7 +457,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;
@@ -498,7 +499,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 78d5c9c3..6c093fa3 100644
--- a/sdk/src/consumer_ext/consumer_message_ext.rs
+++ b/sdk/src/consumer_ext/consumer_message_ext.rs
@@ -70,8 +70,8 @@ impl IggyConsumerMessageExt for IggyConsumer {
Some(Ok(received_message)) => {
let partition_id = received_message.partition_id;
let current_offset = received_message.current_offset;
- //TODO: fix me, this used to be message.offset
- let message_offset = received_message.message.header.base_offset;
+ //TODO(hubcio): fix me, this used to be message.offset
+ let message_offset = received_message.messages[0].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 c7e686f6..52869755 100644
--- a/sdk/src/consumer_ext/mod.rs
+++ b/sdk/src/consumer_ext/mod.rs
@@ -1,7 +1,7 @@
mod consumer_message_ext;
mod consumer_message_trait;
-use crate::clients::consumer::ReceivedMessage;
+use crate::clients::consumer::ReceivedBatch;
use crate::error::IggyError;
pub use consumer_message_trait::IggyConsumerMessageExt;
@@ -18,7 +18,7 @@ pub trait LocalMessageConsumer {
/// # Errors
///
/// * `IggyError` - If the message consumer fails to consume the message
- async fn consume(&self, message: ReceivedMessage) -> Result<(), IggyError>;
+ async fn consume(&self, message: ReceivedBatch) -> Result<(), IggyError>;
}
// Default implementation for `&T`
@@ -33,7 +33,7 @@ impl<T: MessageConsumer + Send + Sync> MessageConsumer for &T {
/// # Errors
///
/// * `IggyError` - If the message consumer fails to consume the message
- async fn consume(&self, message: ReceivedMessage) -> Result<(), IggyError> {
+ async fn consume(&self, message: ReceivedBatch) -> Result<(), IggyError> {
(**self).consume(message).await
}
}
diff --git a/sdk/src/http/messages.rs b/sdk/src/http/messages.rs
index 19844e00..404556f2 100644
--- a/sdk/src/http/messages.rs
+++ b/sdk/src/http/messages.rs
@@ -4,10 +4,8 @@ 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::batch::IggyBatch;
+use crate::messages::{Partitioning, PollingStrategy};
+use crate::models::IggyMessage;
use async_trait::async_trait;
#[async_trait]
@@ -21,7 +19,7 @@ impl MessageClient for HttpClient {
strategy: &PollingStrategy,
count: u32,
auto_commit: bool,
- ) -> Result<IggyBatch, IggyError> {
+ ) -> Result<Vec<IggyMessage>, IggyError> {
/*
let response = self
.get_with_query(
@@ -51,7 +49,7 @@ impl MessageClient for HttpClient {
stream_id: &Identifier,
topic_id: &Identifier,
partitioning: &Partitioning,
- messages: &mut [Message],
+ messages: &mut [IggyMessage],
) -> Result<(), IggyError> {
/*
self.post(
diff --git a/sdk/src/identifier.rs b/sdk/src/identifier.rs
index 804b28a9..b6abadc4 100644
--- a/sdk/src/identifier.rs
+++ b/sdk/src/identifier.rs
@@ -164,6 +164,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 {
diff --git a/sdk/src/lib.rs b/sdk/src/lib.rs
index 7790dc8e..62003368 100644
--- a/sdk/src/lib.rs
+++ b/sdk/src/lib.rs
@@ -28,6 +28,7 @@ pub mod models;
pub mod partitioner;
pub mod partitions;
pub mod personal_access_tokens;
+pub mod prelude;
pub mod quic;
pub mod snapshot;
pub mod stream_builder;
diff --git a/sdk/src/messages/flush_unsaved_buffer.rs b/sdk/src/messages/flush_unsaved_buffer.rs
index 80f69e03..3f6cfe7f 100644
--- a/sdk/src/messages/flush_unsaved_buffer.rs
+++ b/sdk/src/messages/flush_unsaved_buffer.rs
@@ -1,8 +1,3 @@
-use std::fmt::Display;
-
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-
use crate::{
bytes_serializable::BytesSerializable,
command::{Command, FLUSH_UNSAVED_BUFFER_CODE},
@@ -10,6 +5,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 8a588efc..3b36c844 100644
--- a/sdk/src/messages/mod.rs
+++ b/sdk/src/messages/mod.rs
@@ -1,6 +1,18 @@
-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 polling_kind;
+mod polling_strategy;
+mod send_messages;
-const MAX_HEADERS_SIZE: u32 = 100 * 1000;
+pub const MAX_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 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..74a8924f
--- /dev/null
+++ b/sdk/src/messages/partitioning.rs
@@ -0,0 +1,192 @@
+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,
+ })
+ }
+}
diff --git a/sdk/src/messages/partitioning_kind.rs b/sdk/src/messages/partitioning_kind.rs
new file mode 100644
index 00000000..d05bdc3b
--- /dev/null
+++ b/sdk/src/messages/partitioning_kind.rs
@@ -0,0 +1,62 @@
+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},
+};
+
+/// `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 901027f1..4268621d 100644
--- a/sdk/src/messages/poll_messages.rs
+++ b/sdk/src/messages/poll_messages.rs
@@ -1,3 +1,5 @@
+use super::polling_kind::PollingKind;
+use super::polling_strategy::PollingStrategy;
use crate::bytes_serializable::BytesSerializable;
use crate::command::{Command, POLL_MESSAGES_CODE};
use crate::consumer::{Consumer, ConsumerKind};
@@ -12,6 +14,9 @@ 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:
/// - `consumer` - consumer which will poll messages. Either regular consumer or consumer group.
@@ -33,54 +38,27 @@ 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 fn default_number_of_messages_to_poll() -> u32 {
+ DEFAULT_NUMBER_OF_MESSAGES_TO_POLL
+ }
-/// `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,
+ pub fn default_partition_id() -> Option<u32> {
+ Some(DEFAULT_PARTITION_ID)
+ }
}
impl Default for PollMessages {
@@ -90,22 +68,13 @@ impl Default for PollMessages {
stream_id: Identifier::numeric(1).unwrap(),
topic_id: Identifier::numeric(1).unwrap(),
partition_id: default_partition_id(),
- strategy: default_strategy(),
- count: default_count(),
+ 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
@@ -116,128 +85,16 @@ 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(
@@ -363,12 +220,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"
@@ -377,30 +228,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/polling_kind.rs b/sdk/src/messages/polling_kind.rs
new file mode 100644
index 00000000..edb6d7f5
--- /dev/null
+++ b/sdk/src/messages/polling_kind.rs
@@ -0,0 +1,81 @@
+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;
+
+/// `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..8527b8eb
--- /dev/null
+++ b/sdk/src/messages/polling_strategy.rs
@@ -0,0 +1,135 @@
+use super::polling_kind::PollingKind;
+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;
+
+/// 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 copy.rs
similarity index 91%
copy from sdk/src/messages/send_messages.rs
copy to sdk/src/messages/send_messages copy.rs
index 05a1ff87..dd4fbd30 100644
--- a/sdk/src/messages/send_messages.rs
+++ b/sdk/src/messages/send_messages copy.rs
@@ -431,59 +431,6 @@ impl BytesSerializable for Message {
}
}
-// 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)
- .map(|size| size + 24u64.into())
- .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(
- 8 + IGGY_BATCH_OVERHEAD as usize
- + stream_id_bytes.len()
- + topic_id_bytes.len()
- + key_bytes.len()
- + messages_size.as_bytes_usize(),
- );
- let metadata_len = key_bytes.len() + stream_id_bytes.len() + topic_id_bytes.len();
- let metadata_len = metadata_len as u32;
-
- bytes.put_slice(&metadata_len.to_le_bytes());
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_slice(&key_bytes);
-
- let header = IggyHeader::default();
- bytes.put_slice(&header.as_bytes());
- for message in messages {
- // TODO: create a writer method on the `Message` and in the future
- // once the `Message` struct is dropped on the `IggyMessage`.
- bytes.extend_from_slice(&0u32.to_le_bytes()); // offset_delta
- bytes.extend_from_slice(&0u32.to_le_bytes()); // timestamp_delta
- bytes.extend_from_slice(&message.id.to_le_bytes());
-
- let headers_len =
- IggyVarInt::from(header::get_headers_size_bytes(&message.headers).as_bytes_u64());
- let payload_len = IggyVarInt::from(message.length);
- payload_len.encode(&mut bytes);
- headers_len.encode(&mut bytes);
- bytes.extend_from_slice(&message.payload);
- if let Some(headers) = &message.headers {
- let headers_bytes = headers.to_bytes();
- bytes.put_slice(&headers_bytes);
- }
- }
-
- bytes.freeze()
-}
impl FromStr for Message {
type Err = IggyError;
diff --git a/sdk/src/messages/send_messages.rs b/sdk/src/messages/send_messages.rs
index 05a1ff87..8ec53070 100644
--- a/sdk/src/messages/send_messages.rs
+++ b/sdk/src/messages/send_messages.rs
@@ -1,11 +1,13 @@
+use super::{Partitioning, PartitioningKind};
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::batch::{IggyHeader, IGGY_BATCH_OVERHEAD};
-use crate::models::header;
use crate::models::header::{HeaderKey, HeaderValue};
+use crate::models::{
+ IggyMessage, IggyMessageView, IggyMessageViewIterator, IggyMessages, IggyMessagesMut,
+};
use crate::utils::byte_size::IggyByteSize;
use crate::utils::sizeable::Sizeable;
use crate::utils::varint::IggyVarInt;
@@ -27,9 +29,7 @@ const EMPTY_KEY_VALUE: Vec<u8> = vec![];
/// - `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.
-// TODO: Fix me, this struct should have `batch` containing IggyBatch instead of `messages` field
-// so it's compatible with the server side deserialization
+/// - `messages` - collection of messages to be sent using zero-copy message views.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct SendMessages {
/// Unique stream ID (numeric or name).
@@ -40,179 +40,60 @@ pub struct SendMessages {
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>,
+ /// Number of messages to be sent.
+ pub messages_count: u32,
+ /// Messages collection
+ pub messages: Bytes,
}
-/// `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_bytes = stream_id.to_bytes();
+ let topic_id_bytes = topic_id.to_bytes();
+ let partitioning_bytes = partitioning.to_bytes();
+ let messages_count = messages.len() as u32;
+
+ let total_size = stream_id_bytes.len()
+ + topic_id_bytes.len()
+ + partitioning_bytes.len()
+ + 4 // For messages_count (u32)
+ + 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>>,
-}
+ bytes.put_slice(&stream_id_bytes);
+ bytes.put_slice(&topic_id_bytes);
+ bytes.put_slice(&partitioning_bytes);
+ bytes.put_u32_le(messages_count);
-/// `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,
-}
+ for message in messages {
+ message.write_to_bytes_mut(&mut bytes);
+ }
-impl Hash for PartitioningKind {
- fn hash<H: Hasher>(&self, state: &mut H) {
- self.as_code().hash(state);
+ bytes.freeze()
}
}
-fn default_message_id() -> u128 {
- 0
-}
-
impl Default for SendMessages {
fn default() -> Self {
SendMessages {
stream_id: Identifier::default(),
topic_id: Identifier::default(),
partitioning: Partitioning::default(),
- messages: vec![Message::default()],
+ messages: Bytes::new(),
+ messages_count: 0,
}
}
}
-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(),
- }
- }
-}
-
-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
@@ -221,32 +102,47 @@ impl Command for SendMessages {
impl Validatable<IggyError> for SendMessages {
fn validate(&self) -> Result<(), IggyError> {
- if self.messages.is_empty() {
+ if self.messages.is_empty() || self.messages_count == 0 {
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);
+ let mut message_count = 0;
+
+ for message_result in IggyMessageViewIterator::new(&self.messages) {
+ match message_result {
+ Ok(message_view) => {
+ message_count += 1;
+
+ if let Ok(Some(headers)) = message_view.headers() {
+ for value in headers.values() {
+ headers_size += value.value.len() as u32;
+ if headers_size > MAX_HEADERS_SIZE {
+ return Err(IggyError::TooBigHeadersPayload);
+ }
+ }
+ }
+
+ let message_payload = message_view.payload();
+ payload_size += message_payload.len() as u32;
+ if payload_size > MAX_PAYLOAD_SIZE {
+ return Err(IggyError::TooBigMessagePayload);
}
}
+ Err(e) => return Err(e),
}
- payload_size += message.payload.len() as u32;
- if payload_size > MAX_PAYLOAD_SIZE {
- return Err(IggyError::TooBigMessagePayload);
- }
+ }
+
+ if message_count == 0 {
+ return Err(IggyError::InvalidMessagesCount);
}
if payload_size == 0 {
@@ -257,431 +153,186 @@ impl Validatable<IggyError> for SendMessages {
}
}
-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 BytesSerializable for SendMessages {
+ fn to_bytes(&self) -> Bytes {
+ let stream_id_bytes = self.stream_id.to_bytes();
+ let topic_id_bytes = self.topic_id.to_bytes();
+ let partitioning_bytes = self.partitioning.to_bytes();
-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,
- }
- }
-}
+ let metadata_len = stream_id_bytes.len()
+ + topic_id_bytes.len()
+ + partitioning_bytes.len()
+ + std::mem::size_of::<u32>();
-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()
- }
-}
+ let total_len = metadata_len + self.messages.len();
-impl Default for Message {
- fn default() -> Self {
- let payload = Bytes::from("hello world");
- Message {
- id: 1,
- length: payload.len() as u32,
- payload,
- headers: None,
- }
- }
-}
+ let mut bytes = BytesMut::with_capacity(total_len);
-impl Display for Message {
- 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))
- }
- }
-}
+ bytes.put_slice(&stream_id_bytes);
+ bytes.put_slice(&topic_id_bytes);
+ bytes.put_slice(&partitioning_bytes);
+ bytes.put_u32_le(self.messages_count);
+ bytes.put_slice(&self.messages);
-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 {
+ fn from_bytes(bytes: Bytes) -> Result<SendMessages, IggyError> {
+ if bytes.is_empty() {
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 {
+ let mut position = 0;
+ let stream_id = Identifier::from_bytes(bytes.clone())?;
+ position += stream_id.get_size_bytes().as_bytes_usize();
+
+ if bytes.len() <= position {
return Err(IggyError::InvalidCommand);
}
- Ok(Partitioning {
- kind,
- length,
- value,
- })
- }
-}
+ let topic_id = Identifier::from_bytes(bytes.slice(position..))?;
+ position += topic_id.get_size_bytes().as_bytes_usize();
-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);
+ if bytes.len() <= position {
+ return Err(IggyError::InvalidCommand);
}
- bytes.put_u32_le(self.length);
- bytes.put_slice(&self.payload);
- bytes.freeze()
- }
- fn from_bytes(bytes: Bytes) -> Result<Self, IggyError> {
- if bytes.len() < 24 {
+ let partitioning = Partitioning::from_bytes(bytes.slice(position..))?;
+ position += partitioning.get_size_bytes().as_bytes_usize();
+
+ if bytes.len() < position + 4 {
return Err(IggyError::InvalidCommand);
}
- 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]
+ let messages_count = u32::from_le_bytes(
+ bytes
+ .slice(position..position + 4)
+ .as_ref()
.try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ .unwrap(),
);
- if payload_length == 0 {
- return Err(IggyError::EmptyMessagePayload);
- }
-
- 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);
- }
-
- Ok(Message {
- id,
- length: payload_length,
- payload,
- headers,
- })
- }
-}
-
-// 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)
- .map(|size| size + 24u64.into())
- .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(
- 8 + IGGY_BATCH_OVERHEAD as usize
- + stream_id_bytes.len()
- + topic_id_bytes.len()
- + key_bytes.len()
- + messages_size.as_bytes_usize(),
- );
- let metadata_len = key_bytes.len() + stream_id_bytes.len() + topic_id_bytes.len();
- let metadata_len = metadata_len as u32;
-
- bytes.put_slice(&metadata_len.to_le_bytes());
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_slice(&key_bytes);
-
- let header = IggyHeader::default();
- bytes.put_slice(&header.as_bytes());
- for message in messages {
- // TODO: create a writer method on the `Message` and in the future
- // once the `Message` struct is dropped on the `IggyMessage`.
- bytes.extend_from_slice(&0u32.to_le_bytes()); // offset_delta
- bytes.extend_from_slice(&0u32.to_le_bytes()); // timestamp_delta
- bytes.extend_from_slice(&message.id.to_le_bytes());
-
- let headers_len =
- IggyVarInt::from(header::get_headers_size_bytes(&message.headers).as_bytes_u64());
- let payload_len = IggyVarInt::from(message.length);
- payload_len.encode(&mut bytes);
- headers_len.encode(&mut bytes);
- bytes.extend_from_slice(&message.payload);
- if let Some(headers) = &message.headers {
- let headers_bytes = headers.to_bytes();
- bytes.put_slice(&headers_bytes);
- }
- }
-
- bytes.freeze()
-}
-
-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);
- }
-
- Ok(Message {
- id,
- length,
- payload,
- headers: None,
- })
- }
-}
-
-impl BytesSerializable for SendMessages {
- fn to_bytes(&self) -> Bytes {
- as_bytes(
- &self.stream_id,
- &self.topic_id,
- &self.partitioning,
- &self.messages,
- )
- }
-
- fn from_bytes(bytes: Bytes) -> Result<SendMessages, IggyError> {
- if bytes.len() < 11 {
- return Err(IggyError::InvalidCommand);
- }
+ position += 4;
- 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);
- }
+ let messages = bytes.slice(position..);
- let command = SendMessages {
+ Ok(SendMessages {
stream_id,
topic_id,
- partitioning: key,
+ partitioning,
+ messages_count,
messages,
- };
- Ok(command)
+ })
}
}
impl Display for SendMessages {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let count = self.messages_count;
write!(
f,
- "{}|{}|{}|batch_len:{}|batch_size:{}",
+ "{}|{}|{}|messages.len:{}|messages_size:{}",
self.stream_id,
self.topic_id,
self.partitioning,
- self.messages.len(),
- self.messages
- .iter()
- .map(Message::get_size_bytes)
- .sum::<IggyByteSize>(),
+ count,
+ self.messages.len()
)
}
}
-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 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"),
- }
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
- //TODO: Fix me, fix those tests.
- #[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);
- }
- }
+ // //TODO: Fix me, fix those tests.
+ // #[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() {
diff --git a/sdk/src/models/batch.rs b/sdk/src/models/batch copy.rs
similarity index 100%
rename from sdk/src/models/batch.rs
rename to sdk/src/models/batch copy.rs
diff --git a/sdk/src/models/header.rs b/sdk/src/models/header.rs
index 0adc8de9..4cdd9d04 100644
--- a/sdk/src/models/header.rs
+++ b/sdk/src/models/header.rs
@@ -658,11 +658,9 @@ impl BytesSerializable for HashMap<HeaderKey, HeaderValue> {
/// Returns the size in bytes of the specified headers.
pub fn get_headers_size_bytes(headers: &Option<HashMap<HeaderKey, HeaderValue>>) -> IggyByteSize {
- // Headers length field
let mut size = 0;
if let Some(headers) = headers {
for (key, value) in headers {
- // Key length + Key + Kind + Value length + Value
size += 4 + key.as_str().len() as u32 + 1 + 4 + value.value.len() as u32;
}
}
diff --git a/sdk/src/models/message.rs b/sdk/src/models/message.rs
deleted file mode 100644
index 7d6686b3..00000000
--- a/sdk/src/models/message.rs
+++ /dev/null
@@ -1,60 +0,0 @@
-use crate::models::header;
-use crate::models::header::{HeaderKey, HeaderValue};
-use crate::utils::byte_size::IggyByteSize;
-use crate::utils::sizeable::Sizeable;
-use serde_with::base64::Base64;
-use serde_with::serde_as;
-use std::collections::HashMap;
-
-pub const IGGY_MESSAGE_METADATA: u64 = 4 + 4 + 16; // offset_delta timestamp_delta + id
-
-/// The single message that is polled from the partition.
-/// It consists of the following fields:
-/// - `id`: the identifier of the message.
-/// - `offset`: offset
-/// - `timestamp`: timestamp
-/// - `payload`: the binary payload of the message.
-#[serde_as]
-#[derive(Default, Debug, serde::Serialize, serde::Deserialize)]
-pub struct IggyMessage {
- /// The identifier of the message.
- pub id: u128,
- /// The offset of the message.
- pub offset: u64,
- /// The timestamp of the message.
- pub timestamp: u64,
- /// The binary payload of the message.
- #[serde_as(as = "Base64")]
- pub payload: Vec<u8>,
- /// The optional headers of the message.
- pub headers: Option<HashMap<HeaderKey, HeaderValue>>,
-}
-
-impl std::fmt::Display for IggyMessage {
- 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))
- }
- }
-}
-
-impl Sizeable for IggyMessage {
- fn get_size_bytes(&self) -> IggyByteSize {
- // id + offset_delta + timestamp_delta + length + payload + headers
- let payload_len = IggyByteSize::from(self.payload.len() as u64);
- let headers_len = header::get_headers_size_bytes(&self.headers);
- let metadata_len = IggyByteSize::from(IGGY_MESSAGE_METADATA);
-
- payload_len + headers_len + metadata_len
- }
-}
diff --git a/sdk/src/models/messaging/message.rs b/sdk/src/models/messaging/message.rs
new file mode 100644
index 00000000..d3a1f5fb
--- /dev/null
+++ b/sdk/src/models/messaging/message.rs
@@ -0,0 +1,210 @@
+use super::message_header::{IggyMessageHeader, IGGY_MESSAGE_HEADER_SIZE};
+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_with::base64::Base64;
+use serde_with::serde_as;
+use std::collections::HashMap;
+use std::str::FromStr;
+
+/// The single message. It is exact format in which message is saved to / retrieved from the disk.
+#[serde_as]
+#[derive(Default, Debug, serde::Serialize, serde::Deserialize, PartialEq)]
+pub struct IggyMessage {
+ pub header: IggyMessageHeader,
+ #[serde_as(as = "Base64")]
+ pub payload: Bytes,
+ pub headers: Option<HashMap<HeaderKey, HeaderValue>>,
+}
+
+impl IggyMessage {
+ /// Create a message with payload
+ pub fn new(payload: Bytes) -> Self {
+ Self::builder().payload(payload).build()
+ }
+
+ /// Create a message with ID and payload
+ pub fn with_id(id: u128, payload: Bytes) -> Self {
+ Self::builder().id(id).payload(payload).build()
+ }
+
+ /// Start a builder for more complex configuration
+ pub fn builder() -> IggyMessageBuilder {
+ IggyMessageBuilder::new()
+ }
+
+ pub fn write_to_bytes_mut(&self, buf: &mut BytesMut) {
+ buf.put_slice(&self.header.to_bytes());
+ buf.put_slice(&self.payload);
+ if let Some(headers) = &self.headers {
+ buf.put_slice(&headers.to_bytes());
+ }
+ }
+}
+impl FromStr for IggyMessage {
+ type Err = IggyError;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ let payload = Bytes::from(s.as_bytes().to_vec());
+ Ok(IggyMessage::new(payload))
+ }
+}
+
+impl std::fmt::Display for IggyMessage {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let len = self.payload.len();
+
+ if len > 40 {
+ write!(
+ f,
+ "{}|{}...{}",
+ self.header.id,
+ String::from_utf8_lossy(&self.payload[..20]),
+ String::from_utf8_lossy(&self.payload[len - 20..])
+ )
+ } else {
+ write!(
+ f,
+ "{}|{}",
+ self.header.id,
+ String::from_utf8_lossy(&self.payload)
+ )
+ }
+ }
+}
+
+impl Sizeable for IggyMessage {
+ fn get_size_bytes(&self) -> IggyByteSize {
+ let payload_len = IggyByteSize::from(self.payload.len() as u64);
+ let headers_len = header::get_headers_size_bytes(&self.headers);
+ let metadata_len = IggyByteSize::from(IGGY_MESSAGE_HEADER_SIZE as u64);
+
+ payload_len + headers_len + metadata_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.headers {
+ bytes.put_slice(&headers.to_bytes());
+ }
+ bytes.freeze()
+ }
+
+ fn from_bytes(bytes: Bytes) -> Result<Self, IggyError> {
+ if bytes.len() < IGGY_MESSAGE_HEADER_SIZE as usize {
+ return Err(IggyError::InvalidCommand);
+ }
+ let mut position = 0;
+ let header =
+ IggyMessageHeader::from_bytes(bytes.slice(0..IGGY_MESSAGE_HEADER_SIZE as usize))?;
+
+ position += IGGY_MESSAGE_HEADER_SIZE as usize;
+ let payload = bytes.slice(position..position + header.payload_length as usize);
+ if payload.len() != header.payload_length as usize {
+ return Err(IggyError::InvalidMessagePayloadLength);
+ }
+
+ position += header.payload_length as usize;
+ let headers = if header.headers_length > 0 {
+ Some(HashMap::from_bytes(
+ bytes.slice(position..position + header.headers_length as usize),
+ )?)
+ } else {
+ None
+ };
+
+ Ok(IggyMessage {
+ header,
+ payload,
+ headers,
+ })
+ }
+}
+
+pub struct IggyMessageBuilder {
+ id: Option<u128>,
+ payload: Option<Bytes>,
+ headers: Option<HashMap<HeaderKey, HeaderValue>>,
+}
+
+impl IggyMessageBuilder {
+ pub fn new() -> Self {
+ Self {
+ id: None,
+ payload: None,
+ headers: None,
+ }
+ }
+
+ pub fn id(mut self, id: u128) -> Self {
+ self.id = Some(id);
+ self
+ }
+
+ pub fn payload(mut self, payload: Bytes) -> Self {
+ self.payload = Some(payload);
+ self
+ }
+
+ 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
+ }
+
+ pub fn headers(mut self, headers: impl Into<Option<HashMap<HeaderKey, HeaderValue>>>) -> Self {
+ self.headers = headers.into();
+ self
+ }
+
+ pub fn build(self) -> IggyMessage {
+ let payload = self.payload.unwrap_or_else(Bytes::new);
+ let id = self.id.unwrap_or_else(|| uuid::Uuid::new_v4().as_u128());
+
+ let header = IggyMessageHeader {
+ record_size: 0,
+ id,
+ offset: 0,
+ timestamp: 0,
+ origin_timestamp: IggyTimestamp::now().as_micros(),
+ headers_length: 0,
+ payload_length: payload.len() as u32,
+ checksum: 0,
+ };
+
+ IggyMessage {
+ header,
+ payload,
+ headers: self.headers,
+ }
+ }
+}
+
+// Convenience impl for conversion from common types
+impl From<String> for IggyMessage {
+ fn from(s: String) -> Self {
+ Self::new(Bytes::from(s))
+ }
+}
+
+impl From<&str> for IggyMessage {
+ fn from(s: &str) -> Self {
+ Self::new(Bytes::from(s.to_owned()))
+ }
+}
+
+impl From<Vec<u8>> for IggyMessage {
+ fn from(v: Vec<u8>) -> Self {
+ Self::new(Bytes::from(v))
+ }
+}
diff --git a/sdk/src/models/messaging/message_header.rs b/sdk/src/models/messaging/message_header.rs
new file mode 100644
index 00000000..28dfad01
--- /dev/null
+++ b/sdk/src/models/messaging/message_header.rs
@@ -0,0 +1,130 @@
+use bytes::{BufMut, Bytes, BytesMut};
+
+use crate::{
+ bytes_serializable::BytesSerializable,
+ error::IggyError,
+ utils::{byte_size::IggyByteSize, sizeable::Sizeable},
+};
+
+pub const IGGY_MESSAGE_HEADER_SIZE: u32 = 4 + 16 + 8 + 8 + 8 + 4 + 4 + 8;
+
+#[derive(Debug, serde::Serialize, serde::Deserialize, PartialEq, Default)]
+pub struct IggyMessageHeader {
+ /// Total size of message, including headers and payload
+ pub record_size: u32,
+
+ /// Message ID
+ pub id: u128,
+
+ /// Message offset
+ pub offset: u64,
+
+ /// Timestamp of the message after reception
+ pub timestamp: u64,
+
+ /// Timestamp taken on client side, just before sending the message
+ pub origin_timestamp: u64,
+
+ /// Size of headers section, in bytes
+ pub headers_length: u32,
+
+ /// Size of payload section, in bytes
+ pub payload_length: u32,
+
+ /// Checksum
+ pub checksum: u64,
+}
+
+impl Sizeable for IggyMessageHeader {
+ fn get_size_bytes(&self) -> IggyByteSize {
+ (IGGY_MESSAGE_HEADER_SIZE as u64).into()
+ }
+}
+
+impl BytesSerializable for IggyMessageHeader {
+ fn to_bytes(&self) -> Bytes {
+ let mut bytes = BytesMut::with_capacity(self.get_size_bytes().as_bytes_usize());
+ bytes.put_u32_le(self.record_size);
+ 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.headers_length);
+ bytes.put_u32_le(self.payload_length);
+ bytes.put_u64_le(self.checksum);
+ bytes.freeze()
+ }
+
+ fn from_bytes(bytes: Bytes) -> Result<Self, IggyError> {
+ if bytes.len() != IGGY_MESSAGE_HEADER_SIZE as usize {
+ return Err(IggyError::InvalidCommand);
+ }
+
+ // Read record_size (4 bytes): 0-4
+ let record_size = u32::from_le_bytes(
+ bytes[..4]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ // Read id (16 bytes): 4-20
+ let id = u128::from_le_bytes(
+ bytes[4..20]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ // Read offset (8 bytes): 20-28
+ let offset = u64::from_le_bytes(
+ bytes[20..28]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ // Read timestamp (8 bytes): 28-36
+ let timestamp = u64::from_le_bytes(
+ bytes[28..36]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ // Read origin_timestamp (8 bytes): 36-44
+ let origin_timestamp = u64::from_le_bytes(
+ bytes[36..44]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ // Read headers_length (4 bytes): 44-48
+ let headers_length = u32::from_le_bytes(
+ bytes[44..48]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ // Read payload_length (4 bytes): 48-52
+ let payload_length = u32::from_le_bytes(
+ bytes[48..52]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ // Read checksum (8 bytes): 52-60
+ let checksum = u64::from_le_bytes(
+ bytes[52..60]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ Ok(IggyMessageHeader {
+ record_size,
+ id,
+ offset,
+ timestamp,
+ origin_timestamp,
+ headers_length,
+ payload_length,
+ checksum,
+ })
+ }
+}
diff --git a/sdk/src/models/messaging/message_view.rs b/sdk/src/models/messaging/message_view.rs
new file mode 100644
index 00000000..8f50fbbe
--- /dev/null
+++ b/sdk/src/models/messaging/message_view.rs
@@ -0,0 +1,248 @@
+use super::message_header::{IggyMessageHeader, IGGY_MESSAGE_HEADER_SIZE};
+use crate::bytes_serializable::BytesSerializable;
+use crate::error::IggyError;
+use crate::models::header::{HeaderKey, HeaderValue};
+use crate::utils::byte_size::IggyByteSize;
+use crate::utils::sizeable::Sizeable;
+use crate::utils::timestamp::IggyTimestamp;
+use crate::utils::varint::IggyVarInt;
+use ::lending_iterator::prelude::*;
+use bytes::Bytes;
+use std::collections::HashMap;
+use std::ops::Range;
+
+// Re-export related message structs
+pub use super::message_view_mut::{IggyMessageViewMut, IggyMessageViewMutIterator};
+pub use super::messages::IggyMessages;
+pub use super::messages_mut::IggyMessagesMut;
+
+/// A zero-copy view of a message in a buffer
+#[derive(Debug, PartialEq)]
+pub struct IggyMessageView<'a> {
+ /// The buffer containing the message
+ buffer: &'a [u8],
+ /// The offset of the header within the buffer
+ header_offset: usize,
+ /// The offset of the payload within the buffer
+ payload_offset: usize,
+ /// The length of the payload
+ payload_length: u32,
+ /// The offset of the headers within the buffer
+ headers_offset: usize,
+ /// The length of the headers
+ headers_length: u32,
+}
+
+impl<'a> IggyMessageView<'a> {
+ /// Create a new message view from a buffer
+ ///
+ /// # Safety
+ /// The caller must ensure that the buffer contains a valid message at the given offset
+ pub fn new(buffer: &'a [u8], start_offset: usize) -> Result<Self, IggyError> {
+ if buffer.len() < start_offset + IGGY_MESSAGE_HEADER_SIZE as usize {
+ return Err(IggyError::InvalidCommand);
+ }
+
+ let header_slice = &buffer[start_offset..start_offset + IGGY_MESSAGE_HEADER_SIZE as usize];
+
+ // The message header format must match IggyMessageHeader layout
+ // Message header (60 bytes):
+ // - Record size (4 bytes): 0-4
+ // - Message ID (16 bytes): 4-20
+ // - Offset (8 bytes): 20-28
+ // - Timestamp (8 bytes): 28-36
+ // - Origin timestamp (8 bytes): 36-44
+ // - Headers length (4 bytes): 44-48
+ // - Payload length (4 bytes): 48-52
+ // - Checksum (8 bytes): 52-60
+
+ let headers_length = u32::from_le_bytes(
+ header_slice[44..48]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ let payload_length = u32::from_le_bytes(
+ header_slice[48..52]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ const MAX_REASONABLE_SIZE: u32 = 100 * 1024 * 1024;
+ if payload_length > MAX_REASONABLE_SIZE || headers_length > MAX_REASONABLE_SIZE {
+ tracing::error!(
+ "Unreasonable message size detected - payload: {} bytes, headers: {} bytes",
+ payload_length,
+ headers_length
+ );
+ return Err(IggyError::InvalidMessagePayloadLength);
+ }
+
+ let header_offset = start_offset;
+ let payload_offset = start_offset + IGGY_MESSAGE_HEADER_SIZE as usize;
+ let headers_offset = payload_offset + payload_length as usize;
+
+ let total_size =
+ IGGY_MESSAGE_HEADER_SIZE as usize + payload_length as usize + headers_length as usize;
+ if buffer.len() < start_offset + total_size {
+ tracing::error!(
+ "2 Invalid message payload buffer.len(): {}, start_offset: {}, total_size: {}",
+ buffer.len(),
+ start_offset,
+ total_size
+ );
+ return Err(IggyError::InvalidMessagePayloadLength);
+ }
+
+ Ok(Self {
+ buffer,
+ header_offset,
+ payload_offset,
+ payload_length,
+ headers_offset,
+ headers_length,
+ })
+ }
+
+ /// Get the message header
+ pub fn header(&self) -> Result<IggyMessageHeader, IggyError> {
+ let header_end = self.header_offset + IGGY_MESSAGE_HEADER_SIZE as usize;
+ let header_bytes = &self.buffer[self.header_offset..header_end];
+
+ // Convert to Bytes for compatibility with existing code
+ let bytes = Bytes::copy_from_slice(header_bytes);
+ IggyMessageHeader::from_bytes(bytes)
+ }
+
+ /// Get the message ID
+ pub fn id(&self) -> u128 {
+ let id_bytes = &self.buffer[self.header_offset + 4..self.header_offset + 20];
+ u128::from_le_bytes(id_bytes.try_into().unwrap())
+ }
+
+ /// Get the message offset
+ pub fn offset(&self) -> u64 {
+ let offset_bytes = &self.buffer[self.header_offset + 20..self.header_offset + 28];
+ u64::from_le_bytes(offset_bytes.try_into().unwrap())
+ }
+
+ /// Get the message timestamp
+ pub fn timestamp(&self) -> u64 {
+ let timestamp_bytes = &self.buffer[self.header_offset + 28..self.header_offset + 36];
+ u64::from_le_bytes(timestamp_bytes.try_into().unwrap())
+ }
+
+ /// Get the message origin timestamp
+ pub fn origin_timestamp(&self) -> u64 {
+ let timestamp_bytes = &self.buffer[self.header_offset + 36..self.header_offset + 44];
+ u64::from_le_bytes(timestamp_bytes.try_into().unwrap())
+ }
+
+ /// Get the payload as a slice
+ pub fn payload(&self) -> &'a [u8] {
+ &self.buffer[self.payload_offset..self.payload_offset + self.payload_length as usize]
+ }
+
+ /// Get the headers as bytes
+ pub fn headers_bytes(&self) -> &'a [u8] {
+ if self.headers_length == 0 {
+ &[]
+ } else {
+ &self.buffer[self.headers_offset..self.headers_offset + self.headers_length as usize]
+ }
+ }
+
+ /// Parse and get the headers as a HashMap
+ pub fn headers(&self) -> Result<Option<HashMap<HeaderKey, HeaderValue>>, IggyError> {
+ if self.headers_length == 0 {
+ return Ok(None);
+ }
+
+ let headers_bytes = self.headers_bytes();
+ let headers_map = parse_headers(headers_bytes)?;
+ Ok(Some(headers_map))
+ }
+
+ /// Get the total size of the message in bytes
+ pub fn size(&self) -> usize {
+ IGGY_MESSAGE_HEADER_SIZE as usize
+ + self.payload_length as usize
+ + self.headers_length as usize
+ }
+
+ /// Get the total range this message occupies in the buffer
+ pub fn range(&self) -> Range<usize> {
+ self.header_offset..(self.header_offset + self.size())
+ }
+}
+
+/// 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 = Result<IggyMessageView<'a>, IggyError>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.position >= self.buffer.len() {
+ return None;
+ }
+
+ let result = IggyMessageView::new(self.buffer, self.position);
+ match &result {
+ Ok(view) => {
+ self.position += view.size();
+ }
+ Err(_) => {}
+ }
+
+ Some(result)
+ }
+}
+
+/// Parse headers from raw bytes
+fn parse_headers(bytes: &[u8]) -> Result<HashMap<HeaderKey, HeaderValue>, IggyError> {
+ let mut result = HashMap::new();
+ let mut position = 0;
+
+ while position < bytes.len() {
+ let (key_len_size, key_len) = IggyVarInt::decode(&bytes[position..]);
+ position += key_len_size;
+
+ if position + key_len as usize > bytes.len() {
+ return Err(IggyError::InvalidCommand);
+ }
+
+ let key_bytes = &bytes[position..position + key_len as usize];
+ let key_str = std::str::from_utf8(key_bytes).map_err(|_| IggyError::InvalidCommand)?;
+ let key = HeaderKey::new(key_str)?;
+ position += key_len as usize;
+
+ let (value_len_size, value_len) = IggyVarInt::decode(&bytes[position..]);
+ position += value_len_size;
+
+ if position + value_len as usize > bytes.len() {
+ return Err(IggyError::InvalidCommand);
+ }
+
+ let value_bytes = &bytes[position..position + value_len as usize];
+ let bytes_value = Bytes::copy_from_slice(value_bytes);
+ let value = HeaderValue::from_raw(&bytes_value)?;
+ position += value_len as usize;
+
+ result.insert(key, value);
+ }
+
+ Ok(result)
+}
diff --git a/sdk/src/models/messaging/message_view_mut.rs b/sdk/src/models/messaging/message_view_mut.rs
new file mode 100644
index 00000000..cea1d775
--- /dev/null
+++ b/sdk/src/models/messaging/message_view_mut.rs
@@ -0,0 +1,155 @@
+use super::message_header::IGGY_MESSAGE_HEADER_SIZE;
+use crate::error::IggyError;
+use ::lending_iterator::prelude::*;
+use std::ops::Range;
+
+/// A mutable view of a message for in-place modifications
+#[derive(Debug)]
+pub struct IggyMessageViewMut<'a> {
+ /// The buffer containing the message
+ buffer: &'a mut [u8],
+ /// The offset of the header within the buffer
+ header_offset: u32,
+ /// The offset of the payload within the buffer
+ payload_offset: u32,
+ /// The length of the payload
+ payload_length: u32,
+ /// The length of the headers
+ headers_length: u32,
+}
+
+impl<'a> IggyMessageViewMut<'a> {
+ /// Create a new mutable message view from a buffer
+ pub fn new(buffer: &'a mut [u8], start_offset: u32) -> Result<Self, IggyError> {
+ let buffer_len = buffer.len() as u32;
+ if buffer_len < start_offset + IGGY_MESSAGE_HEADER_SIZE {
+ return Err(IggyError::InvalidCommand);
+ }
+
+ let header_bytes =
+ &buffer[start_offset as usize..(start_offset + IGGY_MESSAGE_HEADER_SIZE) as usize];
+
+ // The message header format must match IggyMessageHeader layout
+ // Message header (60 bytes):
+ // - Record size (4 bytes): 0-4
+ // - Message ID (16 bytes): 4-20
+ // - Offset (8 bytes): 20-28
+ // - Timestamp (8 bytes): 28-36
+ // - Origin timestamp (8 bytes): 36-44
+ // - Headers length (4 bytes): 44-48
+ // - Payload length (4 bytes): 48-52
+ // - Checksum (8 bytes): 52-60
+
+ let headers_length = u32::from_le_bytes(
+ header_bytes[44..48]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ let payload_length = u32::from_le_bytes(
+ header_bytes[48..52]
+ .try_into()
+ .map_err(|_| IggyError::InvalidNumberEncoding)?,
+ );
+
+ const MAX_REASONABLE_SIZE: u32 = 100 * 1024 * 1024;
+ if payload_length > MAX_REASONABLE_SIZE || headers_length > MAX_REASONABLE_SIZE {
+ tracing::error!(
+ "Unreasonable message size detected - payload: {} bytes, headers: {} bytes",
+ payload_length,
+ headers_length
+ );
+ return Err(IggyError::InvalidMessagePayloadLength);
+ }
+
+ let header_offset = start_offset;
+ let payload_offset = start_offset + IGGY_MESSAGE_HEADER_SIZE;
+
+ let total_size = IGGY_MESSAGE_HEADER_SIZE + payload_length + headers_length;
+ if buffer_len < start_offset + total_size {
+ tracing::error!(
+ "1 Invalid message payload length: {}, expected: {}",
+ buffer_len - start_offset,
+ total_size
+ );
+ return Err(IggyError::InvalidMessagePayloadLength);
+ }
+
+ Ok(Self {
+ buffer,
+ header_offset,
+ payload_offset,
+ payload_length,
+ headers_length,
+ })
+ }
+
+ /// Update the offset in the header
+ pub fn update_offset(&mut self, offset: u64) {
+ let offset_position = self.header_offset + 20;
+ let bytes = offset.to_le_bytes();
+ self.buffer[offset_position as usize..(offset_position + 8) as usize]
+ .copy_from_slice(&bytes);
+ }
+
+ /// Update the timestamp in the header
+ pub fn update_timestamp(&mut self, timestamp: u64) {
+ let timestamp_position = self.header_offset + 28;
+ let bytes = timestamp.to_le_bytes();
+ self.buffer[timestamp_position as usize..(timestamp_position + 8) as usize]
+ .copy_from_slice(&bytes);
+ }
+
+ /// Get a mutable reference to the payload
+ pub fn payload_mut(&mut self) -> &mut [u8] {
+ &mut self.buffer
+ [self.payload_offset as usize..(self.payload_offset + self.payload_length) as usize]
+ }
+
+ /// Get the range this message occupies in the buffer
+ pub fn range(&self) -> Range<usize> {
+ self.header_offset as usize..(self.header_offset as usize + self.size())
+ }
+
+ /// Get the size of the message in bytes
+ pub fn size(&self) -> usize {
+ IGGY_MESSAGE_HEADER_SIZE as usize
+ + self.payload_length as usize
+ + self.headers_length as usize
+ }
+}
+
+/// Iterator over mutable message views in a buffer
+pub struct IggyMessageViewMutIterator<'a> {
+ buffer: &'a mut [u8],
+ position: usize,
+}
+
+impl<'a> IggyMessageViewMutIterator<'a> {
+ pub fn new(buffer: &'a mut [u8]) -> Self {
+ Self {
+ buffer,
+ position: 0,
+ }
+ }
+}
+
+#[gat]
+impl LendingIterator for IggyMessageViewMutIterator<'_> {
+ type Item<'next> = Result<IggyMessageViewMut<'next>, IggyError>;
+
+ fn next(&mut self) -> Option<Self::Item<'_>> {
+ if self.position >= self.buffer.len() {
+ return None;
+ }
+
+ let buffer_slice = &mut self.buffer[self.position..];
+ let result = IggyMessageViewMut::new(buffer_slice, 0);
+
+ if let Ok(view) = &result {
+ self.position += view.size();
+ }
+
+ Some(result)
+ }
+}
diff --git a/sdk/src/models/messaging/messages.rs b/sdk/src/models/messaging/messages.rs
new file mode 100644
index 00000000..0db05b6e
--- /dev/null
+++ b/sdk/src/models/messaging/messages.rs
@@ -0,0 +1,91 @@
+use super::{message_view::IggyMessageViewIterator, IggyMessage, IggyMessagesMut};
+use crate::bytes_serializable::BytesSerializable;
+use crate::error::IggyError;
+use crate::utils::byte_size::IggyByteSize;
+use crate::utils::sizeable::Sizeable;
+use bytes::{Bytes, BytesMut};
+use serde::{Deserialize, Serialize};
+
+/// An immutable messages container that holds a buffer of messages
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+pub struct IggyMessages {
+ /// The number of messages in the buffer
+ #[serde(skip)]
+ count: u32,
+ /// The buffer containing the messages
+ buffer: Bytes,
+}
+
+impl IggyMessages {
+ /// Create a new messages container from a buffer
+ pub fn new(buffer: Bytes) -> Self {
+ Self { buffer, count: 0 }
+ }
+
+ pub fn from_messages(messages: &[IggyMessage]) -> Self {
+ let mut buffer = BytesMut::new();
+ for message in messages {
+ buffer.extend_from_slice(&message.to_bytes());
+ }
+ Self::new(buffer.freeze())
+ }
+
+ /// Create iterator over messages
+ pub fn iter(&self) -> IggyMessageViewIterator {
+ IggyMessageViewIterator::new(&self.buffer)
+ }
+
+ /// Get the number of messages
+ pub fn count(&self) -> u32 {
+ self.count
+ }
+
+ /// Get the total size of all messages in bytes
+ pub fn size(&self) -> u32 {
+ self.buffer.len() as u32
+ }
+
+ /// Get access to the underlying buffer
+ pub fn buffer(&self) -> &[u8] {
+ &self.buffer
+ }
+}
+
+impl BytesSerializable for IggyMessages {
+ fn to_bytes(&self) -> Bytes {
+ self.buffer.clone()
+ }
+
+ fn from_bytes(bytes: Bytes) -> Result<Self, IggyError>
+ where
+ Self: Sized,
+ {
+ let mut messages_count = 0;
+ let iterator = IggyMessageViewIterator::new(&bytes);
+
+ for result in iterator {
+ result?;
+ messages_count += 1;
+ }
+
+ Ok(Self {
+ buffer: bytes,
+ count: messages_count,
+ })
+ }
+}
+
+impl Sizeable for IggyMessages {
+ fn get_size_bytes(&self) -> IggyByteSize {
+ IggyByteSize::from(self.buffer.len() as u64)
+ }
+}
+
+impl From<IggyMessagesMut> for IggyMessages {
+ fn from(messages: IggyMessagesMut) -> Self {
+ let count = messages.count();
+ let buffer = messages.into_inner().freeze();
+
+ Self { buffer, count }
+ }
+}
diff --git a/sdk/src/models/messaging/messages_mut.rs b/sdk/src/models/messaging/messages_mut.rs
new file mode 100644
index 00000000..a9448301
--- /dev/null
+++ b/sdk/src/models/messaging/messages_mut.rs
@@ -0,0 +1,100 @@
+use super::{
+ message_view::IggyMessageViewMutIterator, IggyMessage, IggyMessageViewIterator, IggyMessages,
+};
+use crate::bytes_serializable::BytesSerializable;
+use crate::error::IggyError;
+use crate::utils::byte_size::IggyByteSize;
+use crate::utils::sizeable::Sizeable;
+use bytes::{BufMut, Bytes, BytesMut};
+use serde::{Deserialize, Serialize};
+
+/// A container for mutable messages
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+pub struct IggyMessagesMut {
+ /// The number of messages in the buffer
+ #[serde(skip)]
+ count: u32,
+ /// The buffer containing the messages
+ buffer: BytesMut,
+}
+
+impl BytesSerializable for IggyMessagesMut {
+ fn to_bytes(&self) -> Bytes {
+ self.buffer.clone().freeze()
+ }
+
+ fn from_bytes(bytes: Bytes) -> Result<Self, IggyError>
+ where
+ Self: Sized,
+ {
+ Ok(Self {
+ buffer: BytesMut::from(&bytes[..]),
+ count: 0,
+ })
+ }
+}
+
+impl Sizeable for IggyMessagesMut {
+ fn get_size_bytes(&self) -> IggyByteSize {
+ IggyByteSize::from(self.buffer.len() as u64)
+ }
+}
+
+impl IggyMessagesMut {
+ /// Create a new messages container from a buffer
+ pub fn new(buffer: BytesMut) -> Self {
+ Self { buffer, count: 0 }
+ }
+
+ /// Create a new messages container from a slice of messages
+ pub fn from_messages(messages: &[IggyMessage], messages_size: u32) -> Self {
+ let mut buffer = BytesMut::with_capacity(messages_size as usize);
+ for message in messages {
+ buffer.extend_from_slice(&message.to_bytes());
+ }
+ Self::new(buffer)
+ }
+
+ /// Extends the messages container with another set of mutable messages by consuming them
+ pub fn extend(&mut self, messages: IggyMessagesMut) {
+ let count = messages.count();
+ let buffer = messages.into_inner();
+ self.buffer.put(buffer);
+ self.count += count;
+ }
+
+ /// Sets the capacity of the messages container
+ pub fn set_capacity(&mut self, capacity: u32) {
+ self.buffer.reserve(capacity as usize);
+ }
+
+ /// Create a lending iterator over mutable messages
+ pub fn iter_mut(&mut self) -> IggyMessageViewMutIterator {
+ IggyMessageViewMutIterator::new(&mut self.buffer)
+ }
+
+ /// Create iterator over messages
+ pub fn iter(&self) -> IggyMessageViewIterator {
+ IggyMessageViewIterator::new(&self.buffer)
+ }
+
+ /// Get the number of messages
+ pub fn count(&self) -> u32 {
+ self.count
+ }
+
+ /// Set the message count
+ pub fn set_count(&mut self, count: u32) {
+ self.count = count;
+ }
+
+ /// Get the total size of all messages in bytes
+ pub fn size(&self) -> u32 {
+ self.buffer.len() as u32
+ }
+
+ /// Get the buffer
+ pub fn into_inner(self) -> BytesMut {
+ self.buffer
+ }
+}
diff --git a/sdk/src/models/messaging/mod.rs b/sdk/src/models/messaging/mod.rs
new file mode 100644
index 00000000..887f43a2
--- /dev/null
+++ b/sdk/src/models/messaging/mod.rs
@@ -0,0 +1,13 @@
+mod message;
+mod message_header;
+mod message_view;
+mod message_view_mut;
+mod messages;
+mod messages_mut;
+
+pub use message::IggyMessage;
+pub use message_header::IggyMessageHeader;
+pub use message_view::{IggyMessageView, IggyMessageViewIterator};
+pub use message_view_mut::{IggyMessageViewMut, IggyMessageViewMutIterator};
+pub use messages::IggyMessages;
+pub use messages_mut::IggyMessagesMut;
diff --git a/sdk/src/models/mod.rs b/sdk/src/models/mod.rs
index 4b5b4eb3..36f81a78 100644
--- a/sdk/src/models/mod.rs
+++ b/sdk/src/models/mod.rs
@@ -1,10 +1,10 @@
-pub mod batch;
+// pub mod batch;
pub mod client_info;
pub mod consumer_group;
pub mod consumer_offset_info;
pub mod header;
pub mod identity_info;
-pub mod message;
+mod messaging;
pub mod partition;
pub mod permissions;
pub mod personal_access_token;
@@ -14,3 +14,8 @@ pub mod stream;
pub mod topic;
pub mod user_info;
pub mod user_status;
+
+pub use messaging::{
+ IggyMessage, IggyMessageHeader, IggyMessageView, IggyMessageViewIterator, IggyMessageViewMut,
+ IggyMessageViewMutIterator, IggyMessages, IggyMessagesMut,
+};
diff --git a/sdk/src/partitioner.rs b/sdk/src/partitioner.rs
index 8d2145c4..8fd66e47 100644
--- a/sdk/src/partitioner.rs
+++ b/sdk/src/partitioner.rs
@@ -1,6 +1,6 @@
use crate::error::IggyError;
use crate::identifier::Identifier;
-use crate::messages::send_messages::Message;
+use crate::prelude::*;
use std::fmt::Debug;
/// The trait represent the logic responsible for calculating the partition ID and is used by the `IggyClient`.
@@ -10,6 +10,6 @@ pub trait Partitioner: Send + Sync + Debug {
&self,
stream_id: &Identifier,
topic_id: &Identifier,
- messages: &[Message],
+ messages: &[IggyMessage],
) -> Result<u32, IggyError>;
}
diff --git a/sdk/src/prelude.rs b/sdk/src/prelude.rs
new file mode 100644
index 00000000..eb386f63
--- /dev/null
+++ b/sdk/src/prelude.rs
@@ -0,0 +1,31 @@
+//! Prelude module for the Iggy SDK.
+//!
+//! This module re-exports the most common types, traits, and functions
+//! from the Iggy SDK to make them easier to import and use.
+//!
+//! # Examples
+//!
+//! ```
+//! use iggy::prelude::*;
+//! ```
+
+// TODO(hubcio): finish this
+
+pub use crate::bytes_serializable::BytesSerializable;
+pub use crate::client::Client;
+pub use crate::error::IggyError;
+pub use crate::identifier::Identifier;
+pub use crate::messages::{
+ FlushUnsavedBuffer, Partitioning, PollMessages, PollingKind, PollingStrategy, SendMessages,
+};
+pub use crate::models::partition::Partition;
+pub use crate::models::stream::Stream;
+pub use crate::models::topic::Topic;
+pub use crate::models::{
+ IggyMessage, IggyMessageHeader, IggyMessageView, IggyMessageViewIterator, IggyMessageViewMut,
+ IggyMessageViewMutIterator, IggyMessages, IggyMessagesMut,
+};
+pub use crate::utils::byte_size::IggyByteSize;
+pub use crate::utils::sizeable::Sizeable;
+pub use crate::utils::timestamp::IggyTimestamp;
+pub use crate::validatable::Validatable;
diff --git a/sdk/src/stream_builder/config/config_iggy_consumer.rs b/sdk/src/stream_builder/config/config_iggy_consumer.rs
index 3cb4d1fe..166446cc 100644
--- a/sdk/src/stream_builder/config/config_iggy_consumer.rs
+++ b/sdk/src/stream_builder/config/config_iggy_consumer.rs
@@ -1,12 +1,11 @@
-use bon::Builder;
-
use crate::clients::consumer::{AutoCommit, AutoCommitWhen};
use crate::consumer::ConsumerKind;
use crate::error::IggyError;
use crate::identifier::Identifier;
-use crate::messages::poll_messages::PollingStrategy;
+use crate::messages::PollingStrategy;
use crate::utils::crypto::EncryptorKind;
use crate::utils::duration::IggyDuration;
+use bon::Builder;
use std::str::FromStr;
use std::sync::Arc;
diff --git a/sdk/src/stream_builder/config/config_iggy_producer.rs b/sdk/src/stream_builder/config/config_iggy_producer.rs
index ea2afbd0..506c02f1 100644
--- a/sdk/src/stream_builder/config/config_iggy_producer.rs
+++ b/sdk/src/stream_builder/config/config_iggy_producer.rs
@@ -1,10 +1,9 @@
-use bon::Builder;
-
use crate::error::IggyError;
use crate::identifier::Identifier;
-use crate::messages::send_messages::Partitioning;
+use crate::messages::Partitioning;
use crate::utils::crypto::EncryptorKind;
use crate::utils::duration::IggyDuration;
+use bon::Builder;
use std::str::FromStr;
use std::sync::Arc;
diff --git a/sdk/src/tcp/client.rs b/sdk/src/tcp/client.rs
index 5e3b023c..e7952779 100644
--- a/sdk/src/tcp/client.rs
+++ b/sdk/src/tcp/client.rs
@@ -21,7 +21,7 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader, BufWriter};
use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
use tokio::net::TcpStream;
use tokio::sync::Mutex;
-use tokio::time::sleep;
+use tokio::time::{sleep, Instant};
use tokio_rustls::{TlsConnector, TlsStream};
use tracing::{error, info, trace, warn};
@@ -623,13 +623,26 @@ impl TcpClient {
let mut stream = self.stream.lock().await;
if let Some(stream) = stream.as_mut() {
let payload_length = payload.len() + REQUEST_INITIAL_BYTES_LENGTH;
- trace!("Sending a TCP request with code: {code}");
+ trace!("Sending a TCP request of size {payload_length} with code: {code}");
+ let now = Instant::now();
stream.write(&(payload_length as u32).to_le_bytes()).await?;
+ let payload_len_write_time = Instant::now();
stream.write(&code.to_le_bytes()).await?;
+ let code_write_time = Instant::now();
stream.write(&payload).await?;
+ let payload_write_time = Instant::now();
stream.flush().await?;
+ let flush_time = Instant::now();
trace!("Sent a TCP request with code: {code}, waiting for a response...");
+ trace!(
+ "Payload length write time: {} us, code write time: {} us, payload write time: {} us, flush time: {} us",
+ (payload_len_write_time - now).as_micros(),
+ (code_write_time - payload_len_write_time).as_micros(),
+ (payload_write_time - code_write_time).as_micros(),
+ (flush_time - payload_write_time).as_micros(),
+ );
+ let now = Instant::now();
let mut response_buffer = [0u8; RESPONSE_INITIAL_BYTES_LENGTH];
let read_bytes = stream.read(&mut response_buffer).await.map_err(|error| {
error!(
@@ -639,6 +652,7 @@ impl TcpClient {
);
IggyError::Disconnected
})?;
+ trace!("Response read time: {} us", now.elapsed().as_micros());
if read_bytes != RESPONSE_INITIAL_BYTES_LENGTH {
error!("Received an invalid or empty response.");
diff --git a/server/src/binary/command.rs b/server/src/binary/command.rs
index 9e044c7c..c6c1114d 100644
--- a/server/src/binary/command.rs
+++ b/server/src/binary/command.rs
@@ -16,15 +16,13 @@ use iggy::consumer_groups::leave_consumer_group::LeaveConsumerGroup;
use iggy::consumer_offsets::delete_consumer_offset::DeleteConsumerOffset;
use iggy::consumer_offsets::get_consumer_offset::GetConsumerOffset;
use iggy::consumer_offsets::store_consumer_offset::StoreConsumerOffset;
-use iggy::error::IggyError;
-use iggy::messages::flush_unsaved_buffer::FlushUnsavedBuffer;
-use iggy::messages::poll_messages::PollMessages;
use iggy::partitions::create_partitions::CreatePartitions;
use iggy::partitions::delete_partitions::DeletePartitions;
use iggy::personal_access_tokens::create_personal_access_token::CreatePersonalAccessToken;
use iggy::personal_access_tokens::delete_personal_access_token::DeletePersonalAccessToken;
use iggy::personal_access_tokens::get_personal_access_tokens::GetPersonalAccessTokens;
use iggy::personal_access_tokens::login_with_personal_access_token::LoginWithPersonalAccessToken;
+use iggy::prelude::*;
use iggy::streams::create_stream::CreateStream;
use iggy::streams::delete_stream::DeleteStream;
use iggy::streams::get_stream::GetStream;
@@ -52,7 +50,6 @@ use iggy::users::login_user::LoginUser;
use iggy::users::logout_user::LogoutUser;
use iggy::users::update_permissions::UpdatePermissions;
use iggy::users::update_user::UpdateUser;
-use iggy::{bytes_serializable::BytesSerializable, messages::send_messages::SendMessages};
use strum::EnumString;
use tracing::{debug, error};
diff --git a/server/src/binary/handlers/messages/flush_unsaved_buffer_handler.rs b/server/src/binary/handlers/messages/flush_unsaved_buffer_handler.rs
index bc6ab6aa..0ea456fc 100644
--- a/server/src/binary/handlers/messages/flush_unsaved_buffer_handler.rs
+++ b/server/src/binary/handlers/messages/flush_unsaved_buffer_handler.rs
@@ -5,8 +5,7 @@ use crate::streaming::session::Session;
use crate::streaming::systems::system::SharedSystem;
use anyhow::Result;
use error_set::ErrContext;
-use iggy::error::IggyError;
-use iggy::messages::flush_unsaved_buffer::FlushUnsavedBuffer;
+use iggy::prelude::*;
use tracing::{debug, instrument};
impl ServerCommandHandler for FlushUnsavedBuffer {
diff --git a/server/src/binary/handlers/messages/poll_messages_handler.rs b/server/src/binary/handlers/messages/poll_messages_handler.rs
index b4e6e8c0..d089fb59 100644
--- a/server/src/binary/handlers/messages/poll_messages_handler.rs
+++ b/server/src/binary/handlers/messages/poll_messages_handler.rs
@@ -7,9 +7,7 @@ use crate::streaming::systems::messages::PollingArgs;
use crate::streaming::systems::system::SharedSystem;
use anyhow::Result;
use error_set::ErrContext;
-use iggy::error::IggyError;
-use iggy::messages::poll_messages::PollMessages;
-use iggy::models::batch::IGGY_BATCH_OVERHEAD;
+use iggy::prelude::*;
use std::io::IoSlice;
use tracing::debug;
@@ -25,45 +23,46 @@ impl ServerCommandHandler for PollMessages {
session: &Session,
system: &SharedSystem,
) -> Result<(), IggyError> {
- debug!("session: {session}, command: {self}");
+ todo!();
+ // debug!("session: {session}, command: {self}");
- let system = system.read().await;
- let result = system
- .poll_messages(
- session,
- &self.consumer,
- &self.stream_id,
- &self.topic_id,
- self.partition_id,
- PollingArgs::new(self.strategy, self.count, self.auto_commit),
- )
- .await
- .with_error_context(|error| format!(
- "{COMPONENT} (error: {error}) - failed to poll messages for consumer: {}, stream_id: {}, topic_id: {}, partition_id: {:?}, session: {session}.",
- self.consumer, self.stream_id, self.topic_id, self.partition_id
- ))?;
- let length = result
- .slices
- .iter()
- .map(|s| s.range.len() as u32)
- .sum::<u32>()
- + IGGY_BATCH_OVERHEAD as u32;
- let length = length.to_le_bytes();
- // Adding 1 for the header and 2 for the prefix required by `send_ok_response`.
- let mut slices = Vec::with_capacity(1 + result.slices.len() + 2);
- let header = result.header.as_bytes();
- slices.push(IoSlice::new(&header));
- for slice in result.slices.iter() {
- // Ergh... it is kinda ugly that we have to index this way, rather than just passing `Range`,
- // but borrow checker gets really anal about it, since the range is field of `IggyBatchSlice`
- // that we borrow inside of that loop.
- // It is fixable by decoupling `Range` from `Bytes`, but w/e.
- let slice = &slice.bytes[slice.range.start..slice.range.end];
- slices.push(IoSlice::new(slice));
- }
+ // let system = system.read().await;
+ // let result = system
+ // .poll_messages(
+ // session,
+ // &self.consumer,
+ // &self.stream_id,
+ // &self.topic_id,
+ // self.partition_id,
+ // PollingArgs::new(self.strategy, self.count, self.auto_commit),
+ // )
+ // .await
+ // .with_error_context(|error| format!(
+ // "{COMPONENT} (error: {error}) - failed to poll messages for consumer: {}, stream_id: {}, topic_id: {}, partition_id: {:?}, session: {session}.",
+ // self.consumer, self.stream_id, self.topic_id, self.partition_id
+ // ))?;
+ // let length = result
+ // .slices
+ // .iter()
+ // .map(|s| s.range.len() as u32)
+ // .sum::<u32>()
+ // + IGGY_BATCH_OVERHEAD as u32;
+ // let length = length.to_le_bytes();
+ // // Adding 1 for the header and 2 for the prefix required by `send_ok_response`.
+ // let mut slices = Vec::with_capacity(1 + result.slices.len() + 2);
+ // let header = result.header.as_bytes();
+ // slices.push(IoSlice::new(&header));
+ // for slice in result.slices.iter() {
+ // // Ergh... it is kinda ugly that we have to index this way, rather than just passing `Range`,
+ // // but borrow checker gets really anal about it, since the range is field of `IggyBatchSlice`
+ // // that we borrow inside of that loop.
+ // // It is fixable by decoupling `Range` from `Bytes`, but w/e.
+ // let slice = &slice.bytes[slice.range.start..slice.range.end];
+ // slices.push(IoSlice::new(slice));
+ // }
- sender.send_ok_response_vectored(&length, slices).await?;
- Ok(())
+ // sender.send_ok_response_vectored(&length, slices).await?;
+ // Ok(())
}
}
diff --git a/server/src/binary/handlers/messages/send_messages_handler.rs b/server/src/binary/handlers/messages/send_messages_handler.rs
index 770ac721..ee26f723 100644
--- a/server/src/binary/handlers/messages/send_messages_handler.rs
+++ b/server/src/binary/handlers/messages/send_messages_handler.rs
@@ -1,17 +1,17 @@
+use std::time::Instant;
+
use crate::binary::command::{BinaryServerCommand, ServerCommandHandler};
-use crate::binary::{handlers::messages::COMPONENT, sender::SenderKind};
+use crate::binary::sender::SenderKind;
use crate::streaming::session::Session;
use crate::streaming::systems::system::SharedSystem;
use anyhow::Result;
-use bytes::{Bytes, BytesMut};
-use error_set::ErrContext;
+use bytes::{Buf, BytesMut};
use iggy::bytes_serializable::BytesSerializable;
use iggy::error::IggyError;
use iggy::identifier::Identifier;
-use iggy::messages::send_messages::{Partitioning, SendMessages};
-use iggy::models::batch::{IggyHeader, IggyMutableBatch, IGGY_BATCH_OVERHEAD};
+use iggy::prelude::*;
use iggy::utils::sizeable::Sizeable;
-use tracing::{debug, instrument};
+use tracing::instrument;
impl ServerCommandHandler for SendMessages {
fn code(&self) -> u32 {
@@ -26,49 +26,64 @@ impl ServerCommandHandler for SendMessages {
partitioning = %self.partitioning
))]
async fn handle(
- self,
+ mut self,
sender: &mut SenderKind,
length: u32,
session: &Session,
system: &SharedSystem,
) -> Result<(), IggyError> {
- let mut metadata_len_bytes = [0u8; 4];
- sender.read(&mut metadata_len_bytes).await?;
- let metadata_len = u32::from_le_bytes(metadata_len_bytes);
-
- let mut metadata = vec![0u8; metadata_len as usize];
- sender.read(&mut metadata).await?;
- let metadata = Bytes::from(metadata);
-
- let stream_id = Identifier::from_bytes(metadata.clone())?;
+ let function_start = Instant::now();
+ let length = length - 4;
+ let mut buffer = BytesMut::with_capacity(length as usize);
+ unsafe {
+ buffer.set_len(length as usize);
+ }
+ sender.read(&mut buffer).await?;
+ let mut offset = 0;
+ let stream_id = Identifier::from_raw_bytes(buffer.chunk())?;
+ offset += stream_id.get_size_bytes().as_bytes_usize();
let mut position = stream_id.get_size_bytes().as_bytes_usize();
- let topic_id = Identifier::from_bytes(metadata.slice(position..))?;
- position += topic_id.get_size_bytes().as_bytes_usize();
- let partitioning = Partitioning::from_bytes(metadata.slice(position..))?;
-
- let mut header_bytes = [0u8; IGGY_BATCH_OVERHEAD as usize];
- sender.read(&mut header_bytes).await?;
- let header = IggyHeader::from_bytes(&header_bytes);
-
- let batch_length = length - metadata_len - IGGY_BATCH_OVERHEAD as u32 - 4 - 4; // TODO(hubcio): magic numbers
- let mut batch_buffer = BytesMut::with_capacity(batch_length as _);
- unsafe { batch_buffer.set_len(batch_length as _) };
- sender.read(&mut batch_buffer).await?;
- let batch = IggyMutableBatch::new(header, batch_buffer);
-
- debug!("session: {session}, command: {self}");
-
+ buffer.advance(position);
+ let topic_id = Identifier::from_raw_bytes(buffer.chunk())?;
+ offset += topic_id.get_size_bytes().as_bytes_usize();
+ position = topic_id.get_size_bytes().as_bytes_usize();
+ buffer.advance(position);
+ let partitioning = Partitioning::from_raw_bytes(buffer.chunk())?;
+ offset += partitioning.get_size_bytes().as_bytes_usize();
+ position = partitioning.get_size_bytes().as_bytes_usize();
+ buffer.advance(position);
+ let messages_count = buffer.get_u32_le();
+ let _metadata = buffer.split_to(offset);
+ let mut messages = IggyMessagesMut::new(buffer);
+ messages.set_count(messages_count);
+ let now = Instant::now();
let system = system.read().await;
+ let lock_time = now.elapsed().as_micros();
+ let now = Instant::now();
system
- .append_messages(session, &stream_id, &topic_id, &partitioning, batch, None)
- .await
- .with_error_context(|error| {
- format!(
- "{COMPONENT} (error: {error}) - failed to append messages, session: {session}"
- )
- })?;
-
+ .append_messages(
+ session,
+ &stream_id,
+ &topic_id,
+ &partitioning,
+ messages,
+ None,
+ )
+ .await?;
+ self.stream_id = stream_id;
+ self.topic_id = topic_id;
+ self.partitioning = partitioning;
+ let append_time = now.elapsed().as_micros();
+ let now = Instant::now();
sender.send_empty_ok_response().await?;
+ let send_time = now.elapsed().as_micros();
+ tracing::error!(
+ "append_messages() took {} µs, system.read() took {} µs, send_empty_ok_response() took {} µs, entire function took {} µs",
+ append_time,
+ lock_time,
+ send_time,
+ function_start.elapsed().as_micros()
+ );
Ok(())
}
}
diff --git a/server/src/http/messages.rs b/server/src/http/messages.rs
index 9ae2bf4f..4a30b1e4 100644
--- a/server/src/http/messages.rs
+++ b/server/src/http/messages.rs
@@ -12,8 +12,7 @@ use axum::{Extension, Json, Router};
use error_set::ErrContext;
use iggy::consumer::Consumer;
use iggy::identifier::Identifier;
-use iggy::messages::poll_messages::PollMessages;
-use iggy::messages::send_messages::SendMessages;
+use iggy::prelude::*;
use iggy::validatable::Validatable;
use std::sync::Arc;
use tracing::instrument;
diff --git a/server/src/streaming/batching/appendable_batch_info.rs b/server/src/streaming/batching/appendable_batch_info.rs
deleted file mode 100644
index 3f3161e3..00000000
--- a/server/src/streaming/batching/appendable_batch_info.rs
+++ /dev/null
@@ -1,16 +0,0 @@
-use iggy::utils::byte_size::IggyByteSize;
-
-#[derive(Debug)]
-pub struct AppendableBatchInfo {
- pub batch_size: IggyByteSize,
- pub partition_id: u32,
-}
-
-impl AppendableBatchInfo {
- pub fn new(batch_size: IggyByteSize, partition_id: u32) -> Self {
- Self {
- batch_size,
- partition_id,
- }
- }
-}
diff --git a/server/src/streaming/batching/batch_accumulator.rs b/server/src/streaming/batching/batch_accumulator.rs
deleted file mode 100644
index 5f60308f..00000000
--- a/server/src/streaming/batching/batch_accumulator.rs
+++ /dev/null
@@ -1,104 +0,0 @@
-use iggy::models::batch::{IggyBatch, IggyHeader, IggyMutableBatch, IGGY_BATCH_OVERHEAD};
-use iggy::utils::byte_size::IggyByteSize;
-use iggy::utils::timestamp::IggyTimestamp;
-use std::sync::Arc;
-
-use crate::streaming::segments::IggyBatchFetchResult;
-
-#[derive(Debug, Default)]
-pub struct BatchAccumulator {
- base_offset: u64,
- base_timestamp: u64,
- current_size: IggyByteSize,
- current_offset: u64,
- current_timestamp: u64,
- leading_header: Option<IggyHeader>,
- batches: Vec<IggyMutableBatch>,
-}
-
-impl BatchAccumulator {
- pub fn coalesce_batch(&mut self, current_offset: u64, mut batch: IggyMutableBatch) -> u32 {
- let header = self.leading_header.get_or_insert_with(|| {
- let mut header = batch.header;
- let base_timestamp = IggyTimestamp::now().as_micros();
- self.base_offset = current_offset;
- self.base_timestamp = base_timestamp;
- self.current_offset = current_offset;
- self.current_timestamp = base_timestamp;
-
- header.base_offset = current_offset;
- header.base_timestamp = base_timestamp;
- header
- });
-
- let batch_size = batch.get_size();
- let messages_count =
- batch.update_header_and_messages_offsets_and_timestamps(current_offset, header);
- self.current_size += batch_size;
- self.current_offset = header.base_offset + header.last_offset_delta as u64;
- self.current_timestamp = header.base_timestamp + header.last_timestamp_delta as u64;
- self.batches.push(batch);
-
- messages_count
- }
-
- pub fn get_messages_by_offset(&self, start_offset: u64, end_offset: u64) -> Vec<IggyBatch> {
- let start_idx = self.batches.partition_point(|batch| {
- let last_offset = batch.header.base_offset + batch.header.last_offset_delta as u64;
- last_offset < start_offset
- });
- let end_idx = self.batches.partition_point(|batch| {
- let last_offset = batch.header.base_offset + batch.header.last_offset_delta as u64;
- last_offset <= end_offset
- });
- let batches = self.batches[start_idx..end_idx]
- .iter()
- .map(|batch| IggyBatch::new(batch.header, batch.batch.clone().freeze()))
- .collect();
- batches
- }
-
- pub fn get_messages_by_timestamp(&self, start_timestamp: u64, count: usize) -> Vec<Arc<()>> {
- //TODO: Fix me
- /*
- let start_idx = self
- .messages
- .partition_point(|msg| msg.timestamp < start_timestamp);
- let end_idx = std::cmp::min(start_idx + count, self.messages.len());
- self.messages[start_idx..end_idx].to_vec()
- */
- todo!()
- }
-
- pub fn is_empty(&self) -> bool {
- self.batches.is_empty()
- }
-
- pub fn unsaved_messages_count(&self) -> usize {
- self.batches
- .iter()
- .map(|b| b.header)
- .map(|h| (h.last_offset_delta + 1) as usize)
- .sum()
- }
-
- pub fn batch_max_offset(&self) -> u64 {
- self.current_offset
- }
-
- pub fn batch_max_timestamp(&self) -> u64 {
- self.current_timestamp
- }
-
- pub fn batch_base_offset(&self) -> u64 {
- self.base_offset
- }
-
- pub fn batch_base_timestamp(&self) -> u64 {
- self.base_timestamp
- }
-
- pub fn materialize(self) -> (IggyHeader, Vec<IggyMutableBatch>) {
- (self.leading_header.unwrap(), self.batches)
- }
-}
diff --git a/server/src/streaming/batching/mod.rs b/server/src/streaming/batching/mod.rs
deleted file mode 100644
index f625181a..00000000
--- a/server/src/streaming/batching/mod.rs
+++ /dev/null
@@ -1,2 +0,0 @@
-pub mod appendable_batch_info;
-pub mod batch_accumulator;
diff --git a/server/src/streaming/mod.rs b/server/src/streaming/mod.rs
index 5630487c..d4b5b06a 100644
--- a/server/src/streaming/mod.rs
+++ b/server/src/streaming/mod.rs
@@ -1,4 +1,3 @@
-pub mod batching;
pub mod cache;
pub mod clients;
mod deduplication;
diff --git a/server/src/streaming/partitions/messages.rs b/server/src/streaming/partitions/messages.rs
index f926cc9e..e2fde77d 100644
--- a/server/src/streaming/partitions/messages.rs
+++ b/server/src/streaming/partitions/messages.rs
@@ -1,14 +1,12 @@
-use crate::streaming::batching::appendable_batch_info::AppendableBatchInfo;
use crate::streaming::partitions::partition::Partition;
use crate::streaming::partitions::COMPONENT;
use crate::streaming::polling_consumer::PollingConsumer;
use crate::streaming::segments::*;
use error_set::ErrContext;
use iggy::error::IggyError;
-use iggy::messages::send_messages::Message;
-use iggy::models::batch::IggyMutableBatch;
+use iggy::models::IggyMessages;
use iggy::utils::timestamp::IggyTimestamp;
-use iggy::{confirmation::Confirmation, models::batch::IggyBatch};
+use iggy::{confirmation::Confirmation, models::IggyMessagesMut};
use std::sync::{atomic::Ordering, Arc};
use tracing::{trace, warn};
@@ -70,7 +68,7 @@ impl Partition {
&self,
start_offset: u64,
count: u32,
- ) -> Result<IggyBatchFetchResult, IggyError> {
+ ) -> Result<IggyMessages, IggyError> {
trace!(
"Getting messages for start offset: {start_offset} for partition: {}, current offset: {}...",
self.partition_id,
@@ -104,12 +102,12 @@ impl Partition {
}
// Retrieves the first messages (up to a specified count).
- pub async fn get_first_messages(&self, count: u32) -> Result<IggyBatchFetchResult, IggyError> {
+ pub async fn get_first_messages(&self, count: u32) -> Result<IggyMessages, IggyError> {
self.get_messages_by_offset(0, count).await
}
// Retrieves the last messages (up to a specified count).
- pub async fn get_last_messages(&self, count: u32) -> Result<IggyBatchFetchResult, IggyError> {
+ pub async fn get_last_messages(&self, count: u32) -> Result<IggyMessages, IggyError> {
let mut requested_count = count as u64;
if requested_count > self.current_offset + 1 {
requested_count = self.current_offset + 1
@@ -124,7 +122,7 @@ impl Partition {
&self,
consumer: PollingConsumer,
count: u32,
- ) -> Result<IggyBatchFetchResult, IggyError> {
+ ) -> Result<IggyMessages, IggyError> {
let (consumer_offsets, consumer_id) = match consumer {
PollingConsumer::Consumer(consumer_id, _) => (&self.consumer_offsets, consumer_id),
PollingConsumer::ConsumerGroup(group_id, _) => (&self.consumer_group_offsets, group_id),
@@ -192,32 +190,32 @@ impl Partition {
segments: Vec<&Segment>,
offset: u64,
count: u32,
- ) -> Result<Vec<IggyBatchSlice>, IggyError> {
- //TODO: Figure out how to flatten those IggyBatchFetchResults.
- let mut results = Vec::new();
- let mut remaining_count = count;
- for segment in segments {
- if remaining_count == 0 {
- break;
- }
- let slices = segment
- .get_messages_by_offset(offset, remaining_count)
- .await
- .with_error_context(|error| {
- format!(
- "{COMPONENT} (error: {error}) - failed to get messages from segment, segment: {}, \
- offset: {}, count: {}",
- segment, offset, remaining_count
- )
- })?;
- let messages_count = slices
- .iter()
- .map(|slice| slice.header.last_offset_delta)
- .sum();
- remaining_count = remaining_count.saturating_sub(messages_count);
- results.extend(slices);
- }
- Ok(results)
+ ) -> Result<IggyMessages, IggyError> {
+ todo!()
+ // let mut results = Vec::new();
+ // let mut remaining_count = count;
+ // for segment in segments {
+ // if remaining_count == 0 {
+ // break;
+ // }
+ // let slices = segment
+ // .get_messages_by_offset(offset, remaining_count)
+ // .await
+ // .with_error_context(|error| {
+ // format!(
+ // "{COMPONENT} (error: {error}) - failed to get messages from segment, segment: {}, \
+ // offset: {}, count: {}",
+ // segment, offset, remaining_count
+ // )
+ // })?;
+ // let messages_count = slices
+ // .iter()
+ // .map(|slice| slice.header.last_offset_delta)
+ // .sum();
+ // remaining_count = remaining_count.saturating_sub(messages_count);
+ // results.extend(slices);
+ // }
+ // Ok(results)
}
// Tries to retrieve messages from the in-memory cache.
@@ -361,8 +359,7 @@ impl Partition {
pub async fn append_messages(
&mut self,
- appendable_batch_info: AppendableBatchInfo,
- batch: IggyMutableBatch,
+ messages: IggyMessagesMut,
confirmation: Option<Confirmation>,
) -> Result<(), IggyError> {
{
@@ -380,8 +377,7 @@ impl Partition {
}
}
- let mut batch = batch;
- let batch_size = appendable_batch_info.batch_size;
+ let messages_size = messages.size();
let current_offset = if !self.should_increment_offset {
0
} else {
@@ -422,18 +418,17 @@ impl Partition {
*/
// Why are we even doing it this way ? XD
- // What are those scopes
+ // What are those scope
let messages_count = {
let last_segment = self.segments.last_mut().ok_or(IggyError::SegmentNotFound)?;
- let messages_count = last_segment
- .append_batch(current_offset, batch)
+ last_segment
+ .append_batch(current_offset, messages)
.await
.with_error_context(|error| {
format!(
"{COMPONENT} (error: {error}) - failed to append batch into last segment: {last_segment}",
)
- })?;
- messages_count
+ })?
};
let last_offset = current_offset + messages_count as u64 - 1;
if self.should_increment_offset {
diff --git a/server/src/streaming/partitions/mod.rs b/server/src/streaming/partitions/mod.rs
index 16c1f7d5..9280384e 100644
--- a/server/src/streaming/partitions/mod.rs
+++ b/server/src/streaming/partitions/mod.rs
@@ -1,6 +1,3 @@
-use bytes::Bytes;
-use iggy::messages::send_messages;
-
pub mod consumer_offsets;
pub mod messages;
pub mod partition;
@@ -9,20 +6,3 @@ pub mod segments;
pub mod storage;
pub const COMPONENT: &str = "STREAMING_PARTITIONS";
-
-#[allow(dead_code)]
-fn create_messages() -> Vec<send_messages::Message> {
- vec![
- create_message(1, "message 1"),
- create_message(2, "message 2"),
- create_message(3, "message 3"),
- create_message(2, "message 3.2"),
- create_message(1, "message 1.2"),
- create_message(3, "message 3.3"),
- ]
-}
-
-fn create_message(id: u128, payload: &str) -> send_messages::Message {
- let payload = Bytes::from(payload.to_string());
- send_messages::Message::new(Some(id), payload, None)
-}
diff --git a/server/src/streaming/partitions/storage.rs b/server/src/streaming/partitions/storage.rs
index 3753ea51..a251be85 100644
--- a/server/src/streaming/partitions/storage.rs
+++ b/server/src/streaming/partitions/storage.rs
@@ -1,6 +1,5 @@
use crate::compat::index_rebuilding::index_rebuilder::IndexRebuilder;
use crate::state::system::PartitionState;
-use crate::streaming::batching::batch_accumulator::BatchAccumulator;
use crate::streaming::partitions::partition::{ConsumerOffset, Partition};
use crate::streaming::partitions::COMPONENT;
use crate::streaming::persistence::persister::PersisterKind;
diff --git a/server/src/streaming/segments/fetch_result.rs b/server/src/streaming/segments/fetch_result.rs
deleted file mode 100644
index aa48b4db..00000000
--- a/server/src/streaming/segments/fetch_result.rs
+++ /dev/null
@@ -1,42 +0,0 @@
-use bytes::Bytes;
-use iggy::models::batch::IggyHeader;
-use std::ops::Range;
-
-#[derive(Default)]
-pub struct IggyBatchSlice {
- pub range: Range<usize>,
- pub header: IggyHeader,
- pub bytes: Bytes,
-}
-
-impl IggyBatchSlice {
- pub fn new(range: Range<usize>, header: IggyHeader, bytes: Bytes) -> Self {
- Self {
- range,
- header,
- bytes,
- }
- }
-}
-
-#[derive(Default)]
-pub struct IggyBatchFetchResult {
- pub header: IggyHeader,
- pub slices: Vec<IggyBatchSlice>,
-}
-
-impl From<Vec<IggyBatchSlice>> for IggyBatchFetchResult {
- fn from(slices: Vec<IggyBatchSlice>) -> Self {
- if slices.is_empty() {
- return Default::default();
- }
- let header = slices[0].header;
- IggyBatchFetchResult::new(header, slices)
- }
-}
-
-impl IggyBatchFetchResult {
- pub fn new(header: IggyHeader, slices: Vec<IggyBatchSlice>) -> Self {
- Self { header, slices }
- }
-}
diff --git a/server/src/streaming/segments/logs/mod.rs b/server/src/streaming/segments/logs/mod.rs
deleted file mode 100644
index 74c57b06..00000000
--- a/server/src/streaming/segments/logs/mod.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-mod log_reader;
-mod log_writer;
-mod persister_task;
-
-pub use log_reader::SegmentLogReader;
-pub use log_writer::SegmentLogWriter;
-pub use persister_task::PersisterTask;
diff --git a/server/src/streaming/segments/logs/log_reader.rs b/server/src/streaming/segments/messages/messages_reader.rs
similarity index 65%
rename from server/src/streaming/segments/logs/log_reader.rs
rename to server/src/streaming/segments/messages/messages_reader.rs
index 9227fe2d..a7363b50 100644
--- a/server/src/streaming/segments/logs/log_reader.rs
+++ b/server/src/streaming/segments/messages/messages_reader.rs
@@ -3,7 +3,7 @@ use bytes::{Bytes, BytesMut};
use error_set::ErrContext;
use iggy::{
error::IggyError,
- models::batch::{IggyBatch, IggyHeader, IGGY_BATCH_OVERHEAD},
+ models::IggyMessages,
utils::{byte_size::IggyByteSize, timestamp::IggyTimestamp},
};
use std::{
@@ -23,13 +23,13 @@ use tracing::{error, trace, warn};
/// A dedicated struct for reading from the log file.
#[derive(Debug)]
-pub struct SegmentLogReader {
+pub struct MessagesLogReader {
file_path: String,
file: Arc<File>,
log_size_bytes: Arc<AtomicU64>,
}
-impl SegmentLogReader {
+impl MessagesLogReader {
/// Opens the log file in read mode.
pub async fn new(file_path: &str, log_size_bytes: Arc<AtomicU64>) -> Result<Self, IggyError> {
let file = OpenOptions::new()
@@ -78,40 +78,41 @@ impl SegmentLogReader {
index_range: &IndexRange,
start_offset: u64,
end_offset: u64,
- ) -> Result<Vec<IggyBatch>, IggyError> {
- let mut file_size = self.file_size();
- // TODO: Fix me
- /*
- if file_size == 0 {
- trace!("Log file {} is empty.", self.file_path);
- return Ok(Vec::new());
- }
- */
+ ) -> Result<IggyMessages, IggyError> {
+ todo!()
+ // let mut file_size = self.file_size();
+ // // TODO: Fix me
+ // /*
+ // if file_size == 0 {
+ // trace!("Log file {} is empty.", self.file_path);
+ // return Ok(Vec::new());
+ // }
+ // */
- let mut position = index_range.start.position as u64;
- let mut batches = Vec::new();
- let mut last_batch_to_read = false;
+ // let mut position = index_range.start.position as u64;
+ // let mut batches = Vec::new();
+ // let mut last_batch_to_read = false;
- while !last_batch_to_read && position < file_size {
- file_size = self.file_size();
- match self.maybe_read_next_batch(position, file_size).await? {
- Some((batch, bytes_read)) => {
- position += bytes_read;
- let last_offset_in_batch =
- batch.header.base_offset + batch.header.last_offset_delta as u64;
- if last_offset_in_batch >= end_offset as u64 || position >= file_size {
- last_batch_to_read = true;
- }
- batches.push(batch);
- }
- None => {
- break;
- }
- }
- }
- //TODO: Fix me
- //trace!("Loaded {} message batches.", batches);
- Ok(batches)
+ // while !last_batch_to_read && position < file_size {
+ // file_size = self.file_size();
+ // match self.maybe_read_next_batch(position, file_size).await? {
+ // Some((batch, bytes_read)) => {
+ // position += bytes_read;
+ // let last_offset_in_batch =
+ // batch.header.base_offset + batch.header.last_offset_delta as u64;
+ // if last_offset_in_batch >= end_offset as u64 || position >= file_size {
+ // last_batch_to_read = true;
+ // }
+ // batches.push(batch);
+ // }
+ // None => {
+ // break;
+ // }
+ // }
+ // }
+ // //TODO: Fix me
+ // //trace!("Loaded {} message batches.", batches);
+ // Ok(batches)
}
// TODO: This one is most likely not needed anymore.
@@ -237,60 +238,61 @@ impl SegmentLogReader {
&self,
position: u64,
file_size: u64,
- ) -> Result<Option<(IggyBatch, u64)>, IggyError> {
- let batch_header_size = IGGY_BATCH_OVERHEAD;
- if position + batch_header_size > file_size {
- return Ok(None);
- }
+ ) -> Result<Option<IggyMessages>, IggyError> {
+ todo!()
+ // let batch_header_size = IGGY_BATCH_OVERHEAD;
+ // if position + batch_header_size > file_size {
+ // return Ok(None);
+ // }
- let header_buf = match self.read_at(position, batch_header_size).await {
- Ok(buf) => buf,
- Err(error) if error.kind() == ErrorKind::UnexpectedEof => return Ok(None),
- Err(error) => {
- error!(
- "Error reading batch header at position {} in file {}: {error}",
- position, self.file_path
- );
- return Err(IggyError::CannotReadBatchBaseOffset);
- }
- };
- if header_buf.len() < batch_header_size as usize {
- warn!(
- "Cannot read batch header at position {} in file {}. Possibly truncated.",
- position, self.file_path
- );
- return Ok(None);
- }
- let header = IggyHeader::from_bytes(&header_buf);
- let batch_length = header.batch_length as usize;
- let batch_position = position + batch_header_size;
- if batch_position + batch_length as u64 > file_size {
- warn!(
- "It's not possible to read the full batch payload ({} bytes) at position {} in file {} of size {}. Possibly truncated.",
- batch_length, batch_position, self.file_path, file_size
- );
- return Ok(None);
- }
+ // let header_buf = match self.read_at(position, batch_header_size).await {
+ // Ok(buf) => buf,
+ // Err(error) if error.kind() == ErrorKind::UnexpectedEof => return Ok(None),
+ // Err(error) => {
+ // error!(
+ // "Error reading batch header at position {} in file {}: {error}",
+ // position, self.file_path
+ // );
+ // return Err(IggyError::CannotReadBatchBaseOffset);
+ // }
+ // };
+ // if header_buf.len() < batch_header_size as usize {
+ // warn!(
+ // "Cannot read batch header at position {} in file {}. Possibly truncated.",
+ // position, self.file_path
+ // );
+ // return Ok(None);
+ // }
+ // let header = IggyHeader::from_bytes(&header_buf);
+ // let batch_length = header.batch_length as usize;
+ // let batch_position = position + batch_header_size;
+ // if batch_position + batch_length as u64 > file_size {
+ // warn!(
+ // "It's not possible to read the full batch payload ({} bytes) at position {} in file {} of size {}. Possibly truncated.",
+ // batch_length, batch_position, self.file_path, file_size
+ // );
+ // return Ok(None);
+ // }
- let batch_bytes = match self
- .read_bytes_at(batch_position, batch_length as u64)
- .await
- {
- Ok(buf) => buf,
- Err(error) if error.kind() == ErrorKind::UnexpectedEof => return Ok(None),
- Err(error) => {
- error!(
- "Error reading batch payload at position {} in file {}: {error}",
- batch_position, self.file_path
- );
- return Err(IggyError::CannotReadBatchPayload);
- }
- };
+ // let batch_bytes = match self
+ // .read_bytes_at(batch_position, batch_length as u64)
+ // .await
+ // {
+ // Ok(buf) => buf,
+ // Err(error) if error.kind() == ErrorKind::UnexpectedEof => return Ok(None),
+ // Err(error) => {
+ // error!(
+ // "Error reading batch payload at position {} in file {}: {error}",
+ // batch_position, self.file_path
+ // );
+ // return Err(IggyError::CannotReadBatchPayload);
+ // }
+ // };
- let bytes_read = batch_header_size + batch_length as u64;
- let batch = IggyBatch::new(header, batch_bytes);
+ // let bytes_read = batch_header_size + batch_length as u64;
+ // let batch = IggyBatch::new(header, batch_bytes);
- Ok(Some((batch, bytes_read)))
+ // Ok(Some((batch, bytes_read)))
}
fn file_size(&self) -> u64 {
diff --git a/server/src/streaming/segments/logs/log_writer.rs b/server/src/streaming/segments/messages/messages_writer.rs
similarity index 74%
rename from server/src/streaming/segments/logs/log_writer.rs
rename to server/src/streaming/segments/messages/messages_writer.rs
index 5b66c1ba..7b274b80 100644
--- a/server/src/streaming/segments/logs/log_writer.rs
+++ b/server/src/streaming/segments/messages/messages_writer.rs
@@ -3,7 +3,7 @@ use error_set::ErrContext;
use iggy::{
confirmation::Confirmation,
error::IggyError,
- models::batch::{IggyBatch, IggyHeader, IggyMutableBatch, IGGY_BATCH_OVERHEAD},
+ models::{IggyMessages, IggyMessagesMut},
utils::{byte_size::IggyByteSize, duration::IggyDuration, sizeable::Sizeable},
};
use std::{
@@ -22,7 +22,7 @@ use tracing::{error, trace};
/// A dedicated struct for writing to the log file.
#[derive(Debug)]
-pub struct SegmentLogWriter {
+pub struct MessagesLogWriter {
file_path: String,
/// Holds the file for synchronous writes; when asynchronous persistence is enabled, this will be None.
file: Option<File>,
@@ -32,7 +32,7 @@ pub struct SegmentLogWriter {
fsync: bool,
}
-impl SegmentLogWriter {
+impl MessagesLogWriter {
/// Opens the log file in write mode.
///
/// If the server confirmation is set to `NoWait`, the file handle is transferred to the
@@ -92,20 +92,20 @@ impl SegmentLogWriter {
})
}
- /// Append a message batch to the log file.
+ /// Append a messages to the log file.
pub async fn save_batches(
&mut self,
- header: IggyHeader,
- batches: Vec<IggyMutableBatch>,
+ messages: IggyMessages,
confirmation: Confirmation,
) -> Result<IggyByteSize, IggyError> {
- let batch_size = IGGY_BATCH_OVERHEAD + header.batch_length;
+ let messages_size = messages.size();
match confirmation {
Confirmation::Wait => {
- self.write_batch(header, batches).await?;
- self.log_size_bytes.fetch_add(batch_size, Ordering::AcqRel);
+ self.write_batch(messages).await?;
+ self.log_size_bytes
+ .fetch_add(messages_size as u64, Ordering::AcqRel);
trace!(
- "Written batch of size {batch_size} bytes to log file: {}",
+ "Written batch of size {messages_size} bytes to log file: {}",
self.file_path
);
if self.fsync {
@@ -114,7 +114,7 @@ impl SegmentLogWriter {
}
Confirmation::NoWait => {
if let Some(task) = &self.persister_task {
- task.persist(batch_size, header, batches).await;
+ task.persist(messages).await;
} else {
panic!(
"Confirmation::NoWait is used, but LogPersisterTask is not set for log file: {}",
@@ -124,35 +124,19 @@ impl SegmentLogWriter {
}
}
- Ok(batch_size.into())
+ Ok(IggyByteSize::from(messages_size as u64))
}
/// Write a batch of bytes to the log file and return the new file position.
- async fn write_batch(
- &mut self,
- header: IggyHeader,
- batches: Vec<IggyMutableBatch>,
- ) -> Result<(), IggyError> {
+ async fn write_batch(&mut self, messages: IggyMessages) -> Result<(), IggyError> {
if let Some(ref mut file) = self.file {
- let mut slices = Vec::new();
-
- let header = header.as_bytes();
- slices.push(IoSlice::new(&header));
- batches.iter().for_each(|b| {
- slices.push(IoSlice::new(&b.batch));
- });
+ file.write_all(messages.buffer())
+ .await
+ .with_error_context(|error| {
+ format!("Failed to log to file: {}. {error}", self.file_path)
+ })
+ .map_err(|_| IggyError::CannotWriteToFile)?;
- let slices = &mut slices.as_mut_slice();
- while slices.len() > 0 {
- let written = file
- .write_vectored(slices)
- .await
- .with_error_context(|error| {
- format!("Failed to log to file: {}. {error}", self.file_path)
- })
- .map_err(|_| IggyError::CannotWriteToFile)?;
- IoSlice::advance_slices(slices, written);
- }
Ok(())
} else {
error!("File handle is not available for synchronous write.");
diff --git a/server/src/streaming/segments/messages/mod.rs b/server/src/streaming/segments/messages/mod.rs
new file mode 100644
index 00000000..1c4aef8d
--- /dev/null
+++ b/server/src/streaming/segments/messages/mod.rs
@@ -0,0 +1,7 @@
+mod messages_reader;
+mod messages_writer;
+mod persister_task;
+
+pub use messages_reader::MessagesLogReader;
+pub use messages_writer::MessagesLogWriter;
+pub use persister_task::PersisterTask;
diff --git a/server/src/streaming/segments/logs/persister_task.rs b/server/src/streaming/segments/messages/persister_task.rs
similarity index 86%
rename from server/src/streaming/segments/logs/persister_task.rs
rename to server/src/streaming/segments/messages/persister_task.rs
index f0bf15df..b4ac5acb 100644
--- a/server/src/streaming/segments/logs/persister_task.rs
+++ b/server/src/streaming/segments/messages/persister_task.rs
@@ -1,9 +1,5 @@
use flume::{unbounded, Receiver};
-use iggy::{
- error::IggyError,
- models::batch::{IggyBatch, IggyHeader, IggyMutableBatch, IGGY_BATCH_OVERHEAD},
- utils::duration::IggyDuration,
-};
+use iggy::{error::IggyError, models::IggyMessages, utils::duration::IggyDuration};
use std::{
io::IoSlice,
sync::{
@@ -18,7 +14,7 @@ use tracing::{error, trace, warn};
#[derive(Debug)]
/// A command to the persister task.
enum PersisterTaskCommand {
- WriteRequest(u64, IggyHeader, Vec<IggyMutableBatch>),
+ WriteRequest(IggyMessages),
Shutdown,
}
@@ -63,17 +59,10 @@ impl PersisterTask {
}
/// Sends the batch bytes to the persister task (fire-and-forget).
- pub async fn persist(
- &self,
- batch_size: u64,
- header: IggyHeader,
- batches: Vec<IggyMutableBatch>,
- ) {
+ pub async fn persist(&self, messages: IggyMessages) {
if let Err(e) = self
.sender
- .send_async(PersisterTaskCommand::WriteRequest(
- batch_size, header, batches,
- ))
+ .send_async(PersisterTaskCommand::WriteRequest(messages))
.await
{
error!(
@@ -183,13 +172,11 @@ impl PersisterTask {
) {
while let Ok(request) = receiver.recv_async().await {
match request {
- PersisterTaskCommand::WriteRequest(batch_size, header, batches) => {
+ PersisterTaskCommand::WriteRequest(messages) => {
match Self::write_with_retries(
&mut file,
&file_path,
- batch_size,
- header,
- batches,
+ messages,
fsync,
max_retries,
retry_delay,
@@ -197,7 +184,7 @@ impl PersisterTask {
.await
{
Ok(bytes_written) => {
- log_file_size.fetch_add(bytes_written, Ordering::AcqRel);
+ log_file_size.fetch_add(bytes_written as u64, Ordering::AcqRel);
}
Err(e) => {
error!(
@@ -226,22 +213,11 @@ impl PersisterTask {
async fn write_with_retries(
file: &mut File,
file_path: &str,
- batch_size: u64,
- header: IggyHeader,
- batches: Vec<IggyMutableBatch>,
+ messages: IggyMessages,
fsync: bool,
max_retries: u32,
retry_delay: IggyDuration,
- ) -> Result<u64, IggyError> {
- // TODO: Fix me, this logic is repeated, maybe could be encapsulated inside of the batch_accumulator
- // that yields accumulated batches and leading header.
- let mut slices = Vec::new();
- let header = header.as_bytes();
- slices.push(IoSlice::new(&header));
- batches.iter().for_each(|b| {
- slices.push(IoSlice::new(&b.batch));
- });
-
+ ) -> Result<u32, IggyError> {
let mut attempts = 0;
// TODO: This "retry" logic should be rewritten.
// There are certain kind of errors whom retyring is considered harmful, for example fsync failure
@@ -249,12 +225,14 @@ impl PersisterTask {
// There are few errors which are worth retrying such as LSE (Latent sector error), as the file system
// might be able to realocate a new sector for the data and recover, but not every file system supports that.
// In general this topic should be furthered researched rather than just naively retry when the write fails.
+
loop {
- match file.write_vectored(&slices).await {
+ let messages_size = messages.size();
+ match file.write_all(messages.buffer()).await {
Ok(_) => {
if fsync {
match file.sync_all().await {
- Ok(_) => return Ok(batch_size),
+ Ok(_) => return Ok(messages_size),
Err(e) => {
attempts += 1;
error!(
@@ -264,7 +242,7 @@ impl PersisterTask {
}
}
} else {
- return Ok(batch_size);
+ return Ok(messages_size);
}
}
Err(e) => {
diff --git a/server/src/streaming/segments/messages_accumulator.rs b/server/src/streaming/segments/messages_accumulator.rs
new file mode 100644
index 00000000..9bcca073
--- /dev/null
+++ b/server/src/streaming/segments/messages_accumulator.rs
@@ -0,0 +1,94 @@
+use bytes::BytesMut;
+use iggy::models::{IggyMessages, IggyMessagesMut};
+use iggy::utils::byte_size::IggyByteSize;
+use iggy::utils::timestamp::IggyTimestamp;
+use std::mem;
+
+/// A container that accumulates messages before they are written to disk
+#[derive(Debug, Default)]
+pub struct MessagesAccumulator {
+ /// Base offset of the first message
+ base_offset: u64,
+ /// Base timestamp of the first message
+ base_timestamp: u64,
+ /// Current size of all accumulated messages
+ current_size: IggyByteSize,
+ /// Current maximum offset
+ current_offset: u64,
+ /// Current maximum timestamp
+ current_timestamp: u64,
+ /// A single IggyMessagesMut instance containing all messages
+ messages: Option<IggyMessagesMut>,
+ /// Number of messages in the accumulator
+ messages_count: u32,
+}
+
+impl MessagesAccumulator {
+ /// Coalesces a batch of messages into the accumulator
+ /// Returns the number of messages in the batch
+ pub fn coalesce_batch(&mut self, current_offset: u64, batch: IggyMessagesMut) -> u32 {
+ let batch_messages_count = batch.count();
+
+ if batch_messages_count == 0 {
+ return 0;
+ }
+
+ if self.messages.is_none() {
+ self.base_offset = current_offset;
+ self.base_timestamp = IggyTimestamp::now().as_micros();
+ self.current_offset = current_offset;
+ self.current_timestamp = self.base_timestamp;
+ }
+
+ let batch_size = batch.size();
+
+ if let Some(messages) = &mut self.messages {
+ messages.extend(batch);
+ } else {
+ self.messages = Some(batch);
+ // self.messages.as_mut().unwrap().set_capacity(1_200_000); // TODO(hubcio): Add new config and multiply this by k factor
+ }
+
+ self.messages_count += batch_messages_count;
+ self.current_size += IggyByteSize::from(batch_size as u64);
+ self.current_offset = self.base_offset + self.messages_count as u64 - 1;
+ self.current_timestamp = IggyTimestamp::now().as_micros();
+
+ batch_messages_count
+ }
+
+ /// Checks if the accumulator is empty
+ pub fn is_empty(&self) -> bool {
+ self.messages.is_none() || self.messages_count == 0
+ }
+
+ /// Returns the number of unsaved messages
+ pub fn unsaved_messages_count(&self) -> usize {
+ self.messages_count as usize
+ }
+
+ /// Returns the maximum offset in the accumulator
+ pub fn batch_max_offset(&self) -> u64 {
+ self.current_offset
+ }
+
+ /// Returns the maximum timestamp in the accumulator
+ pub fn batch_max_timestamp(&self) -> u64 {
+ self.current_timestamp
+ }
+
+ /// Returns the base offset of the accumulator
+ pub fn batch_base_offset(&self) -> u64 {
+ self.base_offset
+ }
+
+ /// Returns the base timestamp of the accumulator
+ pub fn batch_base_timestamp(&self) -> u64 {
+ self.base_timestamp
+ }
+
+ /// Takes ownership of the accumulator and returns the messages
+ pub fn materialize(self) -> IggyMessages {
+ self.messages.unwrap().into()
+ }
+}
diff --git a/server/src/streaming/segments/mod.rs b/server/src/streaming/segments/mod.rs
index 324a19f4..f7bacd74 100644
--- a/server/src/streaming/segments/mod.rs
+++ b/server/src/streaming/segments/mod.rs
@@ -1,11 +1,10 @@
-mod fetch_result;
mod indexes;
-mod logs;
+mod messages;
+mod messages_accumulator;
mod reading_messages;
mod segment;
mod writing_messages;
-pub use fetch_result::*;
pub use indexes::Index;
pub use segment::Segment;
diff --git a/server/src/streaming/segments/reading_messages.rs b/server/src/streaming/segments/reading_messages.rs
index bbb71437..70e9d700 100644
--- a/server/src/streaming/segments/reading_messages.rs
+++ b/server/src/streaming/segments/reading_messages.rs
@@ -1,9 +1,8 @@
-use super::{indexes::*, IggyBatchFetchResult};
-use crate::streaming::segments::{segment::Segment, IggyBatchSlice};
+use crate::streaming::segments::segment::Segment;
use error_set::ErrContext;
use iggy::{
error::IggyError,
- models::batch::{IggyBatch, IggyMutableBatch},
+ models::IggyMessages,
utils::{byte_size::IggyByteSize, checksum, sizeable::Sizeable},
};
use std::{
@@ -12,6 +11,8 @@ use std::{
};
use tracing::{trace, warn};
+use super::{indexes::IndexRange, Index};
+
const COMPONENT: &str = "STREAMING_SEGMENT";
impl Segment {
@@ -28,6 +29,8 @@ impl Segment {
start_timestamp: u64,
count: usize,
) -> Result<Vec<Arc<()>>, IggyError> {
+ todo!()
+
//TODO: Fix me
/*
if count == 0 {
@@ -45,9 +48,9 @@ impl Segment {
remaining -= disk_count;
if remaining > 0 {
- if let Some(batch_accumulator) = &self.unsaved_messages {
+ if let Some(messages_accumulator) = &self.unsaved_messages {
let buffer_messages =
- batch_accumulator.get_messages_by_timestamp(start_timestamp, remaining);
+ messages_accumulator.get_messages_by_timestamp(start_timestamp, remaining);
messages.extend(buffer_messages);
}
}
@@ -56,97 +59,98 @@ impl Segment {
messages.truncate(count);
Ok(messages)
*/
- todo!()
}
pub async fn get_messages_by_offset(
&self,
mut offset: u64,
count: u32,
- ) -> Result<Vec<IggyBatchSlice>, IggyError> {
+ ) -> Result<IggyMessages, IggyError> {
+ todo!()
+
/*
if count == 0 {
return Ok(EMPTY_MESSAGES.into_iter().map(Arc::new).collect());
}
*/
- if offset < self.start_offset {
- offset = self.start_offset;
- }
- let end_offset = offset + (count - 1) as u64;
-
- // TODO: Move this as a method on `IggyBatch` and make this method internal only to the segment module
- let filter_and_create_slice = |batch: IggyBatch| {
- let mut ranges = batch.iter().filter_map(|(range, msg)| {
- //println!("looking for offsets: {} - {}, msg_offset: {}", offset, end_offset, msg.offset);
- if msg.offset >= offset && msg.offset <= end_offset {
- Some(range)
- } else {
- None
- }
- });
- let first = ranges.next();
- let last = ranges.last();
- let range = match (first, last) {
- (Some(f), Some(l)) => f.start..l.end,
- (Some(single), None) => single,
- _ => panic!("TODO: Fix me"),
- };
- IggyBatchSlice::new(range, batch.header, batch.batch)
- };
- // In case that the partition messages buffer is disabled, we need to check the unsaved messages buffer
- if self.unsaved_messages.is_none() {
- return self
- .load_messages_from_disk(offset, end_offset)
- .await
- .map(|batches| {
- batches
- .into_iter()
- .map(filter_and_create_slice)
- .collect::<Vec<_>>()
- });
- }
-
- let batch_accumulator = self.unsaved_messages.as_ref().unwrap();
- if batch_accumulator.is_empty() {
- return self
- .load_messages_from_disk(offset, end_offset)
- .await
- .map(|batches| {
- batches
- .into_iter()
- .map(filter_and_create_slice)
- .collect::<Vec<_>>()
- });
- }
-
- let first_buffer_offset = batch_accumulator.batch_base_offset();
- let last_buffer_offset = batch_accumulator.batch_max_offset();
-
- // Case 1: All messages are in messages_require_to_save buffer
- if offset >= first_buffer_offset && end_offset <= last_buffer_offset {
- return Ok(self
- .load_messages_from_unsaved_buffer(offset, end_offset)
- .into_iter()
- .map(filter_and_create_slice)
- .collect::<Vec<_>>());
- }
-
- // Case 2: All messages are on disk
- if end_offset < first_buffer_offset {
- return self
- .load_messages_from_disk(offset, end_offset)
- .await
- .map(|batches| {
- batches
- .into_iter()
- .map(filter_and_create_slice)
- .collect::<Vec<_>>()
- });
- } else {
- // TODO: Fix me
- todo!()
- }
+ // if offset < self.start_offset {
+ // offset = self.start_offset;
+ // }
+ // let end_offset = offset + (count - 1) as u64;
+
+ // // TODO: Move this as a method on `IggyBatch` and make this method internal only to the segment module
+ // let filter_and_create_slice = |batch: IggyBatch| {
+ // let mut ranges = batch.iter().filter_map(|(range, msg)| {
+ // //println!("looking for offsets: {} - {}, msg_offset: {}", offset, end_offset, msg.offset);
+ // if msg.offset >= offset && msg.offset <= end_offset {
+ // Some(range)
+ // } else {
+ // None
+ // }
+ // });
+ // let first = ranges.next();
+ // let last = ranges.last();
+ // let range = match (first, last) {
+ // (Some(f), Some(l)) => f.start..l.end,
+ // (Some(single), None) => single,
+ // _ => panic!("TODO: Fix me"),
+ // };
+ // IggyBatchSlice::new(range, batch.header, batch.batch)
+ // };
+ // // In case that the partition messages buffer is disabled, we need to check the unsaved messages buffer
+ // if self.unsaved_messages.is_none() {
+ // return self
+ // .load_messages_from_disk(offset, end_offset)
+ // .await
+ // .map(|batches| {
+ // batches
+ // .into_iter()
+ // .map(filter_and_create_slice)
+ // .collect::<Vec<_>>()
+ // });
+ // }
+
+ // let messages_accumulator = self.unsaved_messages.as_ref().unwrap();
+ // if messages_accumulator.is_empty() {
+ // return self
+ // .load_messages_from_disk(offset, end_offset)
+ // .await
+ // .map(|batches| {
+ // batches
+ // .into_iter()
+ // .map(filter_and_create_slice)
+ // .collect::<Vec<_>>()
+ // });
+ // }
+
+ // let first_buffer_offset = messages_accumulator.batch_base_offset();
+ // let last_buffer_offset = messages_accumulator.batch_max_offset();
+
+ // // Case 1: All messages are in messages_require_to_save buffer
+ // if offset >= first_buffer_offset && end_offset <= last_buffer_offset {
+ // return Ok(self
+ // .load_messages_from_unsaved_buffer(offset, end_offset)
+ // .into_iter()
+ // .map(filter_and_create_slice)
+ // .collect::<Vec<_>>());
+ // }
+
+ // // Case 2: All messages are on disk
+ // if end_offset < first_buffer_offset {
+ // return self
+ // .load_messages_from_disk(offset, end_offset)
+ // .await
+ // .map(|batches| {
+ // batches
+ // .into_iter()
+ // .map(filter_and_create_slice)
+ // .collect::<Vec<_>>()
+ // });
+ // } else {
+ // // TODO: Fix me
+ // todo!()
+ // }
// TODO: Fix me
/*
@@ -225,9 +229,11 @@ impl Segment {
&self,
start_offset: u64,
end_offset: u64,
- ) -> Vec<IggyBatch> {
- let batch_accumulator = self.unsaved_messages.as_ref().unwrap();
- batch_accumulator.get_messages_by_offset(start_offset, end_offset)
+ ) -> Vec<IggyMessages> {
+ todo!()
+
+ // let messages_accumulator = self.unsaved_messages.as_ref().unwrap();
+ // messages_accumulator.get_messages_by_offset(start_offset, end_offset)
}
/// Load message batches given an index range.
@@ -236,43 +242,47 @@ impl Segment {
index_range: &IndexRange,
start_offset: u64,
end_offset: u64,
- ) -> Result<Vec<IggyBatch>, IggyError> {
- trace!("Loading message batches for index range: {:?}", index_range);
- let batches = self
- .log_reader
- .as_ref()
- .unwrap()
- .load_batches_by_range_impl(index_range, start_offset, end_offset)
- .await
- .with_error_context(|error| {
- format!(
- "Failed to load message batches by range {:?} from disk for {}. {error}",
- index_range, self
- )
- })?;
- Ok(batches)
+ ) -> Result<Vec<IggyMessages>, IggyError> {
+ todo!()
+
+ // trace!("Loading message batches for index range: {:?}", index_range);
+ // let batches = self
+ // .log_reader
+ // .as_ref()
+ // .unwrap()
+ // .load_batches_by_range_impl(index_range, start_offset, end_offset)
+ // .await
+ // .with_error_context(|error| {
+ // format!(
+ // "Failed to load message batches by range {:?} from disk for {}. {error}",
+ // index_range, self
+ // )
+ // })?;
+ // Ok(batches)
}
pub async fn load_index_for_timestamp(
&self,
timestamp: u64,
) -> Result<Option<Index>, IggyError> {
- trace!("Loading index for timestamp: {}", timestamp);
- let index = self
- .index_reader
- .as_ref()
- .unwrap()
- .load_index_for_timestamp_impl(timestamp)
- .await
- .with_error_context(|error| {
- format!(
- "Failed to load index for timestamp: {timestamp} for {}. {error}",
- self
- )
- })?;
+ todo!()
- trace!("Loaded index: {:?}", index);
- Ok(index)
+ // trace!("Loading index for timestamp: {}", timestamp);
+ // let index = self
+ // .index_reader
+ // .as_ref()
+ // .unwrap()
+ // .load_index_for_timestamp_impl(timestamp)
+ // .await
+ // .with_error_context(|error| {
+ // format!(
+ // "Failed to load index for timestamp: {timestamp} for {}. {error}",
+ // self
+ // )
+ // })?;
+
+ // trace!("Loaded index: {:?}", index);
+ // Ok(index)
}
async fn load_messages_from_disk_by_timestamp(
@@ -354,86 +364,90 @@ impl Segment {
/// Loads and returns all message IDs from the log file.
pub async fn load_message_ids(&self) -> Result<Vec<u128>, IggyError> {
- trace!("Loading message IDs from log file: {}", self.log_path);
- let ids = self
- .log_reader
- .as_ref()
- .unwrap()
- .load_message_ids_impl()
- .await
- .with_error_context(|error| {
- format!("Failed to load message IDs, error: {error} for {self}")
- })?;
- trace!("Loaded {} message IDs from log file.", ids.len());
- Ok(ids)
+ todo!()
+
+ // trace!("Loading message IDs from log file: {}", self.log_path);
+ // let ids = self
+ // .log_reader
+ // .as_ref()
+ // .unwrap()
+ // .load_message_ids_impl()
+ // .await
+ // .with_error_context(|error| {
+ // format!("Failed to load message IDs, error: {error} for {self}")
+ // })?;
+ // trace!("Loaded {} message IDs from log file.", ids.len());
+ // Ok(ids)
}
async fn load_messages_from_disk(
&self,
start_offset: u64,
end_offset: u64,
- ) -> Result<Vec<IggyBatch>, IggyError> {
- trace!(
- "Loading messages from disk, start offset: {}, end offset: {}, current offset: {}...",
- start_offset,
- end_offset,
- self.current_offset
- );
-
- //TODO: Fix me
- /*
- if start_offset > end_offset {
- warn!(
- "Cannot load messages from disk, invalid offset range: {} - {}.",
- start_offset, end_offset
- );
- return Ok(EMPTY_MESSAGES.into_iter().map(Arc::new).collect());
- }
- */
-
- if let Some(indices) = &self.indexes {
- let relative_start_offset = (start_offset - self.start_offset) as u32;
- let relative_end_offset = (end_offset - self.start_offset) as u32;
- let index_range = match self.load_highest_lower_bound_index(
- indices,
- relative_start_offset,
- relative_end_offset,
- ) {
- Ok(range) => range,
- Err(_) => {
- trace!(
- "Cannot load messages from disk, index range not found: {} - {}.",
- start_offset,
- end_offset
- );
- panic!("todo");
- // TODO: Fix me
- /*
- return Ok(EMPTY_MESSAGES.into_iter().map(Arc::new).collect());
- */
- }
- };
-
- return self
- .load_messages_from_segment_file(&index_range, start_offset, end_offset)
- .await;
- }
+ ) -> Result<IggyMessages, IggyError> {
+ todo!()
- match self
- .index_reader
- .as_ref()
- .unwrap()
- .load_index_range_impl(start_offset, end_offset, self.start_offset)
- .await
- .with_error_context(|error| {
- format!("Failed to load index range start offset: {start_offset}, end offset: {end_offset} for {self}. {error}")
- })? {
- Some(index_range) => {
- self.load_messages_from_segment_file(&index_range, start_offset, end_offset)
- .await
- }
- None => panic!("todo"),
- }
+ // trace!(
+ // "Loading messages from disk, start offset: {}, end offset: {}, current offset: {}...",
+ // start_offset,
+ // end_offset,
+ // self.current_offset
+ // );
+
+ // //TODO: Fix me
+ // /*
+ // if start_offset > end_offset {
+ // warn!(
+ // "Cannot load messages from disk, invalid offset range: {} - {}.",
+ // start_offset, end_offset
+ // );
+ // return Ok(EMPTY_MESSAGES.into_iter().map(Arc::new).collect());
+ // }
+ // */
+
+ // if let Some(indices) = &self.indexes {
+ // let relative_start_offset = (start_offset - self.start_offset) as u32;
+ // let relative_end_offset = (end_offset - self.start_offset) as u32;
+ // let index_range = match self.load_highest_lower_bound_index(
+ // indices,
+ // relative_start_offset,
+ // relative_end_offset,
+ // ) {
+ // Ok(range) => range,
+ // Err(_) => {
+ // trace!(
+ // "Cannot load messages from disk, index range not found: {} - {}.",
+ // start_offset,
+ // end_offset
+ // );
+ // panic!("todo");
+ // // TODO: Fix me
+ // /*
+ // return Ok(EMPTY_MESSAGES.into_iter().map(Arc::new).collect());
+ // */
+ // }
+ // };
+
+ // return self
+ // .load_messages_from_segment_file(&index_range, start_offset, end_offset)
+ // .await;
+ // }
+
+ // match self
+ // .index_reader
+ // .as_ref()
+ // .unwrap()
+ // .load_index_range_impl(start_offset, end_offset, self.start_offset)
+ // .await
+ // .with_error_context(|error| {
+ // format!("Failed to load index range start offset: {start_offset}, end offset: {end_offset} for {self}. {error}")
+ // })? {
+ // Some(index_range) => {
+ // self.load_messages_from_segment_file(&index_range, start_offset, end_offset)
+ // .await
+ // }
+ // None => panic!("todo"),
+ // }
}
async fn load_messages_from_segment_file(
@@ -441,20 +455,22 @@ impl Segment {
index_range: &IndexRange,
start_offset: u64,
end_offset: u64,
- ) -> Result<Vec<IggyBatch>, IggyError> {
- trace!(
- "Loading messages from disk, index range: {:?}, start offset: {}, end offset: {}.",
- index_range,
- start_offset,
- end_offset
- );
- let batches = self
- .load_batches_by_range(index_range, start_offset, end_offset)
- .await
- .with_error_context(|error| format!(
- "{COMPONENT} (error: {error}) - failed to load message batches, stream ID: {}, topic ID: {}, partition ID: {}, start offset: {start_offset}, end offset: {end_offset}",
- self.stream_id, self.topic_id, self.partition_id
- ))?;
+ ) -> Result<IggyMessages, IggyError> {
+ todo!()
+
+ // trace!(
+ // "Loading messages from disk, index range: {:?}, start offset: {}, end offset: {}.",
+ // index_range,
+ // start_offset,
+ // end_offset
+ // );
+ // let batches = self
+ // .load_batches_by_range(index_range, start_offset, end_offset)
+ // .await
+ // .with_error_context(|error| format!(
+ // "{COMPONENT} (error: {error}) - failed to load message batches, stream ID: {}, topic ID: {}, partition ID: {}, start offset: {start_offset}, end offset: {end_offset}",
+ // self.stream_id, self.topic_id, self.partition_id
+ // ))?;
//TODO: Fix me
/*
@@ -466,6 +482,6 @@ impl Segment {
);
*/
- Ok(batches)
+ // Ok(batches)
}
}
diff --git a/server/src/streaming/segments/segment.rs b/server/src/streaming/segments/segment.rs
index 1e6b97c2..67d2a2c8 100644
--- a/server/src/streaming/segments/segment.rs
+++ b/server/src/streaming/segments/segment.rs
@@ -1,7 +1,7 @@
use super::indexes::*;
-use super::logs::*;
+use super::messages::*;
+use super::messages_accumulator::MessagesAccumulator;
use crate::configs::system::SystemConfig;
-use crate::streaming::batching::batch_accumulator::BatchAccumulator;
use crate::streaming::segments::*;
use error_set::ErrContext;
use iggy::error::IggyError;
@@ -35,12 +35,12 @@ pub struct Segment {
pub messages_count_of_parent_topic: Arc<AtomicU64>,
pub messages_count_of_parent_partition: Arc<AtomicU64>,
pub is_closed: bool,
- pub(super) log_writer: Option<SegmentLogWriter>,
- pub(super) log_reader: Option<SegmentLogReader>,
+ pub(super) log_writer: Option<MessagesLogWriter>,
+ pub(super) log_reader: Option<MessagesLogReader>,
pub(super) index_writer: Option<SegmentIndexWriter>,
pub(super) index_reader: Option<SegmentIndexReader>,
pub message_expiry: IggyExpiry,
- pub unsaved_messages: Option<BatchAccumulator>,
+ pub unsaved_messages: Option<MessagesAccumulator>,
pub config: Arc<SystemConfig>,
pub indexes: Option<Vec<Index>>,
pub(super) log_size_bytes: Arc<AtomicU64>,
@@ -210,7 +210,7 @@ impl Segment {
let max_file_operation_retries = self.config.state.max_file_operation_retries;
let retry_delay = self.config.state.retry_delay;
- let log_writer = SegmentLogWriter::new(
+ let log_writer = MessagesLogWriter::new(
&self.log_path,
self.log_size_bytes.clone(),
log_fsync,
@@ -230,7 +230,8 @@ impl Segment {
}
pub async fn initialize_reading(&mut self) -> Result<(), IggyError> {
- let log_reader = SegmentLogReader::new(&self.log_path, self.log_size_bytes.clone()).await?;
+ let log_reader =
+ MessagesLogReader::new(&self.log_path, self.log_size_bytes.clone()).await?;
// TODO(hubcio): there is no need to store open fd for reader if we have index cache enabled
let index_reader =
SegmentIndexReader::new(&self.index_path, self.index_size_bytes.clone()).await?;
diff --git a/server/src/streaming/segments/writing_messages.rs b/server/src/streaming/segments/writing_messages.rs
index 25e3152a..0eb2f086 100644
--- a/server/src/streaming/segments/writing_messages.rs
+++ b/server/src/streaming/segments/writing_messages.rs
@@ -1,12 +1,11 @@
use super::indexes::*;
-use crate::streaming::batching::batch_accumulator::BatchAccumulator;
use crate::streaming::segments::segment::Segment;
use error_set::ErrContext;
+use iggy::confirmation::Confirmation;
use iggy::error::IggyError;
-use iggy::models::batch::{IggyMutableBatch, IGGY_BATCH_OVERHEAD};
+use iggy::models::IggyMessagesMut;
use iggy::utils::byte_size::IggyByteSize;
use iggy::utils::sizeable::Sizeable;
-use iggy::{confirmation::Confirmation, models::batch::IggyBatch};
use std::sync::atomic::Ordering;
use tracing::{info, trace};
@@ -14,7 +13,7 @@ impl Segment {
pub async fn append_batch(
&mut self,
current_offset: u64,
- batch: IggyMutableBatch,
+ messages: IggyMessagesMut,
) -> Result<u32, IggyError> {
if self.is_closed {
return Err(IggyError::SegmentClosed(
@@ -22,24 +21,23 @@ impl Segment {
self.partition_id,
));
}
- let batch_size = batch.get_size();
- let batch_accumulator = self.unsaved_messages.get_or_insert_with(Default::default);
- let messages_count = batch_accumulator.coalesce_batch(current_offset, batch);
+ let messages_size = messages.size();
+ let messages_accumulator = self.unsaved_messages.get_or_insert_with(Default::default);
+ let messages_count = messages_accumulator.coalesce_batch(current_offset, messages);
if self.current_offset == 0 {
- self.start_timestamp = batch_accumulator.batch_base_timestamp();
+ self.start_timestamp = messages_accumulator.batch_base_timestamp();
}
- self.end_timestamp = batch_accumulator.batch_max_timestamp();
- self.current_offset = batch_accumulator.batch_max_offset();
- self.size_bytes += batch_size;
+ self.end_timestamp = messages_accumulator.batch_max_timestamp();
+ self.current_offset = messages_accumulator.batch_max_offset();
+ self.size_bytes += IggyByteSize::from(messages_size as u64);
- let batch_size = batch_size.as_bytes_u64();
self.size_of_parent_stream
- .fetch_add(batch_size, Ordering::AcqRel);
+ .fetch_add(messages_size as u64, Ordering::AcqRel);
self.size_of_parent_topic
- .fetch_add(batch_size, Ordering::AcqRel);
+ .fetch_add(messages_size as u64, Ordering::AcqRel);
self.size_of_parent_partition
- .fetch_add(batch_size, Ordering::AcqRel);
+ .fetch_add(messages_size as u64, Ordering::AcqRel);
self.messages_count_of_parent_stream
.fetch_add(messages_count as u64, Ordering::SeqCst);
self.messages_count_of_parent_topic
@@ -79,16 +77,16 @@ impl Segment {
return Ok(0);
}
- let batch_accumulator = self.unsaved_messages.take().unwrap();
- if batch_accumulator.is_empty() {
+ let messages_accumulator = self.unsaved_messages.take().unwrap();
+ if messages_accumulator.is_empty() {
return Ok(0);
}
- let batch_max_offset = batch_accumulator.batch_max_offset();
- let batch_max_timestamp = batch_accumulator.batch_max_timestamp();
+ let batch_max_offset = messages_accumulator.batch_max_offset();
+ let batch_max_timestamp = messages_accumulator.batch_max_timestamp();
let index =
self.store_offset_and_timestamp_index_for_batch(batch_max_offset, batch_max_timestamp);
- let unsaved_messages_number = batch_accumulator.unsaved_messages_count();
+ let unsaved_messages_number = messages_accumulator.unsaved_messages_count();
trace!(
"Saving {} messages on disk in segment with start offset: {} for partition with ID: {}...",
unsaved_messages_number,
@@ -96,16 +94,17 @@ impl Segment {
self.partition_id
);
- let (header, batches) = batch_accumulator.materialize();
+ let messages = messages_accumulator.materialize();
let confirmation = match confirmation {
Some(val) => val,
None => self.config.segment.server_confirmation,
};
+
let saved_bytes = self
.log_writer
.as_mut()
.unwrap()
- .save_batches(header, batches, confirmation)
+ .save_batches(messages, confirmation)
.await
.with_error_context(
|error| format!("Failed to save batch for seg: {self}. {error}",),
@@ -119,13 +118,14 @@ impl Segment {
.await
.with_error_context(|error| format!("Failed to save index for {self}. {error}"))?;
- self.size_bytes += IggyByteSize::from(IGGY_BATCH_OVERHEAD);
- self.size_of_parent_stream
- .fetch_add(IGGY_BATCH_OVERHEAD, Ordering::AcqRel);
- self.size_of_parent_topic
- .fetch_add(IGGY_BATCH_OVERHEAD, Ordering::AcqRel);
- self.size_of_parent_partition
- .fetch_add(IGGY_BATCH_OVERHEAD, Ordering::AcqRel);
+ // TODO(hubcio): fix this
+ // self.size_bytes += IggyByteSize::from(IGGY_BATCH_OVERHEAD);
+ // self.size_of_parent_stream
+ // .fetch_add(IGGY_BATCH_OVERHEAD, Ordering::AcqRel);
+ // self.size_of_parent_topic
+ // .fetch_add(IGGY_BATCH_OVERHEAD, Ordering::AcqRel);
+ // self.size_of_parent_partition
+ // .fetch_add(IGGY_BATCH_OVERHEAD, Ordering::AcqRel);
trace!(
"Saved {} messages on disk in segment with start offset: {} for partition with ID: {}, total bytes written: {}.",
diff --git a/server/src/streaming/systems/messages.rs b/server/src/streaming/systems/messages.rs
index 874b0096..02eb37e3 100644
--- a/server/src/streaming/systems/messages.rs
+++ b/server/src/streaming/systems/messages.rs
@@ -1,5 +1,4 @@
use crate::streaming::cache::memory_tracker::CacheMemoryTracker;
-use crate::streaming::segments::IggyBatchFetchResult;
use crate::streaming::session::Session;
use crate::streaming::systems::system::System;
use crate::streaming::systems::COMPONENT;
@@ -7,11 +6,7 @@ use bytes::Bytes;
use error_set::ErrContext;
use iggy::confirmation::Confirmation;
use iggy::consumer::Consumer;
-use iggy::messages::poll_messages::PollingStrategy;
-use iggy::messages::send_messages::Partitioning;
-use iggy::models::batch::{IggyBatch, IggyMutableBatch};
-use iggy::utils::byte_size::IggyByteSize;
-use iggy::utils::sizeable::Sizeable;
+use iggy::prelude::*;
use iggy::{error::IggyError, identifier::Identifier};
use tracing::{error, trace};
@@ -24,7 +19,7 @@ impl System {
topic_id: &Identifier,
partition_id: Option<u32>,
args: PollingArgs,
- ) -> Result<IggyBatchFetchResult, IggyError> {
+ ) -> Result<IggyMessages, IggyError> {
self.ensure_authenticated(session)?;
if args.count == 0 {
return Err(IggyError::InvalidMessagesCount);
@@ -124,11 +119,11 @@ impl System {
stream_id: &Identifier,
topic_id: &Identifier,
partitioning: &Partitioning,
- batch: IggyMutableBatch,
+ messages: IggyMessagesMut,
confirmation: Option<Confirmation>,
) -> Result<(), IggyError> {
self.ensure_authenticated(session)?;
- let topic = self.find_topic(session, &stream_id, &topic_id).with_error_context(|error| format!("{COMPONENT} (error: {error}) - topic not found for stream_id: {stream_id}, topic_id: {topic_id}"))?;
+ let topic = self.find_topic(session, stream_id, topic_id).with_error_context(|error| format!("{COMPONENT} (error: {error}) - topic not found for stream_id: {stream_id}, topic_id: {topic_id}"))?;
self.permissioner.append_messages(
session.get_user_id(),
topic.stream_id,
@@ -174,9 +169,8 @@ impl System {
}
}
*/
- let batch_size_bytes = batch.get_size();
topic
- .append_messages(batch_size_bytes, partitioning, batch, confirmation)
+ .append_messages(partitioning, messages, confirmation)
.await?;
//TODO: Fix me
//self.metrics.increment_messages(messages_count);
diff --git a/server/src/streaming/topics/messages.rs b/server/src/streaming/topics/messages.rs
index 30cf517f..a265f2d5 100644
--- a/server/src/streaming/topics/messages.rs
+++ b/server/src/streaming/topics/messages.rs
@@ -1,22 +1,20 @@
-use crate::streaming::batching::appendable_batch_info::AppendableBatchInfo;
use crate::streaming::polling_consumer::PollingConsumer;
-use crate::streaming::segments::IggyBatchFetchResult;
use crate::streaming::topics::topic::Topic;
use crate::streaming::topics::COMPONENT;
use crate::streaming::utils::file::folder_size;
use crate::streaming::utils::hash;
use ahash::AHashMap;
use error_set::ErrContext;
-use iggy::confirmation::Confirmation;
use iggy::error::IggyError;
use iggy::locking::IggySharedMutFn;
-use iggy::messages::poll_messages::{PollingKind, PollingStrategy};
-use iggy::messages::send_messages::{Message, Partitioning, PartitioningKind};
-use iggy::models::batch::{IggyBatch, IggyMutableBatch};
+use iggy::messages::{PartitioningKind, PollingKind};
+use iggy::models::{IggyMessages, IggyMessagesMut};
+use iggy::prelude::Partitioning;
use iggy::utils::byte_size::IggyByteSize;
use iggy::utils::expiry::IggyExpiry;
use iggy::utils::sizeable::Sizeable;
use iggy::utils::timestamp::IggyTimestamp;
+use iggy::{confirmation::Confirmation, prelude::PollingStrategy};
use std::sync::atomic::Ordering;
use std::sync::Arc;
use tracing::{info, trace, warn};
@@ -32,7 +30,7 @@ impl Topic {
partition_id: u32,
strategy: PollingStrategy,
count: u32,
- ) -> Result<IggyBatchFetchResult, IggyError> {
+ ) -> Result<IggyMessages, IggyError> {
if !self.has_partitions() {
return Err(IggyError::NoPartitions(self.topic_id, self.stream_id));
}
@@ -71,9 +69,8 @@ impl Topic {
pub async fn append_messages(
&self,
- batch_size: IggyByteSize,
partitioning: &Partitioning,
- batch: IggyMutableBatch,
+ messages: IggyMessagesMut,
confirmation: Option<Confirmation>,
) -> Result<(), IggyError> {
if !self.has_partitions() {
@@ -104,8 +101,7 @@ impl Topic {
}
};
- let appendable_batch_info = AppendableBatchInfo::new(batch_size, partition_id);
- self.append_messages_to_partition(appendable_batch_info, batch, confirmation)
+ self.append_messages_to_partition(messages, partition_id, confirmation)
.await
}
@@ -129,22 +125,20 @@ impl Topic {
async fn append_messages_to_partition(
&self,
- appendable_batch_info: AppendableBatchInfo,
- batch: IggyMutableBatch,
+ messages: IggyMessagesMut,
+ partition_id: u32,
confirmation: Option<Confirmation>,
) -> Result<(), IggyError> {
- let partition = self.partitions.get(&appendable_batch_info.partition_id);
+ let partition = self.partitions.get(&partition_id);
partition
- .ok_or({
- IggyError::PartitionNotFound(
- appendable_batch_info.partition_id,
- self.stream_id,
- self.stream_id,
- )
- })?
+ .ok_or(IggyError::PartitionNotFound(
+ partition_id,
+ self.stream_id,
+ self.stream_id,
+ ))?
.write()
.await
- .append_messages(appendable_batch_info, batch, confirmation)
+ .append_messages(messages, confirmation)
.await
.with_error_context(|error| {
format!("{COMPONENT} (error: {error}) - failed to append messages")
diff --git a/server/src/tcp/connection_handler.rs b/server/src/tcp/connection_handler.rs
index d28e96ad..1dd74e10 100644
--- a/server/src/tcp/connection_handler.rs
+++ b/server/src/tcp/connection_handler.rs
@@ -11,9 +11,6 @@ use iggy::bytes_serializable::BytesSerializable;
use iggy::command::SEND_MESSAGES_CODE;
use iggy::error::IggyError;
use iggy::identifier::Identifier;
-use iggy::messages::send_messages::Partitioning;
-use iggy::models::batch::{IggyHeader, IggyMutableBatch, IGGY_BATCH_OVERHEAD};
-use iggy::utils::sizeable::Sizeable;
use std::io::ErrorKind;
use std::sync::Arc;
use tracing::{debug, error, info};