You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by gk...@apache.org on 2025/07/07 12:43:55 UTC
(iggy) branch io_uring_tpc updated: feat(io_uring): add open method to partition and segment (#1975)
This is an automated email from the ASF dual-hosted git repository.
gkoszyk pushed a commit to branch io_uring_tpc
in repository https://gitbox.apache.org/repos/asf/iggy.git
The following commit(s) were added to refs/heads/io_uring_tpc by this push:
new 7d13fb6a feat(io_uring): add open method to partition and segment (#1975)
7d13fb6a is described below
commit 7d13fb6a5e085925351e30fd12bb3bf45785ac0f
Author: Grzegorz Koszyk <11...@users.noreply.github.com>
AuthorDate: Mon Jul 7 14:43:51 2025 +0200
feat(io_uring): add open method to partition and segment (#1975)
---
core/integration/tests/streaming/segment.rs | 8 +--
.../binary/handlers/topics/create_topic_handler.rs | 64 +++++++++++++++-------
core/server/src/main.rs | 12 ++--
core/server/src/shard/gate.rs | 16 +++---
core/server/src/shard/mod.rs | 54 +++++++++++++++---
core/server/src/shard/system/topics.rs | 41 ++------------
core/server/src/shard/transmission/event.rs | 8 ++-
core/server/src/streaming/partitions/partition.rs | 13 +++++
core/server/src/streaming/partitions/segments.rs | 2 +-
core/server/src/streaming/partitions/storage.rs | 2 +-
core/server/src/streaming/segments/segment.rs | 4 +-
core/server/src/streaming/streams/topics.rs | 4 +-
12 files changed, 140 insertions(+), 88 deletions(-)
diff --git a/core/integration/tests/streaming/segment.rs b/core/integration/tests/streaming/segment.rs
index c5ec065e..c42423e7 100644
--- a/core/integration/tests/streaming/segment.rs
+++ b/core/integration/tests/streaming/segment.rs
@@ -61,7 +61,7 @@ async fn should_persist_segment() {
setup
.create_partition_directory(stream_id, topic_id, partition_id)
.await;
- segment.persist().await.unwrap();
+ segment.open().await.unwrap();
assert_persisted_segment(
&setup
.config
@@ -98,7 +98,7 @@ async fn should_load_existing_segment_from_disk() {
setup
.create_partition_directory(stream_id, topic_id, partition_id)
.await;
- segment.persist().await.unwrap();
+ segment.open().await.unwrap();
assert_persisted_segment(
&setup
.config
@@ -168,7 +168,7 @@ async fn should_persist_and_load_segment_with_messages() {
setup
.create_partition_directory(stream_id, topic_id, partition_id)
.await;
- segment.persist().await.unwrap();
+ segment.open().await.unwrap();
assert_persisted_segment(
&setup
.config
@@ -254,7 +254,7 @@ async fn given_at_least_one_not_expired_message_segment_should_not_be_expired()
setup
.create_partition_directory(stream_id, topic_id, partition_id)
.await;
- segment.persist().await.unwrap();
+ segment.open().await.unwrap();
assert_persisted_segment(
&setup
.config
diff --git a/core/server/src/binary/handlers/topics/create_topic_handler.rs b/core/server/src/binary/handlers/topics/create_topic_handler.rs
index 51088b55..183b5ee1 100644
--- a/core/server/src/binary/handlers/topics/create_topic_handler.rs
+++ b/core/server/src/binary/handlers/topics/create_topic_handler.rs
@@ -20,8 +20,9 @@ use crate::binary::command::{BinaryServerCommand, ServerCommand, ServerCommandHa
use crate::binary::handlers::utils::receive_and_validate;
use crate::binary::mapper;
use crate::binary::{handlers::topics::COMPONENT, sender::SenderKind};
-use crate::shard::IggyShard;
+use crate::shard::namespace::IggyNamespace;
use crate::shard::transmission::event::ShardEvent;
+use crate::shard::{IggyShard, ShardInfo};
use crate::state::command::EntryCommand;
use crate::state::models::CreateTopicWithId;
use crate::streaming::session::Session;
@@ -29,6 +30,7 @@ use anyhow::Result;
use error_set::ErrContext;
use iggy_common::IggyError;
use iggy_common::create_topic::CreateTopic;
+use iggy_common::locking::IggySharedMutFn;
use std::rc::Rc;
use tracing::{debug, instrument};
@@ -47,12 +49,12 @@ impl ServerCommandHandler for CreateTopic {
) -> Result<(), IggyError> {
debug!("session: {session}, command: {self}");
let stream_id = self.stream_id.clone();
- let topic_id = self.topic_id;
- let (shards_assignment, created_topic_id) = shard
+ let maybe_topic_id = self.topic_id;
+ let (topic_id, partition_ids) = shard
.create_topic(
session,
- &self.stream_id,
- self.topic_id,
+ &stream_id,
+ maybe_topic_id,
&self.name,
self.partitions_count,
self.message_expiry,
@@ -61,35 +63,59 @@ impl ServerCommandHandler for CreateTopic {
self.replication_factor,
)
.await
- .with_error_context(|error| format!("{COMPONENT} (error: {error}) - failed to create topic for stream_id: {stream_id}, topic_id: {topic_id:?}"
+ .with_error_context(|error| format!("{COMPONENT} (error: {error}) - failed to create topic for stream_id: {stream_id}, topic_id: {maybe_topic_id:?}"
))?;
+ // `create_topic` always returns numeric identifier.
+ let numeric_topic_id = topic_id.get_u32_value().unwrap();
+ let numeric_stream_id = shard.get_stream(&stream_id).map(|s| s.stream_id).unwrap();
let event = ShardEvent::CreatedTopic {
stream_id: stream_id.clone(),
- topic_id,
+ topic_id: topic_id.clone(),
name: self.name.clone(),
partitions_count: self.partitions_count,
message_expiry: self.message_expiry,
compression_algorithm: self.compression_algorithm,
max_topic_size: self.max_topic_size,
replication_factor: self.replication_factor,
- shards_assignment,
};
- // Broadcast the event to all shards.
let _responses = shard.broadcast_event_to_all_shards(event.into());
-
- let stream = shard
- .get_stream(&self.stream_id)
- .with_error_context(|error| {
- format!(
- "{COMPONENT} (error: {error}) - failed to get stream for stream_id: {stream_id}"
- )
- })?;
- let topic = stream.get_topic(&created_topic_id)
+ let stream = shard.get_stream(&stream_id).with_error_context(|error| {
+ format!(
+ "{COMPONENT} (error: {error}) - failed to get stream for stream_id: {stream_id}"
+ )
+ })?;
+ let topic = stream.get_topic(&topic_id)
.with_error_context(|error| {
format!(
- "{COMPONENT} (error: {error}) - failed to get topic with ID: {created_topic_id} in stream with ID: {stream_id}"
+ "{COMPONENT} (error: {error}) - failed to get topic with ID: {topic_id} in stream with ID: {stream_id}"
)
})?;
+
+ let records = shard
+ .create_shard_table_records(&partition_ids, numeric_stream_id, numeric_topic_id)
+ .collect::<Vec<_>>();
+ // Open partition and segments for that particular shard.
+ for (ns, shard_info) in records.iter() {
+ if shard_info.id() == shard.id {
+ let partition_id = ns.partition_id;
+ let partition = topic.get_partition(partition_id)?;
+ let mut partition = partition.write().await;
+ partition.open().await.with_error_context(|error| {
+ format!(
+ "{COMPONENT} (error: {error}) - failed to open partition with ID: {partition_id} in topic with ID: {topic_id} for stream with ID: {stream_id}"
+ )
+ })?;
+ }
+ }
+ shard.insert_shard_table_records(records);
+ // Broadcast the event to all shards.
+ let event = ShardEvent::CreatedShardTableRecords {
+ stream_id: numeric_stream_id,
+ topic_id: numeric_topic_id,
+ partition_ids,
+ };
+ let _responses = shard.broadcast_event_to_all_shards(event.into());
+
self.message_expiry = topic.message_expiry;
self.max_topic_size = topic.max_topic_size;
let topic_id = topic.topic_id;
diff --git a/core/server/src/main.rs b/core/server/src/main.rs
index 5e6ba0d1..2602e3c8 100644
--- a/core/server/src/main.rs
+++ b/core/server/src/main.rs
@@ -43,7 +43,7 @@ use server::log::logger::Logging;
use server::log::tokio_console::Logging;
use server::server_error::ServerError;
use server::shard::IggyShard;
-use server::shard::gate::Gate;
+use server::shard::gate::Barrier;
use server::state::StateKind;
use server::state::command::EntryCommand;
use server::state::file::FileState;
@@ -128,12 +128,12 @@ fn main() -> Result<(), ServerError> {
let shards_count = available_cpus.into();
let shards_set = 0..shards_count;
let (connections, shutdown_handles) = create_shard_connections(shards_set.clone());
- let gate = Arc::new(Gate::new());
+ let barrier = Arc::new(Barrier::new());
let mut handles = Vec::with_capacity(shards_set.len());
for shard_id in shards_set {
let id = shard_id as u16;
- let gate = gate.clone();
+ let barrier = barrier.clone();
let connections = connections.clone();
let config = config.clone();
let state_persister = resolve_persister(config.system.state.enforce_fsync);
@@ -168,10 +168,10 @@ fn main() -> Result<(), ServerError> {
// Trait bound on the closure is FnOnce.
// Peak into the state to check if the root user exists.
// If it does not exist, create it.
- gate.with_async::<Result<(), IggyError>>(async |gate_state| {
+ barrier.with_async::<Result<(), IggyError>>(async |barrier_state| {
// A thread already initialized state
// Thus, we can skip it.
- if let Some(_) = gate_state.inner() {
+ if let Some(_) = barrier_state.inner() {
return Ok(());
}
@@ -225,7 +225,7 @@ fn main() -> Result<(), ServerError> {
})?;
}
- gate_state.set_result(());
+ barrier_state.set_result(());
Ok(())
})
.await;
diff --git a/core/server/src/shard/gate.rs b/core/server/src/shard/gate.rs
index 2ac20445..1538092d 100644
--- a/core/server/src/shard/gate.rs
+++ b/core/server/src/shard/gate.rs
@@ -1,16 +1,16 @@
use std::sync::Mutex;
#[derive(Default)]
-pub struct Gate<T> {
- state: Mutex<GateState<T>>,
+pub struct Barrier<T> {
+ state: Mutex<BarrierState<T>>,
}
#[derive(Default)]
-pub struct GateState<T> {
+pub struct BarrierState<T> {
result: Option<T>,
}
-impl<T> GateState<T> {
+impl<T> BarrierState<T> {
pub fn set_result(&mut self, result: T) {
self.result = Some(result);
}
@@ -20,22 +20,22 @@ impl<T> GateState<T> {
}
}
-impl<T> Gate<T>
+impl<T> Barrier<T>
where
T: Default,
{
pub fn new() -> Self {
- Gate {
+ Barrier {
state: Default::default(),
}
}
- pub async fn with_async<R>(&self, f: impl AsyncFnOnce(&mut GateState<T>) -> R) {
+ pub async fn with_async<R>(&self, f: impl AsyncFnOnce(&mut BarrierState<T>) -> R) {
let mut guard = self.state.lock().unwrap();
f(&mut guard).await;
}
- pub async fn with<R>(&self, f: impl FnOnce(&mut GateState<T>) -> R) {
+ pub async fn with<R>(&self, f: impl FnOnce(&mut BarrierState<T>) -> R) {
let mut guard = self.state.lock().unwrap();
f(&mut guard);
}
diff --git a/core/server/src/shard/mod.rs b/core/server/src/shard/mod.rs
index 16b4459c..3d467779 100644
--- a/core/server/src/shard/mod.rs
+++ b/core/server/src/shard/mod.rs
@@ -28,7 +28,7 @@ use ahash::{AHashMap, AHashSet, HashMap};
use builder::IggyShardBuilder;
use error_set::ErrContext;
use futures::future::try_join_all;
-use iggy_common::{EncryptorKind, Identifier, IggyError, UserId};
+use iggy_common::{EncryptorKind, Identifier, IggyError, UserId, locking::IggySharedMutFn};
use namespace::IggyNamespace;
use std::{
cell::{Cell, RefCell},
@@ -36,12 +36,12 @@ use std::{
rc::Rc,
str::FromStr,
sync::{
- Arc, RwLock,
+ Arc,
atomic::{AtomicBool, AtomicU32, Ordering},
},
time::{Duration, Instant},
};
-use tracing::{error, info, instrument, trace, warn};
+use tracing::{error, info, instrument, warn};
use transmission::connector::{Receiver, ShardConnector, StopReceiver, StopSender};
use crate::{
@@ -59,7 +59,6 @@ use crate::{
},
state::{
StateKind,
- file::FileState,
system::{StreamState, SystemState, UserState},
},
streaming::{
@@ -524,18 +523,17 @@ impl IggyShard {
compression_algorithm,
max_topic_size,
replication_factor,
- shards_assignment,
} => {
+ let topic_id = topic_id.get_u32_value().ok();
self.create_topic_bypass_auth(
stream_id,
- *topic_id,
+ topic_id,
name,
*partitions_count,
*message_expiry,
*compression_algorithm,
*max_topic_size,
*replication_factor,
- shards_assignment.clone(),
)
.await
}
@@ -549,6 +547,32 @@ impl IggyShard {
self.add_active_session(session);
Ok(())
}
+ ShardEvent::CreatedShardTableRecords {
+ stream_id,
+ topic_id,
+ partition_ids,
+ } => {
+ let records = self
+ .create_shard_table_records(&partition_ids, *stream_id, *topic_id)
+ .collect::<Vec<_>>();
+ let stream = self.get_stream(&Identifier::numeric(*stream_id)?)?;
+ let topic = stream.get_topic(&Identifier::numeric(*topic_id)?)?;
+ // Open partition and segments for that particular shard.
+ for (ns, shard_info) in records.iter() {
+ if shard_info.id() == self.id {
+ let partition_id = ns.partition_id;
+ let partition = topic.get_partition(partition_id)?;
+ let mut partition = partition.write().await;
+ partition.open().await.with_error_context(|error| {
+ format!(
+ "{COMPONENT} (error: {error}) - failed to open partition with ID: {partition_id} in topic with ID: {topic_id} for stream with ID: {stream_id}"
+ )
+ })?;
+ }
+ }
+ self.insert_shard_table_records(records);
+ Ok(())
+ }
}
}
@@ -611,6 +635,22 @@ impl IggyShard {
})
}
+ pub fn create_shard_table_records(
+ &self,
+ partition_ids: &[u32],
+ stream_id: u32,
+ topic_id: u32,
+ ) -> impl Iterator<Item = (IggyNamespace, ShardInfo)> {
+ let records = partition_ids.iter().map(move |partition_id| {
+ let namespace = IggyNamespace::new(stream_id, topic_id, *partition_id);
+ let hash = namespace.generate_hash();
+ let shard_id = hash % self.get_available_shards_count();
+ let shard_info = ShardInfo::new(shard_id as u16);
+ (namespace, shard_info)
+ });
+ records
+ }
+
pub fn insert_shard_table_records(
&self,
records: impl IntoIterator<Item = (IggyNamespace, ShardInfo)>,
diff --git a/core/server/src/shard/system/topics.rs b/core/server/src/shard/system/topics.rs
index d71b0f1d..31562504 100644
--- a/core/server/src/shard/system/topics.rs
+++ b/core/server/src/shard/system/topics.rs
@@ -112,9 +112,8 @@ impl IggyShard {
compression_algorithm: CompressionAlgorithm,
max_topic_size: MaxTopicSize,
replication_factor: Option<u8>,
- shards_assignment: Vec<(IggyNamespace, ShardInfo)>,
) -> Result<(), IggyError> {
- let (topic_id, _) = self.create_topic_base(
+ self.create_topic_base(
stream_id,
topic_id,
name,
@@ -124,25 +123,6 @@ impl IggyShard {
max_topic_size,
replication_factor,
)?;
- let stream = self.get_stream(stream_id).with_error_context(|error| {
- format!("{COMPONENT} (error: {error}) - failed to get stream with ID: {stream_id}")
- })?;
- let stream_id = stream.stream_id;
- let topic = stream
- .get_topic(&Identifier::numeric(topic_id)?)
- .with_error_context(|error| {
- format!("{COMPONENT} (error: {error}) - failed to get topic with ID: {topic_id} in stream with ID: {stream_id}")
- })?;
-
- for (_, shard_info) in &shards_assignment {
- if shard_info.id() == self.id {
- topic.persist().await.with_error_context(|error| {
- format!("{COMPONENT} (error: {error}) - failed to persist topic: {topic}")
- })?;
- }
- }
-
- self.insert_shard_table_records(shards_assignment);
self.metrics.increment_topics(1);
self.metrics.increment_partitions(partitions_count);
@@ -162,7 +142,7 @@ impl IggyShard {
compression_algorithm: CompressionAlgorithm,
max_topic_size: MaxTopicSize,
replication_factor: Option<u8>,
- ) -> Result<(Vec<(IggyNamespace, ShardInfo)>, Identifier), IggyError> {
+ ) -> Result<(Identifier, Vec<u32>), IggyError> {
self.ensure_authenticated(session)?;
{
let stream = self.get_stream(stream_id).with_error_context(|error| {
@@ -195,7 +175,7 @@ impl IggyShard {
})?;
let stream_id = stream.stream_id;
let topic = stream
- .get_topic(&Identifier::numeric(topic_id)?)
+ .get_topic(&topic_id)
.with_error_context(|error| {
format!("{COMPONENT} (error: {error}) - failed to get topic with ID: {topic_id} in stream with ID: {stream_id}")
})?;
@@ -203,22 +183,11 @@ impl IggyShard {
format!("{COMPONENT} (error: {error}) - failed to persist topic: {topic}")
})?;
- // TODO: Refactor
- let records = partition_ids.into_iter().map(|partition_id| {
- let namespace = IggyNamespace::new(stream_id, topic_id, partition_id);
- let hash = namespace.generate_hash();
- let shard_id = hash % self.get_available_shards_count();
- let shard_info = ShardInfo::new(shard_id as u16);
- (namespace, shard_info)
- });
- let records = records.collect::<Vec<_>>();
- self.insert_shard_table_records(records.clone());
-
self.metrics.increment_topics(1);
self.metrics.increment_partitions(partitions_count);
self.metrics.increment_segments(partitions_count);
- Ok((records, Identifier::numeric(topic_id)?))
+ Ok((topic_id, partition_ids))
}
fn create_topic_base(
@@ -231,7 +200,7 @@ impl IggyShard {
compression_algorithm: CompressionAlgorithm,
max_topic_size: MaxTopicSize,
replication_factor: Option<u8>,
- ) -> Result<(u32, Vec<u32>), IggyError> {
+ ) -> Result<(Identifier, Vec<u32>), IggyError> {
let mut stream = self.get_stream_mut(stream_id).with_error_context(|error| {
format!("{COMPONENT} (error: {error}) - failed to get mutable reference to stream with ID: {stream_id}")
})?;
diff --git a/core/server/src/shard/transmission/event.rs b/core/server/src/shard/transmission/event.rs
index c1a34c27..c4f5db29 100644
--- a/core/server/src/shard/transmission/event.rs
+++ b/core/server/src/shard/transmission/event.rs
@@ -9,6 +9,11 @@ use crate::{
#[derive(Debug)]
pub enum ShardEvent {
+ CreatedShardTableRecords {
+ stream_id: u32,
+ topic_id: u32,
+ partition_ids: Vec<u32>,
+ },
CreatedStream {
stream_id: Option<u32>,
name: String,
@@ -20,14 +25,13 @@ pub enum ShardEvent {
//DeletedPartitions(Identifier, Identifier, u32),
CreatedTopic {
stream_id: Identifier,
- topic_id: Option<u32>,
+ topic_id: Identifier,
name: String,
partitions_count: u32,
message_expiry: IggyExpiry,
compression_algorithm: CompressionAlgorithm,
max_topic_size: MaxTopicSize,
replication_factor: Option<u8>,
- shards_assignment: Vec<(IggyNamespace, ShardInfo)>,
},
//CreatedConsumerGroup(Identifier, Identifier, Option<u32>, String),
//DeletedConsumerGroup(Identifier, Identifier, Identifier),
diff --git a/core/server/src/streaming/partitions/partition.rs b/core/server/src/streaming/partitions/partition.rs
index 4a573d14..fc346693 100644
--- a/core/server/src/streaming/partitions/partition.rs
+++ b/core/server/src/streaming/partitions/partition.rs
@@ -21,9 +21,11 @@ use crate::streaming::deduplication::message_deduplicator::MessageDeduplicator;
use crate::streaming::segments::*;
use crate::streaming::storage::SystemStorage;
use dashmap::DashMap;
+use error_set::ErrContext;
use iggy_common::ConsumerKind;
use iggy_common::IggyByteSize;
use iggy_common::IggyDuration;
+use iggy_common::IggyError;
use iggy_common::IggyExpiry;
use iggy_common::IggyTimestamp;
use iggy_common::Sizeable;
@@ -32,6 +34,8 @@ use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
+use super::COMPONENT;
+
#[derive(Debug)]
pub struct Partition {
pub stream_id: u32,
@@ -178,6 +182,15 @@ impl Partition {
partition
}
+
+ pub async fn open(&mut self) -> Result<(), IggyError> {
+ for segment in self.get_segments_mut() {
+ segment.open().await.with_error_context(|error| {
+ format!("{COMPONENT} (error: {error}) - failed to persist segment: {segment}",)
+ })?;
+ }
+ Ok(())
+ }
}
impl Sizeable for Partition {
diff --git a/core/server/src/streaming/partitions/segments.rs b/core/server/src/streaming/partitions/segments.rs
index ae293ca2..88d1bc36 100644
--- a/core/server/src/streaming/partitions/segments.rs
+++ b/core/server/src/streaming/partitions/segments.rs
@@ -88,7 +88,7 @@ impl Partition {
self.messages_count.clone(),
true,
);
- new_segment.persist().await.with_error_context(|error| {
+ new_segment.open().await.with_error_context(|error| {
format!("{COMPONENT} (error: {error}) - failed to persist new segment: {new_segment}",)
})?;
self.segments.push(new_segment);
diff --git a/core/server/src/streaming/partitions/storage.rs b/core/server/src/streaming/partitions/storage.rs
index 67e3d3f4..0b3a65d3 100644
--- a/core/server/src/streaming/partitions/storage.rs
+++ b/core/server/src/streaming/partitions/storage.rs
@@ -324,7 +324,7 @@ impl PartitionStorage for FilePartitionStorage {
}
for segment in partition.get_segments_mut() {
- segment.persist().await.with_error_context(|error| {
+ segment.open().await.with_error_context(|error| {
format!("{COMPONENT} (error: {error}) - failed to persist segment: {segment}",)
})?;
}
diff --git a/core/server/src/streaming/segments/segment.rs b/core/server/src/streaming/segments/segment.rs
index c13ce07a..08b30ef6 100644
--- a/core/server/src/streaming/segments/segment.rs
+++ b/core/server/src/streaming/segments/segment.rs
@@ -205,8 +205,8 @@ impl Segment {
Ok(())
}
- /// Save the segment state to disk.
- pub async fn persist(&mut self) -> Result<(), IggyError> {
+ /// Open segment.
+ pub async fn open(&mut self) -> Result<(), IggyError> {
info!(
"Saving segment with start offset: {} for partition with ID: {} for topic with ID: {} and stream with ID: {}",
self.start_offset, self.partition_id, self.topic_id, self.stream_id
diff --git a/core/server/src/streaming/streams/topics.rs b/core/server/src/streaming/streams/topics.rs
index 7833efa2..a3f309a5 100644
--- a/core/server/src/streaming/streams/topics.rs
+++ b/core/server/src/streaming/streams/topics.rs
@@ -45,7 +45,7 @@ impl Stream {
compression_algorithm: CompressionAlgorithm,
max_topic_size: MaxTopicSize,
replication_factor: u8,
- ) -> Result<(u32, Vec<u32>), IggyError> {
+ ) -> Result<(Identifier, Vec<u32>), IggyError> {
let max_topic_size = Topic::get_max_topic_size(max_topic_size, &self.config)?;
if self.topics_ids.contains_key(name) {
return Err(IggyError::TopicNameAlreadyExists(
@@ -97,7 +97,7 @@ impl Stream {
info!("Created topic {}", topic);
self.topics_ids.insert(name.to_owned(), id);
self.topics.insert(id, topic);
- Ok((id, partition_ids))
+ Ok((Identifier::numeric(id).unwrap(), partition_ids))
}
pub fn update_topic(