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/10/09 07:58:00 UTC
(iggy) 01/01: feat(io_uring): implement Slab
This is an automated email from the ASF dual-hosted git repository.
hgruszecki pushed a commit to branch io_uring_tpc_users
in repository https://gitbox.apache.org/repos/asf/iggy.git
commit 67a8fc935672d3cc3f93d85031804c809d8160ae
Author: Hubert Gruszecki <h....@gmail.com>
AuthorDate: Tue Oct 7 12:56:51 2025 +0200
feat(io_uring): implement Slab<User>
---
core/binary_protocol/src/utils/mapper.rs | 2 +-
core/common/src/commands/users/defaults.rs | 2 +-
.../tests/cli/client/test_client_get_command.rs | 2 +-
core/integration/tests/cli/common/mod.rs | 2 +-
.../tests/cli/user/test_user_create_command.rs | 6 +-
.../tests/cli/user/test_user_delete_command.rs | 4 +-
.../tests/cli/user/test_user_get_command.rs | 8 +-
.../cli/user/test_user_permissions_command.rs | 8 +-
.../scenarios/stream_size_validation_scenario.rs | 2 +-
.../tests/server/scenarios/user_scenario.rs | 12 +-
core/integration/tests/state/file.rs | 15 +-
core/integration/tests/state/system.rs | 2 +-
core/server/src/binary/mapper.rs | 2 +-
core/server/src/bootstrap.rs | 16 +-
core/server/src/http/consumer_groups.rs | 13 +-
core/server/src/http/streams.rs | 17 +-
core/server/src/shard/builder.rs | 19 +-
core/server/src/shard/mod.rs | 30 +--
.../src/shard/system/personal_access_tokens.rs | 81 ++++----
core/server/src/shard/system/segments.rs | 2 +-
core/server/src/shard/system/streams.rs | 33 ++--
core/server/src/shard/system/topics.rs | 18 +-
core/server/src/shard/system/users.rs | 205 +++++++--------------
.../periodic/personal_access_token_cleaner.rs | 4 +-
core/server/src/slab/mod.rs | 1 +
core/server/src/slab/users.rs | 142 ++++++++++++++
core/server/src/streaming/session.rs | 8 +-
core/server/src/streaming/users/user.rs | 2 +-
28 files changed, 358 insertions(+), 300 deletions(-)
diff --git a/core/binary_protocol/src/utils/mapper.rs b/core/binary_protocol/src/utils/mapper.rs
index 725932c5c..356d65931 100644
--- a/core/binary_protocol/src/utils/mapper.rs
+++ b/core/binary_protocol/src/utils/mapper.rs
@@ -898,7 +898,7 @@ fn map_to_client_info(
.map_err(|_| IggyError::InvalidNumberEncoding)?,
);
let user_id = match user_id {
- 0 => None,
+ u32::MAX => None,
_ => Some(user_id),
};
diff --git a/core/common/src/commands/users/defaults.rs b/core/common/src/commands/users/defaults.rs
index f18c8e0da..3d60f18d9 100644
--- a/core/common/src/commands/users/defaults.rs
+++ b/core/common/src/commands/users/defaults.rs
@@ -23,6 +23,6 @@ pub const MIN_PASSWORD_LENGTH: usize = 3;
pub const MAX_PAT_LENGTH: usize = 100;
pub const MAX_PERSONAL_ACCESS_TOKEN_NAME_LENGTH: usize = 30;
pub const MIN_PERSONAL_ACCESS_TOKEN_NAME_LENGTH: usize = 3;
-pub const DEFAULT_ROOT_USER_ID: u32 = 1;
+pub const DEFAULT_ROOT_USER_ID: u32 = 0;
pub const DEFAULT_ROOT_USERNAME: &str = "iggy";
pub const DEFAULT_ROOT_PASSWORD: &str = "iggy";
diff --git a/core/integration/tests/cli/client/test_client_get_command.rs b/core/integration/tests/cli/client/test_client_get_command.rs
index d76c09e47..734341758 100644
--- a/core/integration/tests/cli/client/test_client_get_command.rs
+++ b/core/integration/tests/cli/client/test_client_get_command.rs
@@ -67,7 +67,7 @@ impl IggyCmdTestCase for TestClientGetCmd {
"Client ID | {}",
self.get_client_id()
)))
- .stdout(contains("User ID | 1"));
+ .stdout(contains("User ID | 0"));
}
async fn verify_server_state(&self, _client: &dyn Client) {}
diff --git a/core/integration/tests/cli/common/mod.rs b/core/integration/tests/cli/common/mod.rs
index 0aa7c4123..bebf46f21 100644
--- a/core/integration/tests/cli/common/mod.rs
+++ b/core/integration/tests/cli/common/mod.rs
@@ -128,7 +128,7 @@ impl IggyCmdTest {
.await
.unwrap();
- assert_eq!(identity_info.user_id, 1);
+ assert_eq!(identity_info.user_id, 0);
}
pub(crate) async fn execute_test(&mut self, mut test_case: impl IggyCmdTestCase) {
diff --git a/core/integration/tests/cli/user/test_user_create_command.rs b/core/integration/tests/cli/user/test_user_create_command.rs
index 3678185bd..5c4eecdb8 100644
--- a/core/integration/tests/cli/user/test_user_create_command.rs
+++ b/core/integration/tests/cli/user/test_user_create_command.rs
@@ -193,7 +193,7 @@ pub async fn should_be_successful() {
vec![String::from("3")],
Some(Permissions {
global: GlobalPermissions::default(),
- streams: Some(AHashMap::from([(3u32, StreamPermissions::default())])),
+ streams: Some(AHashMap::from([(3usize, StreamPermissions::default())])),
}),
),
))
@@ -209,7 +209,7 @@ pub async fn should_be_successful() {
Some(Permissions {
global: GlobalPermissions::default(),
streams: Some(AHashMap::from([(
- 1u32,
+ 1usize,
StreamPermissions {
topics: Some(AHashMap::from([(
1,
@@ -249,7 +249,7 @@ pub async fn should_be_successful() {
send_messages: false,
},
streams: Some(AHashMap::from([(
- 2u32,
+ 2usize,
StreamPermissions {
topics: Some(AHashMap::from([(
1,
diff --git a/core/integration/tests/cli/user/test_user_delete_command.rs b/core/integration/tests/cli/user/test_user_delete_command.rs
index dd501eb71..fd0f327b7 100644
--- a/core/integration/tests/cli/user/test_user_delete_command.rs
+++ b/core/integration/tests/cli/user/test_user_delete_command.rs
@@ -111,7 +111,7 @@ pub async fn should_be_successful() {
String::from("username"),
String::from("password"),
UserStatus::Active,
- 2,
+ 1,
TestUserId::Numeric,
))
.await;
@@ -120,7 +120,7 @@ pub async fn should_be_successful() {
String::from("testuser"),
String::from("testpass"),
UserStatus::Inactive,
- 2,
+ 1,
TestUserId::Named,
))
.await;
diff --git a/core/integration/tests/cli/user/test_user_get_command.rs b/core/integration/tests/cli/user/test_user_get_command.rs
index c52ac4547..ba67730a1 100644
--- a/core/integration/tests/cli/user/test_user_get_command.rs
+++ b/core/integration/tests/cli/user/test_user_get_command.rs
@@ -31,8 +31,8 @@ enum TestUser<'a> {
Existing(&'a str),
New(&'a str),
NewWithGlobalPerms(&'a str),
- NewWithStreamPerms(&'a str, u32),
- NewWithStreamAndTopicPerms(&'a str, u32, u32),
+ NewWithStreamPerms(&'a str, usize),
+ NewWithStreamAndTopicPerms(&'a str, usize, usize),
}
struct TestUserGetCmd {
@@ -42,8 +42,8 @@ struct TestUserGetCmd {
using_user_id: TestUserId,
create_user: bool,
check_global_perms: bool,
- check_stream_perms: Option<u32>,
- check_topic_perms: Option<u32>,
+ check_stream_perms: Option<usize>,
+ check_topic_perms: Option<usize>,
}
impl TestUserGetCmd {
diff --git a/core/integration/tests/cli/user/test_user_permissions_command.rs b/core/integration/tests/cli/user/test_user_permissions_command.rs
index 37958231f..116dbb665 100644
--- a/core/integration/tests/cli/user/test_user_permissions_command.rs
+++ b/core/integration/tests/cli/user/test_user_permissions_command.rs
@@ -159,7 +159,7 @@ pub async fn should_be_successful() {
vec![String::from("3")],
Some(Permissions {
global: GlobalPermissions::default(),
- streams: Some(AHashMap::from([(3u32, StreamPermissions::default())])),
+ streams: Some(AHashMap::from([(3usize, StreamPermissions::default())])),
}),
),
TestUserId::Numeric,
@@ -174,7 +174,7 @@ pub async fn should_be_successful() {
Some(Permissions {
global: GlobalPermissions::default(),
streams: Some(AHashMap::from([(
- 1u32,
+ 1usize,
StreamPermissions {
topics: Some(AHashMap::from([(
2,
@@ -213,10 +213,10 @@ pub async fn should_be_successful() {
send_messages: false,
},
streams: Some(AHashMap::from([(
- 2u32,
+ 2usize,
StreamPermissions {
topics: Some(AHashMap::from([(
- 2u32,
+ 2usize,
TopicPermissions {
manage_topic: false,
read_topic: false,
diff --git a/core/integration/tests/server/scenarios/stream_size_validation_scenario.rs b/core/integration/tests/server/scenarios/stream_size_validation_scenario.rs
index 17e5bc870..c816b2dac 100644
--- a/core/integration/tests/server/scenarios/stream_size_validation_scenario.rs
+++ b/core/integration/tests/server/scenarios/stream_size_validation_scenario.rs
@@ -20,7 +20,7 @@ use crate::server::scenarios::{PARTITION_ID, PARTITIONS_COUNT, create_client};
use bytes::Bytes;
use iggy::prelude::*;
use integration::test_server::{ClientFactory, assert_clean_system, login_root};
-use std::{str::FromStr, time::Duration};
+use std::str::FromStr;
const S1_NAME: &str = "test-stream-1";
const T1_NAME: &str = "test-topic-1";
diff --git a/core/integration/tests/server/scenarios/user_scenario.rs b/core/integration/tests/server/scenarios/user_scenario.rs
index 1903c9326..bfcdfb1c3 100644
--- a/core/integration/tests/server/scenarios/user_scenario.rs
+++ b/core/integration/tests/server/scenarios/user_scenario.rs
@@ -37,7 +37,7 @@ pub async fn run(client_factory: &dyn ClientFactory) {
// 3. Login as root user
let identity_info = login_root(&client).await;
- assert_eq!(identity_info.user_id, 1);
+ assert_eq!(identity_info.user_id, 0);
// 4. List all users
let users = client.get_users().await.unwrap();
@@ -45,7 +45,7 @@ pub async fn run(client_factory: &dyn ClientFactory) {
// 5. Get user details
let user = users.first().unwrap();
- assert_eq!(user.id, 1);
+ assert_eq!(user.id, 0);
assert!(user.created_at.as_micros() > 0);
assert_eq!(user.username, DEFAULT_ROOT_USERNAME);
assert_eq!(user.status, UserStatus::Active);
@@ -56,7 +56,7 @@ pub async fn run(client_factory: &dyn ClientFactory) {
.unwrap()
.expect("Failed to get user");
- assert_eq!(user.id, 1);
+ assert_eq!(user.id, 0);
assert!(user.created_at.as_micros() > 0);
assert_eq!(user.username, DEFAULT_ROOT_USERNAME);
assert_eq!(user.status, UserStatus::Active);
@@ -102,7 +102,7 @@ pub async fn run(client_factory: &dyn ClientFactory) {
// 9. Login as the new user
let identity_info = client.login_user(test_user, test_password).await.unwrap();
- assert_eq!(identity_info.user_id, 2);
+ assert_eq!(identity_info.user_id, 1);
// 10. Trying to create a new user (or any other resource) without the appropriate permissions should fail
let create_user_result = client
@@ -168,14 +168,14 @@ pub async fn run(client_factory: &dyn ClientFactory) {
.await
.unwrap();
- assert_eq!(identity_info.user_id, 2);
+ assert_eq!(identity_info.user_id, 1);
let identity_info = client
.login_with_personal_access_token(&raw_pat2.token)
.await
.unwrap();
- assert_eq!(identity_info.user_id, 2);
+ assert_eq!(identity_info.user_id, 1);
// 17. Delete the personal access tokens
client
diff --git a/core/integration/tests/state/file.rs b/core/integration/tests/state/file.rs
index b830cd53b..f8d06bd55 100644
--- a/core/integration/tests/state/file.rs
+++ b/core/integration/tests/state/file.rs
@@ -41,9 +41,9 @@ async fn should_apply_single_entry() {
let state = setup.state();
state.init().await.unwrap();
- let user_id = 1;
+ let user_id = 0;
let command = EntryCommand::CreateUser(CreateUserWithId {
- user_id,
+ user_id: 1,
command: CreateUser {
username: "test".to_string(),
password: "secret".to_string(),
@@ -67,9 +67,9 @@ async fn should_apply_encrypted_entry() {
let state = setup.state();
state.init().await.unwrap();
- let user_id = 1;
+ let user_id = 0;
let command = EntryCommand::CreateUser(CreateUserWithId {
- user_id,
+ user_id: 1,
command: CreateUser {
username: "test".to_string(),
password: "secret".to_string(),
@@ -98,9 +98,10 @@ async fn should_apply_multiple_entries() {
assert_eq!(state.entries_count(), 0);
assert_eq!(state.term(), 0);
- let first_user_id = 1;
+ let first_user_id = 0; // Root user
+ let created_user_id = 1; // First created user
let create_user = EntryCommand::CreateUser(CreateUserWithId {
- user_id: first_user_id,
+ user_id: created_user_id,
command: CreateUser {
username: "test".to_string(),
password: "secret".to_string(),
@@ -115,7 +116,7 @@ async fn should_apply_multiple_entries() {
assert_eq!(state.current_index(), 0);
assert_eq!(state.entries_count(), 1);
- let second_user_id = 2;
+ let second_user_id = 1; // Created user performs action
let stream_id = 1;
let create_stream = EntryCommand::CreateStream(CreateStreamWithId {
stream_id,
diff --git a/core/integration/tests/state/system.rs b/core/integration/tests/state/system.rs
index dce78aea1..77eeb5851 100644
--- a/core/integration/tests/state/system.rs
+++ b/core/integration/tests/state/system.rs
@@ -39,7 +39,7 @@ async fn should_be_initialized_based_on_state_entries() {
let state = setup.state();
state.init().await.unwrap();
- let user_id = 1;
+ let user_id = 0;
let create_user = CreateUser {
username: "user".to_string(),
password: "secret".to_string(),
diff --git a/core/server/src/binary/mapper.rs b/core/server/src/binary/mapper.rs
index 6856dea2f..51de99d6d 100644
--- a/core/server/src/binary/mapper.rs
+++ b/core/server/src/binary/mapper.rs
@@ -293,7 +293,7 @@ fn extend_consumer_group(
fn extend_client(client: &Client, bytes: &mut BytesMut) {
bytes.put_u32_le(client.session.client_id);
- bytes.put_u32_le(client.user_id.unwrap_or(0));
+ bytes.put_u32_le(client.user_id.unwrap_or(u32::MAX));
let transport: u8 = match client.transport {
TransportProtocol::Tcp => 1,
TransportProtocol::Quic => 2,
diff --git a/core/server/src/bootstrap.rs b/core/server/src/bootstrap.rs
index 5a150ab16..1004a7643 100644
--- a/core/server/src/bootstrap.rs
+++ b/core/server/src/bootstrap.rs
@@ -21,6 +21,7 @@ use crate::{
traits_ext::{
EntityComponentSystem, EntityComponentSystemMutCell, Insert, InsertCell, IntoComponents,
},
+ users::Users,
},
state::system::{StreamState, TopicState, UserState},
streaming::{
@@ -45,7 +46,7 @@ use ahash::HashMap;
use compio::{fs::create_dir_all, runtime::Runtime};
use error_set::ErrContext;
use iggy_common::{
- ConsumerKind, IggyError, UserId,
+ ConsumerKind, IggyError,
defaults::{
DEFAULT_ROOT_PASSWORD, DEFAULT_ROOT_USERNAME, MAX_PASSWORD_LENGTH, MAX_USERNAME_LENGTH,
MIN_PASSWORD_LENGTH, MIN_USERNAME_LENGTH,
@@ -198,8 +199,8 @@ pub async fn load_streams(
Ok(streams)
}
-pub fn load_users(state: impl IntoIterator<Item = UserState>) -> HashMap<UserId, User> {
- let mut users = HashMap::default();
+pub fn load_users(state: impl IntoIterator<Item = UserState>) -> Users {
+ let users = Users::new();
for user_state in state {
let UserState {
id,
@@ -217,16 +218,11 @@ pub fn load_users(state: impl IntoIterator<Item = UserState>) -> HashMap<UserId,
.map(|token| {
(
Arc::new(token.token_hash.clone()),
- PersonalAccessToken::raw(
- user_state.id,
- &token.name,
- &token.token_hash,
- token.expiry_at,
- ),
+ PersonalAccessToken::raw(id, &token.name, &token.token_hash, token.expiry_at),
)
})
.collect();
- users.insert(id, user);
+ users.insert(user);
}
users
}
diff --git a/core/server/src/http/consumer_groups.rs b/core/server/src/http/consumer_groups.rs
index 16c6ac91c..b69c62ba2 100644
--- a/core/server/src/http/consumer_groups.rs
+++ b/core/server/src/http/consumer_groups.rs
@@ -257,12 +257,13 @@ async fn delete_consumer_group(
// Get members from the deleted consumer group and make them leave
let slab = consumer_group.members().inner().shared_get();
for (_, member) in slab.iter() {
- if let Err(err) = state.shard.shard().client_manager.borrow_mut().leave_consumer_group(
- member.client_id,
- stream_id_usize,
- topic_id_usize,
- cg_id,
- ) {
+ if let Err(err) = state
+ .shard
+ .shard()
+ .client_manager
+ .borrow_mut()
+ .leave_consumer_group(member.client_id, stream_id_usize, topic_id_usize, cg_id)
+ {
tracing::warn!(
"{COMPONENT} (error: {err}) - failed to make client leave consumer group for client ID: {}, group ID: {}",
member.client_id,
diff --git a/core/server/src/http/streams.rs b/core/server/src/http/streams.rs
index 51aad3ee5..cc71fa230 100644
--- a/core/server/src/http/streams.rs
+++ b/core/server/src/http/streams.rs
@@ -228,15 +228,16 @@ async fn delete_stream(
// Delete stream and get the stream entity
let stream = {
- let future = SendWrapper::new(state.shard.shard().delete_stream2(
- &session,
- &identifier_stream_id,
- ));
+ let future = SendWrapper::new(
+ state
+ .shard
+ .shard()
+ .delete_stream2(&session, &identifier_stream_id),
+ );
future.await
- }.with_error_context(|error| {
- format!(
- "{COMPONENT} (error: {error}) - failed to delete stream with ID: {stream_id}",
- )
+ }
+ .with_error_context(|error| {
+ format!("{COMPONENT} (error: {error}) - failed to delete stream with ID: {stream_id}",)
})?;
let stream_id_numeric = stream.root().id();
diff --git a/core/server/src/shard/builder.rs b/core/server/src/shard/builder.rs
index 5f25ce630..744bd9874 100644
--- a/core/server/src/shard/builder.rs
+++ b/core/server/src/shard/builder.rs
@@ -23,19 +23,14 @@ use super::{
use crate::{
configs::server::ServerConfig,
shard::{Shard, ShardInfo, namespace::IggyNamespace},
- slab::streams::Streams,
+ slab::{streams::Streams, users::Users},
state::StateKind,
- streaming::{diagnostics::metrics::Metrics, users::user::User, utils::ptr::EternalPtr},
+ streaming::{diagnostics::metrics::Metrics, utils::ptr::EternalPtr},
versioning::SemanticVersion,
};
-use ahash::HashMap;
use dashmap::DashMap;
-use iggy_common::{EncryptorKind, UserId};
-use std::{
- cell::{Cell, RefCell},
- rc::Rc,
- sync::atomic::AtomicBool,
-};
+use iggy_common::EncryptorKind;
+use std::{cell::Cell, rc::Rc, sync::atomic::AtomicBool};
#[derive(Default)]
pub struct IggyShardBuilder {
@@ -43,7 +38,7 @@ pub struct IggyShardBuilder {
streams: Option<Streams>,
shards_table: Option<EternalPtr<DashMap<IggyNamespace, ShardInfo>>>,
state: Option<StateKind>,
- users: Option<HashMap<UserId, User>>,
+ users: Option<Users>,
connections: Option<Vec<ShardConnector<ShardFrame>>>,
config: Option<ServerConfig>,
encryptor: Option<EncryptorKind>,
@@ -95,7 +90,7 @@ impl IggyShardBuilder {
self
}
- pub fn users(mut self, users: HashMap<UserId, User>) -> Self {
+ pub fn users(mut self, users: Users) -> Self {
self.users = Some(users);
self
}
@@ -147,7 +142,7 @@ impl IggyShardBuilder {
shards,
shards_table,
streams2: streams, // TODO: Fixme
- users: RefCell::new(users),
+ users,
encryptor,
config,
_version: version,
diff --git a/core/server/src/shard/mod.rs b/core/server/src/shard/mod.rs
index 4bebc36c5..cc96d0951 100644
--- a/core/server/src/shard/mod.rs
+++ b/core/server/src/shard/mod.rs
@@ -38,35 +38,29 @@ use crate::{
},
},
shard_error, shard_info,
- slab::{streams::Streams, traits_ext::EntityMarker},
+ slab::{streams::Streams, traits_ext::EntityMarker, users::Users},
state::StateKind,
streaming::{
- clients::client_manager::ClientManager,
- diagnostics::metrics::Metrics,
- partitions,
- polling_consumer::PollingConsumer,
- session::Session,
- traits::MainOps,
- users::{permissioner::Permissioner, user::User},
- utils::ptr::EternalPtr,
+ clients::client_manager::ClientManager, diagnostics::metrics::Metrics, partitions,
+ polling_consumer::PollingConsumer, session::Session, traits::MainOps,
+ users::permissioner::Permissioner, utils::ptr::EternalPtr,
},
versioning::SemanticVersion,
};
-use ahash::HashMap;
use builder::IggyShardBuilder;
use compio::io::AsyncWriteAtExt;
use dashmap::DashMap;
use error_set::ErrContext;
use hash32::{Hasher, Murmur3Hasher};
use iggy_common::{
- EncryptorKind, Identifier, IggyError, IggyTimestamp, PollingKind, TransportProtocol, UserId,
+ EncryptorKind, Identifier, IggyError, IggyTimestamp, PollingKind, TransportProtocol,
};
use std::hash::Hasher as _;
use std::{
cell::{Cell, RefCell},
net::SocketAddr,
rc::Rc,
- sync::atomic::{AtomicBool, AtomicU32, Ordering},
+ sync::atomic::{AtomicBool, Ordering},
time::{Duration, Instant},
};
use tracing::{debug, error, instrument, trace};
@@ -75,8 +69,6 @@ use transmission::connector::{Receiver, ShardConnector, StopReceiver};
pub const COMPONENT: &str = "SHARD";
pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10);
-static USER_ID: AtomicU32 = AtomicU32::new(1);
-
pub(crate) struct Shard {
id: u16,
connection: ShardConnector<ShardFrame>,
@@ -138,7 +130,7 @@ pub struct IggyShard {
pub(crate) client_manager: RefCell<ClientManager>,
pub(crate) active_sessions: RefCell<Vec<Rc<Session>>>,
pub(crate) permissioner: RefCell<Permissioner>,
- pub(crate) users: RefCell<HashMap<UserId, User>>,
+ pub(crate) users: Users,
pub(crate) metrics: Metrics,
pub messages_receiver: Cell<Option<Receiver<ShardFrame>>>,
pub(crate) stop_receiver: StopReceiver,
@@ -423,13 +415,11 @@ impl IggyShard {
}
async fn load_users(&self) -> Result<(), IggyError> {
- let users = self.users.borrow();
- let users_count = users.len();
- let current_user_id = users.keys().max().unwrap_or(&1);
- USER_ID.store(current_user_id + 1, Ordering::SeqCst);
+ let users_list = self.users.values();
+ let users_count = users_list.len();
self.permissioner
.borrow_mut()
- .init(&users.values().collect::<Vec<_>>());
+ .init(&users_list.iter().collect::<Vec<_>>());
self.metrics.increment_users(users_count as u32);
shard_info!(self.id, "Initialized {} user(s).", users_count);
Ok(())
diff --git a/core/server/src/shard/system/personal_access_tokens.rs b/core/server/src/shard/system/personal_access_tokens.rs
index 6eb6a0cd3..47ad7856d 100644
--- a/core/server/src/shard/system/personal_access_tokens.rs
+++ b/core/server/src/shard/system/personal_access_tokens.rs
@@ -99,26 +99,26 @@ impl IggyShard {
let name = personal_access_token.name.clone();
let token_hash = personal_access_token.token.clone();
let identifier = user_id.try_into()?;
- let user = self.get_user_mut(&identifier).with_error_context(|error| {
- format!("{COMPONENT} create PAT (error: {error}) - failed to get mutable reference to the user with id: {user_id}")
- })?;
-
- if user
- .personal_access_tokens
- .iter()
- .any(|pat| pat.name.as_str() == name.as_str())
- {
- error!("Personal access token: {name} for user with ID: {user_id} already exists.");
- return Err(IggyError::PersonalAccessTokenAlreadyExists(
- name.to_string(),
- user_id,
- ));
- }
+ self.users.with_user_mut(&identifier, |user| {
+ if user
+ .personal_access_tokens
+ .iter()
+ .any(|pat| pat.name.as_str() == name.as_str())
+ {
+ error!("Personal access token: {name} for user with ID: {user_id} already exists.");
+ return Err(IggyError::PersonalAccessTokenAlreadyExists(
+ name.to_string(),
+ user_id,
+ ));
+ }
- info!("Creating personal access token: {name} for user with ID: {user_id}...");
- user.personal_access_tokens
- .insert(token_hash, personal_access_token);
- info!("Created personal access token: {name} for user with ID: {user_id}.");
+ user.personal_access_tokens
+ .insert(token_hash, personal_access_token);
+ info!("Created personal access token: {name} for user with ID: {user_id}.");
+ Ok(())
+ }).with_error_context(|error| {
+ format!("{COMPONENT} create PAT (error: {error}) - failed to access user with id: {user_id}")
+ })??;
Ok(())
}
@@ -141,27 +141,26 @@ impl IggyShard {
}
fn delete_personal_access_token_base(&self, user_id: u32, name: &str) -> Result<(), IggyError> {
- let user = self
- .get_user_mut(&user_id.try_into()?)
- .with_error_context(|error| {
- format!(
- "{COMPONENT} delete PAT (error: {error}) - failed to get mutable reference to the user with id: {user_id}"
- )
- })?;
+ self.users.with_user_mut(&user_id.try_into()?, |user| {
+ let token = if let Some(pat) = user
+ .personal_access_tokens
+ .iter()
+ .find(|pat| pat.name.as_str() == name)
+ {
+ pat.token.clone()
+ } else {
+ error!("Personal access token: {name} for user with ID: {user_id} does not exist.",);
+ return Err(IggyError::ResourceNotFound(name.to_owned()));
+ };
- let token = if let Some(pat) = user
- .personal_access_tokens
- .iter()
- .find(|pat| pat.name.as_str() == name)
- {
- pat.token.clone()
- } else {
- error!("Personal access token: {name} for user with ID: {user_id} does not exist.",);
- return Err(IggyError::ResourceNotFound(name.to_owned()));
- };
-
- info!("Deleting personal access token: {name} for user with ID: {user_id}...");
- user.personal_access_tokens.remove(&token);
+ info!("Deleting personal access token: {name} for user with ID: {user_id}...");
+ user.personal_access_tokens.remove(&token);
+ Ok(())
+ }).with_error_context(|error| {
+ format!(
+ "{COMPONENT} delete PAT (error: {error}) - failed to access user with id: {user_id}"
+ )
+ })??;
info!("Deleted personal access token: {name} for user with ID: {user_id}.");
Ok(())
}
@@ -182,9 +181,9 @@ impl IggyShard {
session: Option<&Session>,
) -> Result<User, IggyError> {
let token_hash = PersonalAccessToken::hash_token(token);
- let users = self.users.borrow();
+ let users = self.users.values();
let mut personal_access_token = None;
- for user in users.values() {
+ for user in &users {
if let Some(pat) = user.personal_access_tokens.get(&token_hash) {
personal_access_token = Some(pat);
break;
diff --git a/core/server/src/shard/system/segments.rs b/core/server/src/shard/system/segments.rs
index 055e0d76f..62d3ef0fa 100644
--- a/core/server/src/shard/system/segments.rs
+++ b/core/server/src/shard/system/segments.rs
@@ -44,7 +44,7 @@ impl IggyShard {
stream_id,
topic_id,
partition_id,
- |(_, stats,.., log)| {
+ |(_, stats, .., log)| {
let upperbound = log.segments().len();
let begin = upperbound.saturating_sub(segments_count as usize);
let segments = log
diff --git a/core/server/src/shard/system/streams.rs b/core/server/src/shard/system/streams.rs
index 4929d676e..1623d402a 100644
--- a/core/server/src/shard/system/streams.rs
+++ b/core/server/src/shard/system/streams.rs
@@ -148,14 +148,15 @@ impl IggyShard {
})?;
let mut stream = self.delete_stream2_base(id);
let stream_id_usize = stream.id();
-
+
// Clean up consumer groups from ClientManager for this stream
self.client_manager
.borrow_mut()
.delete_consumer_groups_for_stream(stream_id_usize);
-
+
// Remove all entries from shards_table for this stream (all topics and partitions)
- let namespaces_to_remove: Vec<_> = self.shards_table
+ let namespaces_to_remove: Vec<_> = self
+ .shards_table
.iter()
.filter_map(|entry| {
let (ns, _) = entry.pair();
@@ -166,11 +167,11 @@ impl IggyShard {
}
})
.collect();
-
+
for ns in namespaces_to_remove {
self.remove_shard_table_record(&ns);
}
-
+
delete_stream_from_disk(self.id, &mut stream, &self.config.system).await?;
Ok(stream)
}
@@ -229,13 +230,13 @@ mod tests {
use crate::shard::ShardInfo;
use crate::shard::transmission::connector::ShardConnector;
use crate::slab::streams::Streams;
+ use crate::slab::users::Users;
use crate::state::{MockState, StateKind};
use crate::streaming::session::Session;
use crate::streaming::streams;
use crate::streaming::users::user::User;
use crate::streaming::utils::ptr::EternalPtr;
use crate::versioning::SemanticVersion;
- use ahash::HashMap;
use dashmap::DashMap;
use iggy_common::defaults::{DEFAULT_ROOT_PASSWORD, DEFAULT_ROOT_USERNAME};
use std::net::{Ipv4Addr, SocketAddr};
@@ -250,11 +251,8 @@ mod tests {
let shards_table = Box::leak(shards_table);
let shards_table: EternalPtr<DashMap<crate::shard::namespace::IggyNamespace, ShardInfo>> =
shards_table.into();
-
- let users = HashMap::default();
+ let users = Users::new();
let state = StateKind::Mock(MockState::new());
-
- // Create single shard connection
let connections = vec![ShardConnector::new(0, 1)];
let builder = IggyShard::builder();
@@ -281,13 +279,12 @@ mod tests {
// Initialize root user and session
let root = User::root(DEFAULT_ROOT_USERNAME, DEFAULT_ROOT_PASSWORD);
+ let root_id = shard.users.insert(root);
let session = Session::new(
1,
- root.id,
+ root_id as u32,
SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 1234),
);
-
- shard.users.borrow_mut().insert(root.id, root);
shard
.permissioner
.borrow_mut()
@@ -340,13 +337,12 @@ mod tests {
// Initialize root user and session
let root = User::root(DEFAULT_ROOT_USERNAME, DEFAULT_ROOT_PASSWORD);
+ let root_id = shard.users.insert(root);
let session = Session::new(
1,
- root.id,
+ root_id as u32,
SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 1234),
);
-
- shard.users.borrow_mut().insert(root.id, root);
shard
.permissioner
.borrow_mut()
@@ -399,13 +395,12 @@ mod tests {
// Initialize root user and session
let root = User::root(DEFAULT_ROOT_USERNAME, DEFAULT_ROOT_PASSWORD);
+ let root_id = shard.users.insert(root);
let session = Session::new(
1,
- root.id,
+ root_id as u32,
SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 1234),
);
-
- shard.users.borrow_mut().insert(root.id, root);
shard
.permissioner
.borrow_mut()
diff --git a/core/server/src/shard/system/topics.rs b/core/server/src/shard/system/topics.rs
index bffd78e41..b061f104d 100644
--- a/core/server/src/shard/system/topics.rs
+++ b/core/server/src/shard/system/topics.rs
@@ -219,14 +219,15 @@ impl IggyShard {
})?;
let mut topic = self.delete_topic_base2(stream_id, topic_id);
let topic_id_numeric = topic.id();
-
+
// Clean up consumer groups from ClientManager for this topic
self.client_manager
.borrow_mut()
.delete_consumer_groups_for_topic(numeric_stream_id, topic_id_numeric);
-
+
// Remove all partition entries from shards_table for this topic
- let namespaces_to_remove: Vec<_> = self.shards_table
+ let namespaces_to_remove: Vec<_> = self
+ .shards_table
.iter()
.filter_map(|entry| {
let (ns, _) = entry.pair();
@@ -237,11 +238,11 @@ impl IggyShard {
}
})
.collect();
-
+
for ns in namespaces_to_remove {
self.remove_shard_table_record(&ns);
}
-
+
let parent = topic.stats().parent().clone();
// We need to borrow topic as mutable, as we are extracting partitions out of it, in order to close them.
let (messages_count, size_bytes, segments_count) =
@@ -347,6 +348,13 @@ impl IggyShard {
self.delete_segments_bypass_auth(stream_id, topic_id, part_id, u32::MAX)
.await?;
}
+
+ // Zero out topic stats after purging all partitions
+ self.streams2
+ .with_topic_by_id(stream_id, topic_id, |(_root, _aux, stats)| {
+ stats.zero_out_all();
+ });
+
Ok(())
}
}
diff --git a/core/server/src/shard/system/users.rs b/core/server/src/shard/system/users.rs
index 8aa7d9635..9ce5cb293 100644
--- a/core/server/src/shard/system/users.rs
+++ b/core/server/src/shard/system/users.rs
@@ -22,15 +22,12 @@ use crate::streaming::session::Session;
use crate::streaming::users::user::User;
use crate::streaming::utils::crypto;
use error_set::ErrContext;
+use iggy_common::Identifier;
use iggy_common::IggyError;
use iggy_common::Permissions;
use iggy_common::UserStatus;
-use iggy_common::{IdKind, Identifier};
-use std::cell::RefMut;
-use std::sync::atomic::{AtomicU32, Ordering};
use tracing::{error, warn};
-static USER_ID: AtomicU32 = AtomicU32::new(1);
const MAX_USERS: usize = u32::MAX as usize;
impl IggyShard {
@@ -62,54 +59,7 @@ impl IggyShard {
}
pub fn try_get_user(&self, user_id: &Identifier) -> Result<Option<User>, IggyError> {
- match user_id.kind {
- IdKind::Numeric => {
- let user = self.users.borrow().get(&user_id.get_u32_value()?).cloned();
- Ok(user)
- }
- IdKind::String => {
- let username = user_id.get_cow_str_value()?;
- let user = self
- .users
- .borrow()
- .iter()
- .find(|(_, user)| user.username == username)
- .map(|(_, user)| user.clone());
- Ok(user)
- }
- }
- }
-
- pub fn get_user_mut(&self, user_id: &Identifier) -> Result<RefMut<'_, User>, IggyError> {
- match user_id.kind {
- IdKind::Numeric => {
- let user_id = user_id.get_u32_value()?;
- let users = self.users.borrow_mut();
- let exists = users.contains_key(&user_id);
- if !exists {
- return Err(IggyError::ResourceNotFound(user_id.to_string()));
- }
- Ok(RefMut::map(users, |u| {
- let user = u.get_mut(&user_id);
- user.unwrap()
- }))
- }
- IdKind::String => {
- let username = user_id.get_cow_str_value()?;
- let users = self.users.borrow_mut();
- let exists = users.iter().any(|(_, user)| user.username == username);
- if !exists {
- return Err(IggyError::ResourceNotFound(user_id.to_string()));
- }
- Ok(RefMut::map(users, |u| {
- let user = u
- .iter_mut()
- .find(|(_, user)| user.username == username)
- .map(|(_, user)| user);
- user.unwrap()
- }))
- }
- }
+ self.users.get_by_identifier(user_id)
}
pub async fn get_users(&self, session: &Session) -> Result<Vec<User>, IggyError> {
@@ -123,7 +73,7 @@ impl IggyShard {
session.get_user_id()
)
})?;
- Ok(self.users.borrow().values().cloned().collect())
+ Ok(self.users.values())
}
pub fn create_user(
@@ -145,60 +95,49 @@ impl IggyShard {
)
})?;
- if self
- .users
- .borrow()
- .iter()
- .any(|(_, user)| user.username == username)
- {
+ if self.users.username_exists(username) {
error!("User: {username} already exists.");
return Err(IggyError::UserAlreadyExists);
}
- if self.users.borrow().len() >= MAX_USERS {
+ if self.users.len() >= MAX_USERS {
error!("Available users limit reached.");
return Err(IggyError::UsersLimitReached);
}
- // TODO: Tech debt, replace with Slab.
- USER_ID.fetch_add(1, Ordering::SeqCst);
- let current_user_id = USER_ID.load(Ordering::SeqCst);
- self.create_user_base(current_user_id, username, password, status, permissions)?;
- self.get_user(¤t_user_id.try_into()?)
+ let user_id = self.create_user_base(username, password, status, permissions)?;
+ self.get_user(&(user_id as u32).try_into()?)
.with_error_context(|error| {
- format!(
- "{COMPONENT} (error: {error}) - failed to get user with id: {current_user_id}"
- )
+ format!("{COMPONENT} (error: {error}) - failed to get user with id: {user_id}")
})
}
pub fn create_user_bypass_auth(
&self,
- user_id: u32,
+ _user_id: u32, // Ignored - Slab auto-assigns IDs
username: &str,
password: &str,
status: UserStatus,
permissions: Option<Permissions>,
) -> Result<(), IggyError> {
- self.create_user_base(user_id, username, password, status, permissions)?;
+ self.create_user_base(username, password, status, permissions)?;
Ok(())
}
fn create_user_base(
&self,
- user_id: u32,
username: &str,
password: &str,
status: UserStatus,
permissions: Option<Permissions>,
- ) -> Result<(), IggyError> {
- let user = User::new(user_id, username, password, status, permissions.clone());
+ ) -> Result<usize, IggyError> {
+ let user = User::new(0, username, password, status, permissions.clone());
+ let user_id = self.users.insert(user);
self.permissioner
.borrow_mut()
- .init_permissions_for_user(user_id, permissions);
- self.users.borrow_mut().insert(user.id, user);
+ .init_permissions_for_user(user_id as u32, permissions);
self.metrics.increment_users(1);
- Ok(())
+ Ok(user_id)
}
pub fn delete_user(&self, session: &Session, user_id: &Identifier) -> Result<User, IggyError> {
@@ -221,32 +160,30 @@ impl IggyShard {
}
fn delete_user_base(&self, user_id: &Identifier) -> Result<User, IggyError> {
- let existing_user_id;
- {
- let user = self.get_user(user_id).with_error_context(|error| {
- format!("{COMPONENT} (error: {error}) - failed to get user with id: {user_id}")
- })?;
- if user.is_root() {
- error!("Cannot delete the root user.");
- return Err(IggyError::CannotDeleteUser(user.id));
- }
+ let user = self.get_user(user_id).with_error_context(|error| {
+ format!("{COMPONENT} (error: {error}) - failed to get user with id: {user_id}")
+ })?;
- existing_user_id = user.id;
+ if user.is_root() {
+ error!("Cannot delete the root user.");
+ return Err(IggyError::CannotDeleteUser(user.id));
}
+ let user_slab_id = user.id as usize;
+ let user_u32_id = user.id;
+
let user = self
.users
- .borrow_mut()
- .remove(&existing_user_id)
+ .remove(user_slab_id)
.ok_or(IggyError::ResourceNotFound(user_id.to_string()))?;
self.permissioner
.borrow_mut()
- .delete_permissions_for_user(existing_user_id);
+ .delete_permissions_for_user(user_u32_id);
self.client_manager.borrow_mut()
- .delete_clients_for_user(existing_user_id)
+ .delete_clients_for_user(user_u32_id)
.with_error_context(|error| {
format!(
- "{COMPONENT} (error: {error}) - failed to delete clients for user with ID: {existing_user_id}"
+ "{COMPONENT} (error: {error}) - failed to delete clients for user with ID: {user_u32_id}"
)
})?;
self.metrics.decrement_users(1);
@@ -289,29 +226,26 @@ impl IggyShard {
username: Option<String>,
status: Option<UserStatus>,
) -> Result<User, IggyError> {
- if let Some(username) = username.to_owned() {
+ if let Some(ref new_username) = username {
let user = self.get_user(user_id)?;
- let existing_user = self.get_user(&username.to_owned().try_into()?);
+ let existing_user = self.get_user(&new_username.to_owned().try_into()?);
if existing_user.is_ok() && existing_user.unwrap().id != user.id {
- error!("User: {username} already exists.");
+ error!("User: {new_username} already exists.");
return Err(IggyError::UserAlreadyExists);
}
}
- let mut user = self.get_user_mut(user_id).with_error_context(|error| {
- format!("{COMPONENT} update user (error: {error}) - failed to get mutable reference to the user with id: {user_id}")
- })?;
- if let Some(username) = username {
- user.username = username;
- }
-
- if let Some(status) = status {
- user.status = status;
- }
- let cloned_user = user.clone();
- drop(user);
-
- Ok(cloned_user)
+ self.users.with_user_mut(user_id, |user| {
+ if let Some(username) = username {
+ user.username = username;
+ }
+ if let Some(status) = status {
+ user.status = status;
+ }
+ user.clone()
+ }).with_error_context(|error| {
+ format!("{COMPONENT} update user (error: {error}) - failed to update user with id: {user_id}")
+ })
}
pub fn update_permissions(
@@ -356,26 +290,21 @@ impl IggyShard {
user_id: &Identifier,
permissions: Option<Permissions>,
) -> Result<(), IggyError> {
- {
- let user: User = self.get_user(user_id).with_error_context(|error| {
- format!("{COMPONENT} (error: {error}) - failed to get user with id: {user_id}")
- })?;
+ let user: User = self.get_user(user_id).with_error_context(|error| {
+ format!("{COMPONENT} (error: {error}) - failed to get user with id: {user_id}")
+ })?;
- self.permissioner
- .borrow_mut()
- .update_permissions_for_user(user.id, permissions.clone());
- }
+ self.permissioner
+ .borrow_mut()
+ .update_permissions_for_user(user.id, permissions.clone());
- {
- let mut user = self.get_user_mut(user_id).with_error_context(|error| {
- format!(
- "{COMPONENT} update user permissions (error: {error}) - failed to get mutable reference to the user with id: {user_id}"
- )
- })?;
+ self.users.with_user_mut(user_id, |user| {
user.permissions = permissions;
- }
-
- Ok(())
+ }).with_error_context(|error| {
+ format!(
+ "{COMPONENT} update user permissions (error: {error}) - failed to update permissions for user with id: {user_id}"
+ )
+ })
}
pub fn change_password(
@@ -417,19 +346,19 @@ impl IggyShard {
current_password: &str,
new_password: &str,
) -> Result<(), IggyError> {
- let mut user = self.get_user_mut(user_id).with_error_context(|error| {
- format!("{COMPONENT} change password (error: {error}) - failed to get mutable reference to the user with id: {user_id}")
- })?;
- if !crypto::verify_password(current_password, &user.password) {
- error!(
- "Invalid current password for user: {} with ID: {user_id}.",
- user.username
- );
- return Err(IggyError::InvalidCredentials);
- }
-
- user.password = crypto::hash_password(new_password);
- Ok(())
+ self.users.with_user_mut(user_id, |user| {
+ if !crypto::verify_password(current_password, &user.password) {
+ error!(
+ "Invalid current password for user: {} with ID: {user_id}.",
+ user.username
+ );
+ return Err(IggyError::InvalidCredentials);
+ }
+ user.password = crypto::hash_password(new_password);
+ Ok(())
+ }).with_error_context(|error| {
+ format!("{COMPONENT} change password (error: {error}) - failed to change password for user with id: {user_id}")
+ })?
}
pub fn login_user_event(
diff --git a/core/server/src/shard/tasks/periodic/personal_access_token_cleaner.rs b/core/server/src/shard/tasks/periodic/personal_access_token_cleaner.rs
index 670b04ef9..3c1203a9a 100644
--- a/core/server/src/shard/tasks/periodic/personal_access_token_cleaner.rs
+++ b/core/server/src/shard/tasks/periodic/personal_access_token_cleaner.rs
@@ -48,8 +48,8 @@ async fn clear_personal_access_tokens(shard: Rc<IggyShard>) -> Result<(), IggyEr
let now = IggyTimestamp::now();
let mut total_removed = 0;
- let users = shard.users.borrow();
- for user in users.values() {
+ let users = shard.users.values();
+ for user in &users {
let expired_tokens: Vec<Arc<String>> = user
.personal_access_tokens
.iter()
diff --git a/core/server/src/slab/mod.rs b/core/server/src/slab/mod.rs
index 13c8f472f..0569f7749 100644
--- a/core/server/src/slab/mod.rs
+++ b/core/server/src/slab/mod.rs
@@ -4,6 +4,7 @@ pub mod partitions;
pub mod streams;
pub mod topics;
pub mod traits_ext;
+pub mod users;
use std::fmt::{Debug, Display};
diff --git a/core/server/src/slab/users.rs b/core/server/src/slab/users.rs
new file mode 100644
index 000000000..3b6ad44c4
--- /dev/null
+++ b/core/server/src/slab/users.rs
@@ -0,0 +1,142 @@
+use ahash::AHashMap;
+use iggy_common::{Identifier, IggyError};
+use slab::Slab;
+use std::cell::RefCell;
+
+use crate::streaming::users::user::User;
+
+const CAPACITY: usize = 1024;
+
+#[derive(Debug, Clone, Default)]
+pub struct Users {
+ index: RefCell<AHashMap<String, usize>>,
+ users: RefCell<Slab<User>>,
+}
+
+impl Users {
+ pub fn new() -> Self {
+ Self {
+ index: RefCell::new(AHashMap::with_capacity(CAPACITY)),
+ users: RefCell::new(Slab::with_capacity(CAPACITY)),
+ }
+ }
+
+ /// Insert a user and return the assigned ID (auto-incremented by Slab)
+ pub fn insert(&self, user: User) -> usize {
+ let username = user.username.clone();
+ let mut users = self.users.borrow_mut();
+ let mut index = self.index.borrow_mut();
+
+ let id = users.insert(user);
+ // Update the user's ID to match the Slab index
+ users[id].id = id as u32;
+ index.insert(username, id);
+ id
+ }
+
+ /// Get user by ID (numeric identifier)
+ pub fn get(&self, id: usize) -> Option<User> {
+ self.users.borrow().get(id).cloned()
+ }
+
+ /// Get user by username or ID (via Identifier enum)
+ pub fn get_by_identifier(&self, identifier: &Identifier) -> Result<Option<User>, IggyError> {
+ match identifier.kind {
+ iggy_common::IdKind::Numeric => {
+ let id = identifier.get_u32_value()? as usize;
+ Ok(self.users.borrow().get(id).cloned())
+ }
+ iggy_common::IdKind::String => {
+ let username = identifier.get_string_value()?;
+ let index = self.index.borrow();
+ if let Some(&id) = index.get(&username) {
+ Ok(self.users.borrow().get(id).cloned())
+ } else {
+ Ok(None)
+ }
+ }
+ }
+ }
+
+ /// Remove user by Slab index
+ pub fn remove(&self, id: usize) -> Option<User> {
+ let mut users = self.users.borrow_mut();
+ let mut index = self.index.borrow_mut();
+
+ if !users.contains(id) {
+ return None;
+ }
+
+ let user = users.remove(id);
+ index.remove(&user.username);
+ Some(user)
+ }
+
+ /// Check if user exists
+ pub fn contains(&self, identifier: &Identifier) -> bool {
+ match identifier.kind {
+ iggy_common::IdKind::Numeric => {
+ if let Ok(id) = identifier.get_u32_value() {
+ self.users.borrow().contains(id as usize)
+ } else {
+ false
+ }
+ }
+ iggy_common::IdKind::String => {
+ if let Ok(username) = identifier.get_string_value() {
+ self.index.borrow().contains_key(&username)
+ } else {
+ false
+ }
+ }
+ }
+ }
+
+ /// Get all users as a Vec
+ pub fn values(&self) -> Vec<User> {
+ self.users.borrow().iter().map(|(_, u)| u.clone()).collect()
+ }
+
+ /// Get number of users
+ pub fn len(&self) -> usize {
+ self.users.borrow().len()
+ }
+
+ /// Check if empty
+ pub fn is_empty(&self) -> bool {
+ self.users.borrow().is_empty()
+ }
+
+ /// Get mutable access to a user via closure (to avoid RefMut escaping issues)
+ pub fn with_user_mut<F, R>(&self, identifier: &Identifier, f: F) -> Result<R, IggyError>
+ where
+ F: FnOnce(&mut User) -> R,
+ {
+ let id = match identifier.kind {
+ iggy_common::IdKind::Numeric => identifier.get_u32_value()? as usize,
+ iggy_common::IdKind::String => {
+ let username = identifier.get_string_value()?;
+ let index = self.index.borrow();
+ *index
+ .get(&username)
+ .ok_or_else(|| IggyError::ResourceNotFound(username.to_string()))?
+ }
+ };
+
+ let mut users = self.users.borrow_mut();
+ let user = users
+ .get_mut(id)
+ .ok_or_else(|| IggyError::ResourceNotFound(identifier.to_string()))?;
+ Ok(f(user))
+ }
+
+ /// Check if username already exists (for validation during create/update)
+ pub fn username_exists(&self, username: &str) -> bool {
+ self.index.borrow().contains_key(username)
+ }
+
+ /// Get ID by username (useful for cross-references)
+ pub fn get_id_by_username(&self, username: &str) -> Option<usize> {
+ self.index.borrow().get(username).copied()
+ }
+}
diff --git a/core/server/src/streaming/session.rs b/core/server/src/streaming/session.rs
index c34e39d49..1afbd724d 100644
--- a/core/server/src/streaming/session.rs
+++ b/core/server/src/streaming/session.rs
@@ -45,7 +45,7 @@ impl Session {
}
pub fn from_client_id(client_id: u32, ip_address: SocketAddr) -> Self {
- Self::new(client_id, 0, ip_address)
+ Self::new(client_id, u32::MAX, ip_address)
}
pub fn get_user_id(&self) -> UserId {
@@ -61,7 +61,7 @@ impl Session {
}
pub fn clear_user_id(&self) {
- self.set_user_id(0);
+ self.set_user_id(u32::MAX);
}
pub fn is_active(&self) -> bool {
@@ -69,14 +69,14 @@ impl Session {
}
pub fn is_authenticated(&self) -> bool {
- self.get_user_id() > 0
+ self.get_user_id() != u32::MAX
}
}
impl Display for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let user_id = self.get_user_id();
- if user_id > 0 {
+ if user_id != u32::MAX {
write!(
f,
"client ID: {}, user ID: {}, IP address: {}",
diff --git a/core/server/src/streaming/users/user.rs b/core/server/src/streaming/users/user.rs
index 7e68d98ff..437ce955b 100644
--- a/core/server/src/streaming/users/user.rs
+++ b/core/server/src/streaming/users/user.rs
@@ -38,7 +38,7 @@ pub struct User {
impl Default for User {
fn default() -> Self {
Self {
- id: 1,
+ id: 0,
status: UserStatus::Active,
username: "user".to_string(),
password: "secret".to_string(),