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 2026/04/02 06:40:32 UTC
(iggy) 03/12: refactor(server): switch WAL to wire types and move domain commands to http DTOs
This is an automated email from the ASF dual-hosted git repository.
hgruszecki pushed a commit to branch refactor-binary-7-http
in repository https://gitbox.apache.org/repos/asf/iggy.git
commit 019f4aba6de9253db1d644e4942bfe267094327f
Author: Hubert Gruszecki <h....@gmail.com>
AuthorDate: Thu Mar 26 19:10:08 2026 +0100
refactor(server): switch WAL to wire types and move domain commands to http DTOs
EntryCommand serialized domain types via BytesSerializable for
WAL persistence while the same types carried serde for HTTP -
serving two masters with duplicate codec logic. Wire types in
iggy_binary_protocol produce identical bytes but were unused
for WAL because the WithId wrappers added server-assigned IDs.
Switch EntryCommand variants and WithId wrappers to wire types.
Use WireEncode/WireDecode for WAL serialization, codes from
iggy_binary_protocol::codes. Remove intermediate domain type
construction in execution.rs - wire types flow directly from
handler to WAL.
Rename commands/ to http/ as pure serde DTOs: strip
BytesSerializable, Command trait, Display impls, and roundtrip
tests (~5200 lines deleted). Delete the Command trait and
duplicate code constants from iggy_common. Migrate the
metadata crate's STM macro to decode via WireDecode on wire
request types. Fix simulator to use wire types directly.
WAL byte format is preserved - WireEncode produces identical
bytes to the former BytesSerializable (verified by all state
and integration tests).
---
Cargo.lock | 1 -
.../consumer_groups/create_consumer_group.rs | 189 ---------
.../consumer_groups/delete_consumer_group.rs | 147 -------
core/common/src/commands/messages/poll_messages.rs | 341 ----------------
.../src/commands/partitions/create_partitions.rs | 167 --------
.../src/commands/partitions/delete_partitions.rs | 167 --------
.../create_personal_access_token.rs | 157 --------
.../delete_personal_access_token.rs | 156 --------
.../src/commands/segments/delete_segments.rs | 202 ----------
core/common/src/commands/streams/create_stream.rs | 153 --------
core/common/src/commands/streams/delete_stream.rs | 99 -----
core/common/src/commands/streams/purge_stream.rs | 102 -----
core/common/src/commands/streams/update_stream.rs | 151 -------
core/common/src/commands/topics/create_topic.rs | 301 --------------
core/common/src/commands/topics/delete_topic.rs | 126 ------
core/common/src/commands/topics/purge_topic.rs | 124 ------
core/common/src/commands/topics/update_topic.rs | 302 --------------
core/common/src/commands/users/change_password.rs | 246 ------------
core/common/src/commands/users/create_user.rs | 347 ----------------
core/common/src/commands/users/delete_user.rs | 99 -----
.../src/commands/users/update_permissions.rs | 189 ---------
core/common/src/commands/users/update_user.rs | 231 -----------
.../http/consumer_groups/create_consumer_group.rs | 60 +++
.../http/consumer_groups/delete_consumer_group.rs | 46 +++
.../src/{commands => http}/consumer_groups/mod.rs | 0
.../src/{commands => http}/consumer_offsets/mod.rs | 0
core/common/src/{commands => http}/messages/mod.rs | 0
core/common/src/http/messages/poll_messages.rs | 131 +++++++
.../{commands => http}/messages/send_messages.rs | 31 +-
core/common/src/{commands => http}/mod.rs | 0
.../src/http/partitions/create_partitions.rs | 60 +++
.../src/http/partitions/delete_partitions.rs | 60 +++
.../src/{commands => http}/partitions/mod.rs | 0
.../create_personal_access_token.rs | 57 +++
.../delete_personal_access_token.rs | 52 +++
.../personal_access_tokens/mod.rs | 0
core/common/src/http/segments/delete_segments.rs | 59 +++
core/common/src/{commands => http}/segments/mod.rs | 0
core/common/src/http/streams/create_stream.rs | 49 +++
.../mod.rs => http/streams/delete_stream.rs} | 24 +-
core/common/src/{commands => http}/streams/mod.rs | 0
.../mod.rs => http/streams/purge_stream.rs} | 24 +-
core/common/src/http/streams/update_stream.rs | 55 +++
core/common/src/{commands => http}/system/mod.rs | 0
core/common/src/http/topics/create_topic.rs | 89 +++++
.../streams/mod.rs => http/topics/delete_topic.rs} | 28 +-
core/common/src/{commands => http}/topics/mod.rs | 0
.../streams/mod.rs => http/topics/purge_topic.rs} | 28 +-
core/common/src/http/topics/update_topic.rs | 86 ++++
core/common/src/http/users/change_password.rs | 74 ++++
core/common/src/http/users/create_user.rs | 76 ++++
.../src/{commands => http}/users/defaults.rs | 0
.../streams/mod.rs => http/users/delete_user.rs} | 24 +-
core/common/src/{commands => http}/users/mod.rs | 0
.../mod.rs => http/users/update_permissions.rs} | 28 +-
core/common/src/http/users/update_user.rs | 55 +++
core/common/src/lib.rs | 19 +-
core/common/src/types/command/mod.rs | 156 --------
core/common/src/types/message/mod.rs | 4 +-
core/integration/tests/state/file.rs | 33 +-
core/integration/tests/state/system.rs | 154 +++-----
core/metadata/Cargo.toml | 1 -
core/metadata/src/stm/consumer_group.rs | 115 +++---
core/metadata/src/stm/mod.rs | 10 +-
core/metadata/src/stm/stream.rs | 107 +++--
core/metadata/src/stm/user.rs | 84 ++--
core/server/src/http/segments.rs | 10 +-
core/server/src/quic/listener.rs | 4 +-
core/server/src/shard/execution.rs | 310 ++++++---------
core/server/src/state/command.rs | 234 ++++++-----
core/server/src/state/models.rs | 435 ++++++++-------------
core/server/src/state/system.rs | 193 +++++----
core/simulator/src/client.rs | 26 +-
73 files changed, 1877 insertions(+), 5211 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 9915a2f5e..66d8271d2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6800,7 +6800,6 @@ dependencies = [
"message_bus",
"paste",
"rmp-serde",
- "secrecy",
"serde",
"slab",
"tempfile",
diff --git a/core/common/src/commands/consumer_groups/create_consumer_group.rs b/core/common/src/commands/consumer_groups/create_consumer_group.rs
deleted file mode 100644
index f697bc9c7..000000000
--- a/core/common/src/commands/consumer_groups/create_consumer_group.rs
+++ /dev/null
@@ -1,189 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use super::MAX_NAME_LENGTH;
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Sizeable;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{CREATE_CONSUMER_GROUP_CODE, Command};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-use std::str::from_utf8;
-
-/// `CreateConsumerGroup` command creates a new consumer group for the topic.
-/// It has additional payload:
-/// - `stream_id` - unique stream ID (numeric or name).
-/// - `topic_id` - unique topic ID (numeric or name).
-/// - `name` - unique consumer group name, max length is 255 characters.
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct CreateConsumerGroup {
- /// Unique stream ID (numeric or name).
- #[serde(skip)]
- pub stream_id: Identifier,
- /// Unique topic ID (numeric or name).
- #[serde(skip)]
- pub topic_id: Identifier,
- /// Unique consumer group name, max length is 255 characters.
- pub name: String,
-}
-
-impl Command for CreateConsumerGroup {
- fn code(&self) -> u32 {
- CREATE_CONSUMER_GROUP_CODE
- }
-}
-
-impl Default for CreateConsumerGroup {
- fn default() -> Self {
- CreateConsumerGroup {
- stream_id: Identifier::default(),
- topic_id: Identifier::default(),
- name: "consumer_group_1".to_string(),
- }
- }
-}
-
-impl Validatable<IggyError> for CreateConsumerGroup {
- fn validate(&self) -> Result<(), IggyError> {
- if self.name.is_empty() || self.name.len() > MAX_NAME_LENGTH {
- return Err(IggyError::InvalidConsumerGroupName);
- }
-
- Ok(())
- }
-}
-
-impl BytesSerializable for CreateConsumerGroup {
- fn to_bytes(&self) -> Bytes {
- let stream_id_bytes = self.stream_id.to_bytes();
- let topic_id_bytes = self.topic_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(
- 1 + stream_id_bytes.len() + topic_id_bytes.len() + self.name.len(),
- );
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(self.name.len() as u8);
- bytes.put_slice(self.name.as_bytes());
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<CreateConsumerGroup, IggyError> {
- if bytes.len() < 6 {
- return Err(IggyError::InvalidCommand);
- }
-
- 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 name_length = *bytes.get(position).ok_or(IggyError::InvalidCommand)?;
- let name = from_utf8(
- bytes
- .get(position + 1..position + 1 + name_length as usize)
- .ok_or(IggyError::InvalidCommand)?,
- )
- .map_err(|_| IggyError::InvalidUtf8)?
- .to_string();
- let command = CreateConsumerGroup {
- stream_id,
- topic_id,
- name,
- };
- Ok(command)
- }
-}
-
-impl Display for CreateConsumerGroup {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}|{}|{}", self.stream_id, self.topic_id, self.name)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = CreateConsumerGroup {
- stream_id: Identifier::numeric(1).unwrap(),
- topic_id: Identifier::numeric(2).unwrap(),
- name: "test".to_string(),
- };
-
- 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 name_length = bytes[position];
- let name = from_utf8(&bytes[position + 1..position + 1 + name_length as usize]).unwrap();
- assert!(!bytes.is_empty());
- assert_eq!(stream_id, command.stream_id);
- assert_eq!(topic_id, command.topic_id);
- assert_eq!(name, command.name);
- }
-
- #[test]
- fn from_bytes_should_fail_on_empty_input() {
- assert!(CreateConsumerGroup::from_bytes(Bytes::new()).is_err());
- }
-
- #[test]
- fn from_bytes_should_fail_on_truncated_input() {
- let command = CreateConsumerGroup::default();
- let bytes = command.to_bytes();
- for i in 0..bytes.len() - 1 {
- let truncated = bytes.slice(..i);
- assert!(
- CreateConsumerGroup::from_bytes(truncated).is_err(),
- "expected error for truncation at byte {i}"
- );
- }
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let stream_id = Identifier::numeric(1).unwrap();
- let topic_id = Identifier::numeric(2).unwrap();
- let name = "test".to_string();
- let stream_id_bytes = stream_id.to_bytes();
- let topic_id_bytes = topic_id.to_bytes();
- let mut bytes =
- BytesMut::with_capacity(1 + stream_id_bytes.len() + topic_id_bytes.len() + name.len());
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(name.len() as u8);
- bytes.put_slice(name.as_bytes());
- let command = CreateConsumerGroup::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.stream_id, stream_id);
- assert_eq!(command.topic_id, topic_id);
- assert_eq!(command.name, name);
- }
-}
diff --git a/core/common/src/commands/consumer_groups/delete_consumer_group.rs b/core/common/src/commands/consumer_groups/delete_consumer_group.rs
deleted file mode 100644
index 859ded6f9..000000000
--- a/core/common/src/commands/consumer_groups/delete_consumer_group.rs
+++ /dev/null
@@ -1,147 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Sizeable;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{Command, DELETE_CONSUMER_GROUP_CODE};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-
-/// `DeleteConsumerGroup` command deletes an existing consumer group from the topic.
-/// It has additional payload:
-/// - `stream_id` - unique stream ID (numeric or name).
-/// - `topic_id` - unique topic ID (numeric or name).
-/// - `group_id` - unique consumer group ID (numeric or name).
-#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
-pub struct DeleteConsumerGroup {
- /// Unique stream ID (numeric or name).
- #[serde(skip)]
- pub stream_id: Identifier,
- /// Unique topic ID (numeric or name).
- #[serde(skip)]
- pub topic_id: Identifier,
- /// Unique consumer group ID (numeric or name).
- #[serde(skip)]
- pub group_id: Identifier,
-}
-
-impl Command for DeleteConsumerGroup {
- fn code(&self) -> u32 {
- DELETE_CONSUMER_GROUP_CODE
- }
-}
-
-impl Validatable<IggyError> for DeleteConsumerGroup {
- fn validate(&self) -> Result<(), IggyError> {
- Ok(())
- }
-}
-
-impl BytesSerializable for DeleteConsumerGroup {
- fn to_bytes(&self) -> Bytes {
- let stream_id_bytes = self.stream_id.to_bytes();
- let topic_id_bytes = self.topic_id.to_bytes();
- let group_id_bytes = self.group_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(
- stream_id_bytes.len() + topic_id_bytes.len() + group_id_bytes.len(),
- );
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_slice(&group_id_bytes);
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<DeleteConsumerGroup, IggyError> {
- if bytes.len() < 9 {
- return Err(IggyError::InvalidCommand);
- }
-
- 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 group_id = Identifier::from_bytes(bytes.slice(position..))?;
- let command = DeleteConsumerGroup {
- stream_id,
- topic_id,
- group_id,
- };
- Ok(command)
- }
-}
-
-impl Display for DeleteConsumerGroup {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}|{}|{}", self.stream_id, self.topic_id, self.group_id)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = DeleteConsumerGroup {
- stream_id: Identifier::numeric(1).unwrap(),
- topic_id: Identifier::numeric(2).unwrap(),
- group_id: Identifier::numeric(3).unwrap(),
- };
-
- 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 group_id = Identifier::from_bytes(bytes.slice(position..)).unwrap();
-
- assert!(!bytes.is_empty());
- assert_eq!(stream_id, command.stream_id);
- assert_eq!(topic_id, command.topic_id);
- assert_eq!(group_id, command.group_id);
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let stream_id = Identifier::numeric(1).unwrap();
- let topic_id = Identifier::numeric(2).unwrap();
- let group_id = Identifier::numeric(3).unwrap();
- let stream_id_bytes = stream_id.to_bytes();
- let topic_id_bytes = topic_id.to_bytes();
- let group_id_bytes = group_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(
- stream_id_bytes.len() + topic_id_bytes.len() + group_id_bytes.len(),
- );
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_slice(&group_id_bytes);
- let command = DeleteConsumerGroup::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.stream_id, stream_id);
- assert_eq!(command.topic_id, topic_id);
- assert_eq!(command.group_id, group_id);
- }
-}
diff --git a/core/common/src/commands/messages/poll_messages.rs b/core/common/src/commands/messages/poll_messages.rs
deleted file mode 100644
index ac266ca4c..000000000
--- a/core/common/src/commands/messages/poll_messages.rs
+++ /dev/null
@@ -1,341 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use crate::error::IggyError;
-use crate::{BytesSerializable, Identifier, PollingKind, PollingStrategy, Sizeable, Validatable};
-use crate::{Command, POLL_MESSAGES_CODE};
-use crate::{Consumer, ConsumerKind};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-
-pub const DEFAULT_PARTITION_ID: u32 = 0;
-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.
-/// - `stream_id` - unique stream ID (numeric or name).
-/// - `topic_id` - unique topic ID (numeric or name).
-/// - `partition_id` - partition ID from which messages will be polled. Has to be specified for the regular consumer. For consumer group it is ignored (use `None`).
-/// - `strategy` - polling strategy which specifies from where to start polling messages.
-/// - `count` - number of messages to poll.
-/// - `auto_commit` - whether to commit offset on the server automatically after polling the messages.
-#[derive(Debug, Serialize, Deserialize, PartialEq)]
-pub struct PollMessages {
- /// Consumer which will poll messages. Either regular consumer or consumer group.
- #[serde(flatten)]
- pub consumer: Consumer,
- /// Unique stream ID (numeric or name).
- #[serde(skip)]
- pub stream_id: Identifier,
- /// Unique topic ID (numeric or name).
- #[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 = "PollMessages::default_partition_id")]
- pub partition_id: Option<u32>,
- /// Polling strategy which specifies from where to start polling messages.
- #[serde(default = "PollingStrategy::default", flatten)]
- pub strategy: PollingStrategy,
- /// Number of messages to poll.
- #[serde(default = "PollMessages::default_number_of_messages_to_poll")]
- pub count: u32,
- /// Whether to commit offset on the server automatically after polling the messages.
- #[serde(default)]
- pub auto_commit: bool,
-}
-
-impl PollMessages {
- pub fn bytes(
- stream_id: &Identifier,
- topic_id: &Identifier,
- partition_id: Option<u32>,
- consumer: &Consumer,
- strategy: &PollingStrategy,
- count: u32,
- auto_commit: bool,
- ) -> Bytes {
- let consumer_bytes = consumer.to_bytes();
- let stream_id_bytes = stream_id.to_bytes();
- let topic_id_bytes = topic_id.to_bytes();
- let strategy_bytes = strategy.to_bytes();
- let mut bytes = BytesMut::with_capacity(
- 10 + consumer_bytes.len()
- + stream_id_bytes.len()
- + topic_id_bytes.len()
- + strategy_bytes.len(),
- );
- bytes.put_slice(&consumer_bytes);
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- // Encode partition_id with a flag byte: 1 = Some, 0 = None
- if let Some(partition_id) = partition_id {
- bytes.put_u8(1);
- bytes.put_u32_le(partition_id);
- } else {
- bytes.put_u8(0);
- bytes.put_u32_le(0); // Padding to keep structure consistent
- }
- bytes.put_slice(&strategy_bytes);
- bytes.put_u32_le(count);
- if auto_commit {
- bytes.put_u8(1);
- } else {
- bytes.put_u8(0);
- }
-
- bytes.freeze()
- }
-
- pub fn default_number_of_messages_to_poll() -> u32 {
- DEFAULT_NUMBER_OF_MESSAGES_TO_POLL
- }
-
- pub fn default_partition_id() -> Option<u32> {
- Some(DEFAULT_PARTITION_ID)
- }
-}
-
-impl Default for PollMessages {
- fn default() -> Self {
- Self {
- consumer: Consumer::default(),
- stream_id: Identifier::numeric(1).unwrap(),
- topic_id: Identifier::numeric(1).unwrap(),
- partition_id: PollMessages::default_partition_id(),
- strategy: PollingStrategy::default(),
- count: PollMessages::default_number_of_messages_to_poll(),
- auto_commit: false,
- }
- }
-}
-
-impl Command for PollMessages {
- fn code(&self) -> u32 {
- POLL_MESSAGES_CODE
- }
-}
-
-impl Validatable<IggyError> for PollMessages {
- fn validate(&self) -> Result<(), IggyError> {
- Ok(())
- }
-}
-
-impl BytesSerializable for PollMessages {
- fn to_bytes(&self) -> Bytes {
- PollMessages::bytes(
- &self.stream_id,
- &self.topic_id,
- self.partition_id,
- &self.consumer,
- &self.strategy,
- self.count,
- self.auto_commit,
- )
- }
-
- fn from_bytes(bytes: Bytes) -> Result<Self, IggyError> {
- if bytes.len() < 30 {
- return Err(IggyError::InvalidCommand);
- }
-
- let mut position = 0;
- let consumer_kind =
- ConsumerKind::from_code(*bytes.first().ok_or(IggyError::InvalidCommand)?)?;
- let consumer_id = Identifier::from_bytes(bytes.slice(1..))?;
- position += 1 + consumer_id.get_size_bytes().as_bytes_usize();
- let consumer = Consumer {
- kind: consumer_kind,
- id: consumer_id,
- };
- let stream_id = Identifier::from_bytes(bytes.slice(position..))?;
- 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 has_partition_id = *bytes.get(position).ok_or(IggyError::InvalidCommand)?;
- let partition_id_value = u32::from_le_bytes(
- bytes
- .get(position + 1..position + 5)
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let partition_id = if has_partition_id == 1 {
- Some(partition_id_value)
- } else {
- None
- };
- let polling_kind =
- PollingKind::from_code(*bytes.get(position + 5).ok_or(IggyError::InvalidCommand)?)?;
- position += 6;
- let value = u64::from_le_bytes(
- bytes
- .get(position..position + 8)
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let strategy = PollingStrategy {
- kind: polling_kind,
- value,
- };
- let count = u32::from_le_bytes(
- bytes
- .get(position + 8..position + 12)
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let auto_commit = *bytes.get(position + 12).ok_or(IggyError::InvalidCommand)? == 1;
- let command = PollMessages {
- consumer,
- stream_id,
- topic_id,
- partition_id,
- strategy,
- count,
- auto_commit,
- };
- Ok(command)
- }
-}
-
-impl Display for PollMessages {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "{}|{}|{}|{}|{}|{}|{}",
- self.consumer,
- self.stream_id,
- self.topic_id,
- self.partition_id.unwrap_or(0),
- self.strategy,
- self.count,
- auto_commit_to_string(self.auto_commit)
- )
- }
-}
-
-fn auto_commit_to_string(auto_commit: bool) -> &'static str {
- if auto_commit { "a" } else { "n" }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = PollMessages {
- consumer: Consumer::new(Identifier::numeric(1).unwrap()),
- stream_id: Identifier::numeric(2).unwrap(),
- topic_id: Identifier::numeric(3).unwrap(),
- partition_id: Some(4),
- strategy: PollingStrategy::offset(2),
- count: 3,
- auto_commit: true,
- };
-
- let bytes = command.to_bytes();
- let mut position = 0;
- let consumer_kind = ConsumerKind::from_code(bytes[0]).unwrap();
- let consumer_id = Identifier::from_bytes(bytes.slice(1..)).unwrap();
- position += 1 + consumer_id.get_size_bytes().as_bytes_usize();
- let consumer = Consumer {
- kind: consumer_kind,
- id: consumer_id,
- };
- let stream_id = Identifier::from_bytes(bytes.slice(position..)).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 has_partition_id = bytes[position];
- let partition_id =
- u32::from_le_bytes(bytes[position + 1..position + 5].try_into().unwrap());
- let partition_id = if has_partition_id == 1 {
- Some(partition_id)
- } else {
- None
- };
- let polling_kind = PollingKind::from_code(bytes[position + 5]).unwrap();
- position += 6;
- let value = u64::from_le_bytes(bytes[position..position + 8].try_into().unwrap());
- let strategy = PollingStrategy {
- kind: polling_kind,
- value,
- };
- let count = u32::from_le_bytes(bytes[position + 8..position + 12].try_into().unwrap());
- let auto_commit = bytes[position + 12];
- let auto_commit = matches!(auto_commit, 1);
-
- assert!(!bytes.is_empty());
- assert_eq!(consumer, command.consumer);
- assert_eq!(stream_id, command.stream_id);
- assert_eq!(topic_id, command.topic_id);
- assert_eq!(partition_id, command.partition_id);
- assert_eq!(strategy, command.strategy);
- assert_eq!(count, command.count);
- assert_eq!(auto_commit, command.auto_commit);
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let consumer = Consumer::new(Identifier::numeric(1).unwrap());
- let stream_id = Identifier::numeric(2).unwrap();
- let topic_id = Identifier::numeric(3).unwrap();
- let partition_id = 4u32;
- let strategy = PollingStrategy::offset(2);
- let count = 3u32;
- let auto_commit = 1u8;
-
- let consumer_bytes = consumer.to_bytes();
- let stream_id_bytes = stream_id.to_bytes();
- let topic_id_bytes = topic_id.to_bytes();
- let strategy_bytes = strategy.to_bytes();
- let mut bytes = BytesMut::with_capacity(
- 10 + consumer_bytes.len()
- + stream_id_bytes.len()
- + topic_id_bytes.len()
- + strategy_bytes.len(),
- );
- bytes.put_slice(&consumer_bytes);
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_u8(1); // Flag: partition_id is Some
- bytes.put_u32_le(partition_id);
- bytes.put_slice(&strategy_bytes);
- bytes.put_u32_le(count);
- bytes.put_u8(auto_commit);
-
- let command = PollMessages::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let auto_commit = matches!(auto_commit, 1);
-
- let command = command.unwrap();
- assert_eq!(command.consumer, consumer);
- assert_eq!(command.stream_id, stream_id);
- assert_eq!(command.topic_id, topic_id);
- assert_eq!(command.partition_id, Some(partition_id));
- assert_eq!(command.strategy, strategy);
- assert_eq!(command.count, count);
- assert_eq!(command.auto_commit, auto_commit);
- }
-}
diff --git a/core/common/src/commands/partitions/create_partitions.rs b/core/common/src/commands/partitions/create_partitions.rs
deleted file mode 100644
index 2bd9ee454..000000000
--- a/core/common/src/commands/partitions/create_partitions.rs
+++ /dev/null
@@ -1,167 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use super::MAX_PARTITIONS_COUNT;
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Sizeable;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{CREATE_PARTITIONS_CODE, Command};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-
-/// `CreatePartitions` command is used to create new partitions for a topic.
-/// It has additional payload:
-/// - `stream_id` - unique stream ID (numeric or name).
-/// - `topic_id` - unique topic ID (numeric or name).
-/// - `partitions_count` - number of partitions in the topic to create, max value is 1000.
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct CreatePartitions {
- /// Unique stream ID (numeric or name).
- #[serde(skip)]
- pub stream_id: Identifier,
- /// Unique topic ID (numeric or name).
- #[serde(skip)]
- pub topic_id: Identifier,
- /// Number of partitions in the topic to create, max value is 1000.
- pub partitions_count: u32,
-}
-
-impl Command for CreatePartitions {
- fn code(&self) -> u32 {
- CREATE_PARTITIONS_CODE
- }
-}
-
-impl Default for CreatePartitions {
- fn default() -> Self {
- CreatePartitions {
- stream_id: Identifier::default(),
- topic_id: Identifier::default(),
- partitions_count: 1,
- }
- }
-}
-
-impl Validatable<IggyError> for CreatePartitions {
- fn validate(&self) -> Result<(), IggyError> {
- if !(1..=MAX_PARTITIONS_COUNT).contains(&self.partitions_count) {
- return Err(IggyError::TooManyPartitions);
- }
-
- Ok(())
- }
-}
-
-impl BytesSerializable for CreatePartitions {
- fn to_bytes(&self) -> Bytes {
- let stream_id_bytes = self.stream_id.to_bytes();
- let topic_id_bytes = self.topic_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(4 + stream_id_bytes.len() + topic_id_bytes.len());
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_u32_le(self.partitions_count);
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> std::result::Result<CreatePartitions, IggyError> {
- if bytes.len() < 10 {
- return Err(IggyError::InvalidCommand);
- }
-
- 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 partitions_count = u32::from_le_bytes(
- bytes
- .get(position..position + 4)
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let command = CreatePartitions {
- stream_id,
- topic_id,
- partitions_count,
- };
- Ok(command)
- }
-}
-
-impl Display for CreatePartitions {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "{}|{}|{}",
- self.stream_id, self.topic_id, self.partitions_count
- )
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use bytes::BufMut;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = CreatePartitions {
- stream_id: Identifier::numeric(1).unwrap(),
- topic_id: Identifier::numeric(2).unwrap(),
- partitions_count: 3,
- };
-
- 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 partitions_count =
- u32::from_le_bytes(bytes[position..position + 4].try_into().unwrap());
-
- assert!(!bytes.is_empty());
- assert_eq!(stream_id, command.stream_id);
- assert_eq!(topic_id, command.topic_id);
- assert_eq!(partitions_count, command.partitions_count);
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let stream_id = Identifier::numeric(1).unwrap();
- let topic_id = Identifier::numeric(2).unwrap();
- let partitions_count = 3u32;
- let stream_id_bytes = stream_id.to_bytes();
- let topic_id_bytes = topic_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(4 + stream_id_bytes.len() + topic_id_bytes.len());
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_u32_le(partitions_count);
- let command = CreatePartitions::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.stream_id, stream_id);
- assert_eq!(command.topic_id, topic_id);
- assert_eq!(command.partitions_count, partitions_count);
- }
-}
diff --git a/core/common/src/commands/partitions/delete_partitions.rs b/core/common/src/commands/partitions/delete_partitions.rs
deleted file mode 100644
index 9e0cf1ddc..000000000
--- a/core/common/src/commands/partitions/delete_partitions.rs
+++ /dev/null
@@ -1,167 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use super::MAX_PARTITIONS_COUNT;
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Sizeable;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{Command, DELETE_PARTITIONS_CODE};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-
-/// `DeletePartitions` command is used to delete partitions from a topic.
-/// It has additional payload:
-/// - `stream_id` - unique stream ID (numeric or name).
-/// - `topic_id` - unique topic ID (numeric or name).
-/// - `partitions_count` - number of partitions in the topic to delete, max value is 1000.
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct DeletePartitions {
- /// Unique stream ID (numeric or name).
- #[serde(skip)]
- pub stream_id: Identifier,
- /// Unique topic ID (numeric or name).
- #[serde(skip)]
- pub topic_id: Identifier,
- /// Number of partitions in the topic to delete, max value is 1000.
- pub partitions_count: u32,
-}
-
-impl Command for DeletePartitions {
- fn code(&self) -> u32 {
- DELETE_PARTITIONS_CODE
- }
-}
-
-impl Default for DeletePartitions {
- fn default() -> Self {
- DeletePartitions {
- stream_id: Identifier::default(),
- topic_id: Identifier::default(),
- partitions_count: 1,
- }
- }
-}
-
-impl Validatable<IggyError> for DeletePartitions {
- fn validate(&self) -> Result<(), IggyError> {
- if !(1..=MAX_PARTITIONS_COUNT).contains(&self.partitions_count) {
- return Err(IggyError::TooManyPartitions);
- }
-
- Ok(())
- }
-}
-
-impl BytesSerializable for DeletePartitions {
- fn to_bytes(&self) -> Bytes {
- let stream_id_bytes = self.stream_id.to_bytes();
- let topic_id_bytes = self.topic_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(4 + stream_id_bytes.len() + topic_id_bytes.len());
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_u32_le(self.partitions_count);
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> std::result::Result<DeletePartitions, IggyError> {
- if bytes.len() < 10 {
- return Err(IggyError::InvalidCommand);
- }
-
- 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 partitions_count = u32::from_le_bytes(
- bytes
- .get(position..position + 4)
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let command = DeletePartitions {
- stream_id,
- topic_id,
- partitions_count,
- };
- Ok(command)
- }
-}
-
-impl Display for DeletePartitions {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "{}|{}|{}",
- self.stream_id, self.topic_id, self.partitions_count
- )
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use bytes::BufMut;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = DeletePartitions {
- stream_id: Identifier::numeric(1).unwrap(),
- topic_id: Identifier::numeric(2).unwrap(),
- partitions_count: 3,
- };
-
- 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 partitions_count =
- u32::from_le_bytes(bytes[position..position + 4].try_into().unwrap());
-
- assert!(!bytes.is_empty());
- assert_eq!(stream_id, command.stream_id);
- assert_eq!(topic_id, command.topic_id);
- assert_eq!(partitions_count, command.partitions_count);
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let stream_id = Identifier::numeric(1).unwrap();
- let topic_id = Identifier::numeric(2).unwrap();
- let partitions_count = 3u32;
- let stream_id_bytes = stream_id.to_bytes();
- let topic_id_bytes = topic_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(4 + stream_id_bytes.len() + topic_id_bytes.len());
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_u32_le(partitions_count);
- let command = DeletePartitions::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.stream_id, stream_id);
- assert_eq!(command.topic_id, topic_id);
- assert_eq!(command.partitions_count, partitions_count);
- }
-}
diff --git a/core/common/src/commands/personal_access_tokens/create_personal_access_token.rs b/core/common/src/commands/personal_access_tokens/create_personal_access_token.rs
deleted file mode 100644
index 395822854..000000000
--- a/core/common/src/commands/personal_access_tokens/create_personal_access_token.rs
+++ /dev/null
@@ -1,157 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use crate::BytesSerializable;
-use crate::Validatable;
-use crate::defaults::*;
-use crate::error::IggyError;
-use crate::utils::expiry::IggyExpiry;
-use crate::{CREATE_PERSONAL_ACCESS_TOKEN_CODE, Command};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::{Display, Formatter};
-use std::str::from_utf8;
-
-/// `CreatePersonalAccessToken` command is used to create a new personal access token for the authenticated user.
-/// It has additional payload:
-/// - `name` - unique name of the token, must be between 3 and 30 characters long.
-/// - `expiry` - expiry of the token.
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct CreatePersonalAccessToken {
- /// Unique name of the token, must be between 3 and 30 characters long.
- pub name: String,
- /// Expiry of the token.
- pub expiry: IggyExpiry,
-}
-
-impl Command for CreatePersonalAccessToken {
- fn code(&self) -> u32 {
- CREATE_PERSONAL_ACCESS_TOKEN_CODE
- }
-}
-
-impl Default for CreatePersonalAccessToken {
- fn default() -> Self {
- CreatePersonalAccessToken {
- name: "token".to_string(),
- expiry: IggyExpiry::NeverExpire,
- }
- }
-}
-
-impl Validatable<IggyError> for CreatePersonalAccessToken {
- fn validate(&self) -> Result<(), IggyError> {
- if self.name.is_empty()
- || self.name.len() > MAX_PERSONAL_ACCESS_TOKEN_NAME_LENGTH
- || self.name.len() < MIN_PERSONAL_ACCESS_TOKEN_NAME_LENGTH
- {
- return Err(IggyError::InvalidPersonalAccessTokenName);
- }
-
- Ok(())
- }
-}
-
-impl BytesSerializable for CreatePersonalAccessToken {
- fn to_bytes(&self) -> Bytes {
- let mut bytes = BytesMut::with_capacity(5 + self.name.len());
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(self.name.len() as u8);
- bytes.put_slice(self.name.as_bytes());
- bytes.put_u64_le(self.expiry.into());
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<CreatePersonalAccessToken, IggyError> {
- if bytes.len() < 12 {
- return Err(IggyError::InvalidCommand);
- }
-
- let name_length = *bytes.first().ok_or(IggyError::InvalidCommand)? as usize;
- let name = from_utf8(
- bytes
- .get(1..1 + name_length)
- .ok_or(IggyError::InvalidCommand)?,
- )
- .map_err(|_| IggyError::InvalidUtf8)?
- .to_string();
-
- let position = 1 + name_length;
- let expiry = u64::from_le_bytes(
- bytes
- .get(position..position + 8)
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let expiry: IggyExpiry = expiry.into();
-
- let command = CreatePersonalAccessToken { name, expiry };
- Ok(command)
- }
-}
-
-impl Display for CreatePersonalAccessToken {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}|{}", self.name, self.expiry)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = CreatePersonalAccessToken {
- name: "test".to_string(),
- expiry: IggyExpiry::NeverExpire,
- };
-
- let bytes = command.to_bytes();
- let name_length = bytes[0];
- let name = from_utf8(&bytes[1..1 + name_length as usize]).unwrap();
- let expiry = u64::from_le_bytes(
- bytes[1 + name_length as usize..9 + name_length as usize]
- .try_into()
- .unwrap(),
- );
- let expiry: IggyExpiry = expiry.into();
- assert!(!bytes.is_empty());
- assert_eq!(name, command.name);
- assert_eq!(expiry, command.expiry);
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let name = "test";
- let expiry = IggyExpiry::NeverExpire;
- let mut bytes = BytesMut::new();
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(name.len() as u8);
- bytes.put_slice(name.as_bytes());
- bytes.put_u64_le(expiry.into());
-
- let command = CreatePersonalAccessToken::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.name, name);
- assert_eq!(command.expiry, expiry);
- }
-}
diff --git a/core/common/src/commands/personal_access_tokens/delete_personal_access_token.rs b/core/common/src/commands/personal_access_tokens/delete_personal_access_token.rs
deleted file mode 100644
index 0d19b68c9..000000000
--- a/core/common/src/commands/personal_access_tokens/delete_personal_access_token.rs
+++ /dev/null
@@ -1,156 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use crate::Command;
-use crate::Validatable;
-use crate::defaults::*;
-use crate::error::IggyError;
-use crate::{BytesSerializable, DELETE_PERSONAL_ACCESS_TOKEN_CODE};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::{Display, Formatter};
-use std::str::from_utf8;
-
-/// `DeletePersonalAccessToken` command is used to delete a personal access token for the authenticated user.
-/// It has additional payload:
-/// - `name` - unique name of the token, must be between 3 and 30 characters long.
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct DeletePersonalAccessToken {
- /// Unique name of the token, must be between 3 and 30 characters long.
- pub name: String,
-}
-
-impl Command for DeletePersonalAccessToken {
- fn code(&self) -> u32 {
- DELETE_PERSONAL_ACCESS_TOKEN_CODE
- }
-}
-
-impl Default for DeletePersonalAccessToken {
- fn default() -> Self {
- DeletePersonalAccessToken {
- name: "token".to_string(),
- }
- }
-}
-
-impl Validatable<IggyError> for DeletePersonalAccessToken {
- fn validate(&self) -> Result<(), IggyError> {
- if self.name.is_empty()
- || self.name.len() > MAX_PERSONAL_ACCESS_TOKEN_NAME_LENGTH
- || self.name.len() < MIN_PERSONAL_ACCESS_TOKEN_NAME_LENGTH
- {
- return Err(IggyError::InvalidPersonalAccessTokenName);
- }
-
- Ok(())
- }
-}
-
-impl BytesSerializable for DeletePersonalAccessToken {
- fn to_bytes(&self) -> Bytes {
- let mut bytes = BytesMut::with_capacity(5 + self.name.len());
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(self.name.len() as u8);
- bytes.put_slice(self.name.as_bytes());
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<DeletePersonalAccessToken, IggyError> {
- if bytes.len() < 4 {
- return Err(IggyError::InvalidCommand);
- }
-
- let name_length = *bytes.first().ok_or(IggyError::InvalidCommand)? as usize;
- let name = from_utf8(
- bytes
- .get(1..1 + name_length)
- .ok_or(IggyError::InvalidCommand)?,
- )
- .map_err(|_| IggyError::InvalidUtf8)?
- .to_string();
-
- let command = DeletePersonalAccessToken { name };
- Ok(command)
- }
-}
-
-impl Display for DeletePersonalAccessToken {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}", self.name)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = DeletePersonalAccessToken {
- name: "test".to_string(),
- };
-
- let bytes = command.to_bytes();
- let name_length = bytes[0];
- let name = from_utf8(&bytes[1..1 + name_length as usize]).unwrap();
- assert!(!bytes.is_empty());
- assert_eq!(name, command.name);
- }
-
- #[test]
- fn from_bytes_should_fail_on_empty_input() {
- assert!(DeletePersonalAccessToken::from_bytes(Bytes::new()).is_err());
- }
-
- #[test]
- fn from_bytes_should_fail_on_truncated_input() {
- let command = DeletePersonalAccessToken::default();
- let bytes = command.to_bytes();
- for i in 0..bytes.len() - 1 {
- let truncated = bytes.slice(..i);
- assert!(
- DeletePersonalAccessToken::from_bytes(truncated).is_err(),
- "expected error for truncation at byte {i}"
- );
- }
- }
-
- #[test]
- fn from_bytes_should_fail_on_corrupted_name_length() {
- let mut buf = BytesMut::new();
- buf.put_u8(255);
- buf.put_slice(b"short");
- assert!(DeletePersonalAccessToken::from_bytes(buf.freeze()).is_err());
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let name = "test";
- let mut bytes = BytesMut::new();
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(name.len() as u8);
- bytes.put_slice(name.as_bytes());
-
- let command = DeletePersonalAccessToken::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.name, name);
- }
-}
diff --git a/core/common/src/commands/segments/delete_segments.rs b/core/common/src/commands/segments/delete_segments.rs
deleted file mode 100644
index c57833f4c..000000000
--- a/core/common/src/commands/segments/delete_segments.rs
+++ /dev/null
@@ -1,202 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Sizeable;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{Command, DELETE_SEGMENTS_CODE};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-
-/// `DeleteSegments` command is used to delete segments from a partition.
-/// It has additional payload:
-/// - `stream_id` - unique stream ID (numeric or name).
-/// - `topic_id` - unique topic ID (numeric or name).
-/// - `partition_id` - unique partition ID (numeric or name).
-/// - `segments_count` - number of segments in the partition to delete.
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct DeleteSegments {
- /// Unique stream ID (numeric or name).
- #[serde(skip)]
- pub stream_id: Identifier,
- /// Unique topic ID (numeric or name).
- #[serde(skip)]
- pub topic_id: Identifier,
- /// Unique partition ID (numeric or name).
- #[serde(skip)]
- pub partition_id: u32,
- /// Number of segments in the partition to delete, max value is 1000.
- pub segments_count: u32,
-}
-
-impl Command for DeleteSegments {
- fn code(&self) -> u32 {
- DELETE_SEGMENTS_CODE
- }
-}
-
-impl Default for DeleteSegments {
- fn default() -> Self {
- DeleteSegments {
- segments_count: 1,
- stream_id: Identifier::default(),
- topic_id: Identifier::default(),
- partition_id: u32::default(),
- }
- }
-}
-
-impl Validatable<IggyError> for DeleteSegments {
- fn validate(&self) -> Result<(), IggyError> {
- Ok(())
- }
-}
-
-impl BytesSerializable for DeleteSegments {
- fn to_bytes(&self) -> Bytes {
- let stream_id_bytes = self.stream_id.to_bytes();
- let topic_id_bytes = self.topic_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(
- std::mem::size_of::<u32>()
- + std::mem::size_of::<u32>()
- + stream_id_bytes.len()
- + topic_id_bytes.len(),
- );
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_u32_le(self.partition_id);
- bytes.put_u32_le(self.segments_count);
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> std::result::Result<DeleteSegments, IggyError> {
- if bytes.len() < 10 {
- return Err(IggyError::InvalidCommand);
- }
-
- 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 partition_id = u32::from_le_bytes(
- bytes
- .get(position..position + std::mem::size_of::<u32>())
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- position += std::mem::size_of::<u32>();
- let segments_count = u32::from_le_bytes(
- bytes
- .get(position..position + std::mem::size_of::<u32>())
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let command = DeleteSegments {
- stream_id,
- topic_id,
- partition_id,
- segments_count,
- };
- Ok(command)
- }
-}
-
-impl Display for DeleteSegments {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "{}|{}|{}|{}",
- self.stream_id, self.topic_id, self.partition_id, self.segments_count
- )
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use bytes::BufMut;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = DeleteSegments {
- stream_id: Identifier::numeric(1).unwrap(),
- topic_id: Identifier::numeric(2).unwrap(),
- partition_id: 3,
- segments_count: 3,
- };
-
- 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 partition_id = u32::from_le_bytes(
- bytes[position..position + std::mem::size_of::<u32>()]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)
- .unwrap(),
- );
- position += std::mem::size_of::<u32>();
- let segments_count = u32::from_le_bytes(
- bytes[position..position + std::mem::size_of::<u32>()]
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)
- .unwrap(),
- );
-
- assert!(!bytes.is_empty());
- assert_eq!(stream_id, command.stream_id);
- assert_eq!(topic_id, command.topic_id);
- assert_eq!(partition_id, command.partition_id);
- assert_eq!(segments_count, command.segments_count);
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let stream_id = Identifier::numeric(1).unwrap();
- let topic_id = Identifier::numeric(2).unwrap();
- let partition_id = 3;
- let segments_count = 3u32;
- let stream_id_bytes = stream_id.to_bytes();
- let topic_id_bytes = topic_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(
- std::mem::size_of::<u32>()
- + std::mem::size_of::<u32>()
- + stream_id_bytes.len()
- + topic_id_bytes.len(),
- );
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_u32_le(partition_id);
- bytes.put_u32_le(segments_count);
- let command = DeleteSegments::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(stream_id, command.stream_id);
- assert_eq!(topic_id, command.topic_id);
- assert_eq!(partition_id, command.partition_id);
- assert_eq!(segments_count, command.segments_count);
- }
-}
diff --git a/core/common/src/commands/streams/create_stream.rs b/core/common/src/commands/streams/create_stream.rs
deleted file mode 100644
index d5964eb5e..000000000
--- a/core/common/src/commands/streams/create_stream.rs
+++ /dev/null
@@ -1,153 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use super::MAX_NAME_LENGTH;
-use crate::BytesSerializable;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{CREATE_STREAM_CODE, Command};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-use std::str::from_utf8;
-
-/// `CreateStream` command is used to create a new stream.
-/// It has additional payload:
-/// - `name` - unique stream name (string), max length is 255 characters.
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct CreateStream {
- /// Unique stream name (string), max length is 255 characters.
- pub name: String,
-}
-
-impl Command for CreateStream {
- fn code(&self) -> u32 {
- CREATE_STREAM_CODE
- }
-}
-
-impl Default for CreateStream {
- fn default() -> Self {
- CreateStream {
- name: "stream".to_string(),
- }
- }
-}
-
-impl Validatable<IggyError> for CreateStream {
- fn validate(&self) -> Result<(), IggyError> {
- if self.name.is_empty() || self.name.len() > MAX_NAME_LENGTH {
- return Err(IggyError::InvalidStreamName);
- }
-
- Ok(())
- }
-}
-
-impl BytesSerializable for CreateStream {
- fn to_bytes(&self) -> Bytes {
- let mut bytes = BytesMut::with_capacity(5 + self.name.len());
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(self.name.len() as u8);
- bytes.put_slice(self.name.as_bytes());
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<CreateStream, IggyError> {
- if bytes.len() < 2 {
- return Err(IggyError::InvalidCommand);
- }
-
- let name_length = *bytes.first().ok_or(IggyError::InvalidCommand)? as usize;
- let name = from_utf8(
- bytes
- .get(1..1 + name_length)
- .ok_or(IggyError::InvalidCommand)?,
- )
- .map_err(|_| IggyError::InvalidUtf8)?
- .to_string();
-
- let command = CreateStream { name };
- Ok(command)
- }
-}
-
-impl Display for CreateStream {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}", self.name)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = CreateStream {
- name: "test".to_string(),
- };
-
- let bytes = command.to_bytes();
- let name_length = bytes[0];
- let name = from_utf8(&bytes[1..1 + name_length as usize]).unwrap();
-
- assert!(!bytes.is_empty());
- assert_eq!(name, command.name);
- }
-
- #[test]
- fn from_bytes_should_fail_on_empty_input() {
- assert!(CreateStream::from_bytes(Bytes::new()).is_err());
- }
-
- #[test]
- fn from_bytes_should_fail_on_truncated_input() {
- let command = CreateStream::default();
- let bytes = command.to_bytes();
- for i in 0..bytes.len() - 1 {
- let truncated = bytes.slice(..i);
- assert!(
- CreateStream::from_bytes(truncated).is_err(),
- "expected error for truncation at byte {i}"
- );
- }
- }
-
- #[test]
- fn from_bytes_should_fail_on_corrupted_name_length() {
- let mut buf = BytesMut::new();
- buf.put_u8(255);
- buf.put_slice(b"short");
- assert!(CreateStream::from_bytes(buf.freeze()).is_err());
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let name = "test".to_string();
- let mut bytes = BytesMut::new();
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(name.len() as u8);
- bytes.put_slice(name.as_bytes());
- let command = CreateStream::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.name, name);
- }
-}
diff --git a/core/common/src/commands/streams/delete_stream.rs b/core/common/src/commands/streams/delete_stream.rs
deleted file mode 100644
index f44110340..000000000
--- a/core/common/src/commands/streams/delete_stream.rs
+++ /dev/null
@@ -1,99 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{Command, DELETE_STREAM_CODE};
-use bytes::Bytes;
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-
-/// `DeleteStream` command is used to delete an existing stream.
-/// It has additional payload:
-/// - `stream_id` - unique stream ID (numeric or name).
-#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
-pub struct DeleteStream {
- /// Unique stream ID (numeric or name).
- #[serde(skip)]
- pub stream_id: Identifier,
-}
-
-impl Command for DeleteStream {
- fn code(&self) -> u32 {
- DELETE_STREAM_CODE
- }
-}
-
-impl Validatable<IggyError> for DeleteStream {
- fn validate(&self) -> Result<(), IggyError> {
- Ok(())
- }
-}
-
-impl BytesSerializable for DeleteStream {
- fn to_bytes(&self) -> Bytes {
- self.stream_id.to_bytes()
- }
-
- fn from_bytes(bytes: Bytes) -> std::result::Result<DeleteStream, IggyError> {
- if bytes.len() < 3 {
- return Err(IggyError::InvalidCommand);
- }
-
- let stream_id = Identifier::from_bytes(bytes)?;
- let command = DeleteStream { stream_id };
- Ok(command)
- }
-}
-
-impl Display for DeleteStream {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}", self.stream_id)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = DeleteStream {
- stream_id: Identifier::numeric(1).unwrap(),
- };
-
- let bytes = command.to_bytes();
- let stream_id = Identifier::from_bytes(bytes.clone()).unwrap();
-
- assert!(!bytes.is_empty());
- assert_eq!(stream_id, command.stream_id);
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let stream_id = Identifier::numeric(1).unwrap();
- let bytes = stream_id.to_bytes();
- let command = DeleteStream::from_bytes(bytes);
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.stream_id, stream_id);
- }
-}
diff --git a/core/common/src/commands/streams/purge_stream.rs b/core/common/src/commands/streams/purge_stream.rs
deleted file mode 100644
index 036930ff8..000000000
--- a/core/common/src/commands/streams/purge_stream.rs
+++ /dev/null
@@ -1,102 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{Command, PURGE_STREAM_CODE};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-
-/// `PurgeStream` command is used to purge stream data (all the messages from its topics).
-/// It has additional payload:
-/// - `stream_id` - unique stream ID (numeric or name).
-#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
-pub struct PurgeStream {
- /// Unique stream ID (numeric or name).
- #[serde(skip)]
- pub stream_id: Identifier,
-}
-
-impl Command for PurgeStream {
- fn code(&self) -> u32 {
- PURGE_STREAM_CODE
- }
-}
-
-impl Validatable<IggyError> for PurgeStream {
- fn validate(&self) -> Result<(), IggyError> {
- Ok(())
- }
-}
-
-impl BytesSerializable for PurgeStream {
- fn to_bytes(&self) -> Bytes {
- let stream_id_bytes = self.stream_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(stream_id_bytes.len());
- bytes.put_slice(&stream_id_bytes);
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<PurgeStream, IggyError> {
- if bytes.len() < 5 {
- return Err(IggyError::InvalidCommand);
- }
-
- let stream_id = Identifier::from_bytes(bytes)?;
- let command = PurgeStream { stream_id };
- Ok(command)
- }
-}
-
-impl Display for PurgeStream {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}", self.stream_id)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = PurgeStream {
- stream_id: Identifier::numeric(1).unwrap(),
- };
-
- let bytes = command.to_bytes();
- let stream_id = Identifier::from_bytes(bytes.clone()).unwrap();
-
- assert!(!bytes.is_empty());
- assert_eq!(stream_id, command.stream_id);
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let stream_id = Identifier::numeric(1).unwrap();
- let bytes = stream_id.to_bytes();
- let command = PurgeStream::from_bytes(bytes);
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.stream_id, stream_id);
- }
-}
diff --git a/core/common/src/commands/streams/update_stream.rs b/core/common/src/commands/streams/update_stream.rs
deleted file mode 100644
index a202105bf..000000000
--- a/core/common/src/commands/streams/update_stream.rs
+++ /dev/null
@@ -1,151 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use super::MAX_NAME_LENGTH;
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Sizeable;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{Command, UPDATE_STREAM_CODE};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-use std::str::from_utf8;
-
-/// `UpdateStream` command is used to update an existing stream.
-/// It has additional payload:
-/// - `stream_id` - unique stream ID (numeric or name).
-/// - `name` - unique stream name (string), max length is 255 characters.
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct UpdateStream {
- /// Unique stream ID (numeric or name).
- #[serde(skip)]
- pub stream_id: Identifier,
- /// Unique stream name (string), max length is 255 characters.
- pub name: String,
-}
-
-impl Command for UpdateStream {
- fn code(&self) -> u32 {
- UPDATE_STREAM_CODE
- }
-}
-
-impl Default for UpdateStream {
- fn default() -> Self {
- UpdateStream {
- stream_id: Identifier::default(),
- name: "stream".to_string(),
- }
- }
-}
-
-impl Validatable<IggyError> for UpdateStream {
- fn validate(&self) -> Result<(), IggyError> {
- if self.name.is_empty() || self.name.len() > MAX_NAME_LENGTH {
- return Err(IggyError::InvalidStreamName);
- }
-
- Ok(())
- }
-}
-
-impl BytesSerializable for UpdateStream {
- fn to_bytes(&self) -> Bytes {
- let stream_id_bytes = self.stream_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(1 + stream_id_bytes.len() + self.name.len());
- bytes.put_slice(&stream_id_bytes);
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(self.name.len() as u8);
- bytes.put_slice(self.name.as_bytes());
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> std::result::Result<UpdateStream, IggyError> {
- if bytes.len() < 5 {
- return Err(IggyError::InvalidCommand);
- }
-
- let mut position = 0;
- let stream_id = Identifier::from_bytes(bytes.clone())?;
- position += stream_id.get_size_bytes().as_bytes_usize();
- let name_length = *bytes.get(position).ok_or(IggyError::InvalidCommand)? as usize;
- let name = from_utf8(
- bytes
- .get(position + 1..position + 1 + name_length)
- .ok_or(IggyError::InvalidCommand)?,
- )
- .map_err(|_| IggyError::InvalidUtf8)?
- .to_string();
-
- let command = UpdateStream { stream_id, name };
- Ok(command)
- }
-}
-
-impl Display for UpdateStream {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}|{}", self.stream_id, self.name)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = UpdateStream {
- stream_id: Identifier::numeric(1).unwrap(),
- name: "test".to_string(),
- };
-
- 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 name_length = bytes[position];
- let name = from_utf8(&bytes[position + 1..position + 1 + name_length as usize])
- .unwrap()
- .to_string();
-
- assert!(!bytes.is_empty());
- assert_eq!(stream_id, command.stream_id);
- assert_eq!(name, command.name);
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let stream_id = Identifier::numeric(1).unwrap();
- let name = "test".to_string();
-
- let stream_id_bytes = stream_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(1 + stream_id_bytes.len() + name.len());
- bytes.put_slice(&stream_id_bytes);
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(name.len() as u8);
- bytes.put_slice(name.as_bytes());
- let command = UpdateStream::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.stream_id, stream_id);
- assert_eq!(command.name, name);
- }
-}
diff --git a/core/common/src/commands/topics/create_topic.rs b/core/common/src/commands/topics/create_topic.rs
deleted file mode 100644
index bd4d87f48..000000000
--- a/core/common/src/commands/topics/create_topic.rs
+++ /dev/null
@@ -1,301 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use super::{MAX_NAME_LENGTH, MAX_PARTITIONS_COUNT};
-use crate::BytesSerializable;
-use crate::CompressionAlgorithm;
-use crate::Identifier;
-use crate::Sizeable;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::utils::expiry::IggyExpiry;
-use crate::utils::topic_size::MaxTopicSize;
-use crate::{CREATE_TOPIC_CODE, Command};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-use std::str::from_utf8;
-
-/// `CreateTopic` command is used to create a new topic in a stream.
-/// It has additional payload:
-/// - `stream_id` - unique stream ID (numeric or name).
-/// - `partitions_count` - number of partitions in the topic, max value is 1000.
-/// - `message_expiry` - message expiry, if `NeverExpire` then messages will never expire.
-/// - `max_topic_size` - maximum size of the topic, if `Unlimited` then topic size is unlimited.
-/// Can't be lower than segment size in the config.
-/// - `replication_factor` - replication factor for the topic.
-/// - `name` - unique topic name, max length is 255 characters.
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct CreateTopic {
- /// Unique stream ID (numeric or name).
- #[serde(skip)]
- pub stream_id: Identifier,
- /// Number of partitions in the topic, max value is 1000.
- pub partitions_count: u32,
- /// Compression algorithm for the topic.
- pub compression_algorithm: CompressionAlgorithm,
- /// Message expiry, if `NeverExpire` then messages will never expire.
- pub message_expiry: IggyExpiry,
- /// Max topic size, if `Unlimited` then topic size is unlimited.
- /// Can't be lower than segment size in the config.
- pub max_topic_size: MaxTopicSize,
- /// Replication factor for the topic.
- pub replication_factor: Option<u8>,
- /// Unique topic name, max length is 255 characters.
- pub name: String,
-}
-
-impl Command for CreateTopic {
- fn code(&self) -> u32 {
- CREATE_TOPIC_CODE
- }
-}
-
-impl Default for CreateTopic {
- fn default() -> Self {
- CreateTopic {
- stream_id: Identifier::default(),
- partitions_count: 1,
- compression_algorithm: CompressionAlgorithm::None,
- message_expiry: IggyExpiry::NeverExpire,
- max_topic_size: MaxTopicSize::ServerDefault,
- replication_factor: None,
- name: "topic".to_string(),
- }
- }
-}
-
-impl Validatable<IggyError> for CreateTopic {
- fn validate(&self) -> Result<(), IggyError> {
- if self.name.is_empty() || self.name.len() > MAX_NAME_LENGTH {
- return Err(IggyError::InvalidTopicName);
- }
-
- if !(0..=MAX_PARTITIONS_COUNT).contains(&self.partitions_count) {
- return Err(IggyError::TooManyPartitions);
- }
-
- if let Some(replication_factor) = self.replication_factor
- && replication_factor == 0
- {
- return Err(IggyError::InvalidReplicationFactor);
- }
-
- Ok(())
- }
-}
-
-impl BytesSerializable for CreateTopic {
- fn to_bytes(&self) -> Bytes {
- let stream_id_bytes = self.stream_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(19 + stream_id_bytes.len() + self.name.len());
- bytes.put_slice(&stream_id_bytes);
- bytes.put_u32_le(self.partitions_count);
- bytes.put_u8(self.compression_algorithm.as_code());
- bytes.put_u64_le(self.message_expiry.into());
- bytes.put_u64_le(self.max_topic_size.into());
- match self.replication_factor {
- Some(replication_factor) => bytes.put_u8(replication_factor),
- None => bytes.put_u8(0),
- }
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(self.name.len() as u8);
- bytes.put_slice(self.name.as_bytes());
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> std::result::Result<CreateTopic, IggyError> {
- if bytes.len() < 14 {
- return Err(IggyError::InvalidCommand);
- }
- let mut position = 0;
- let stream_id = Identifier::from_bytes(bytes.clone())?;
- position += stream_id.get_size_bytes().as_bytes_usize();
- let partitions_count = u32::from_le_bytes(
- bytes
- .get(position..position + 4)
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let compression_algorithm = CompressionAlgorithm::from_code(
- *bytes.get(position + 4).ok_or(IggyError::InvalidCommand)?,
- )?;
- let message_expiry = u64::from_le_bytes(
- bytes
- .get(position + 5..position + 13)
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let message_expiry: IggyExpiry = message_expiry.into();
- let max_topic_size = u64::from_le_bytes(
- bytes
- .get(position + 13..position + 21)
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let max_topic_size: MaxTopicSize = max_topic_size.into();
- let replication_factor = match *bytes.get(position + 21).ok_or(IggyError::InvalidCommand)? {
- 0 => None,
- factor => Some(factor),
- };
- let name_length = *bytes.get(position + 22).ok_or(IggyError::InvalidCommand)? as usize;
- let name = from_utf8(
- bytes
- .get(position + 23..position + 23 + name_length)
- .ok_or(IggyError::InvalidCommand)?,
- )
- .map_err(|_| IggyError::InvalidUtf8)?
- .to_string();
- let command = CreateTopic {
- stream_id,
- partitions_count,
- compression_algorithm,
- message_expiry,
- max_topic_size,
- replication_factor,
- name,
- };
- Ok(command)
- }
-}
-
-impl Display for CreateTopic {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "{}|{}|{}|{}|{}|{}",
- self.stream_id,
- self.partitions_count,
- self.message_expiry,
- self.max_topic_size,
- self.replication_factor.unwrap_or(0),
- self.name
- )
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use bytes::BufMut;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = CreateTopic {
- stream_id: Identifier::numeric(1).unwrap(),
- partitions_count: 3,
- message_expiry: IggyExpiry::NeverExpire,
- compression_algorithm: CompressionAlgorithm::None,
- max_topic_size: MaxTopicSize::ServerDefault,
- replication_factor: Some(1),
- name: "test".to_string(),
- };
- 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 partitions_count =
- u32::from_le_bytes(bytes[position..position + 4].try_into().unwrap());
- let compression_algorithm = CompressionAlgorithm::from_code(bytes[position + 4]).unwrap();
- let message_expiry =
- u64::from_le_bytes(bytes[position + 5..position + 13].try_into().unwrap());
- let message_expiry: IggyExpiry = message_expiry.into();
- let max_topic_size =
- u64::from_le_bytes(bytes[position + 13..position + 21].try_into().unwrap());
- let max_topic_size: MaxTopicSize = max_topic_size.into();
- let replication_factor = bytes[position + 21];
- let name_length = bytes[position + 22];
- let name = from_utf8(&bytes[position + 23..(position + 23 + name_length as usize)])
- .unwrap()
- .to_string();
-
- assert!(!bytes.is_empty());
- assert_eq!(stream_id, command.stream_id);
- assert_eq!(partitions_count, command.partitions_count);
- assert_eq!(compression_algorithm, command.compression_algorithm);
- assert_eq!(message_expiry, command.message_expiry);
- assert_eq!(max_topic_size, command.max_topic_size);
- assert_eq!(replication_factor, command.replication_factor.unwrap());
- assert_eq!(name.len() as u8, command.name.len() as u8);
- assert_eq!(name, command.name);
- }
-
- #[test]
- fn from_bytes_should_fail_on_empty_input() {
- assert!(CreateTopic::from_bytes(Bytes::new()).is_err());
- }
-
- #[test]
- fn from_bytes_should_fail_on_truncated_input() {
- let command = CreateTopic {
- stream_id: Identifier::numeric(1).unwrap(),
- partitions_count: 3,
- compression_algorithm: CompressionAlgorithm::None,
- message_expiry: IggyExpiry::NeverExpire,
- max_topic_size: MaxTopicSize::ServerDefault,
- replication_factor: Some(1),
- name: "test".to_string(),
- };
- let bytes = command.to_bytes();
- for i in 0..bytes.len() - 1 {
- let truncated = bytes.slice(..i);
- assert!(
- CreateTopic::from_bytes(truncated).is_err(),
- "expected error for truncation at byte {i}"
- );
- }
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let stream_id = Identifier::numeric(1).unwrap();
- let partitions_count = 3u32;
- let compression_algorithm = CompressionAlgorithm::None;
- let name = "test".to_string();
- let message_expiry = IggyExpiry::NeverExpire;
- let max_topic_size = MaxTopicSize::ServerDefault;
- let replication_factor = 1;
- let stream_id_bytes = stream_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(10 + stream_id_bytes.len() + name.len());
- bytes.put_slice(&stream_id_bytes);
- bytes.put_u32_le(partitions_count);
- bytes.put_u8(compression_algorithm.as_code());
- bytes.put_u64_le(message_expiry.into());
- bytes.put_u64_le(max_topic_size.as_bytes_u64());
- bytes.put_u8(replication_factor);
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(name.len() as u8);
- bytes.put_slice(name.as_bytes());
-
- let command = CreateTopic::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.stream_id, stream_id);
- assert_eq!(command.name, name);
- assert_eq!(command.partitions_count, partitions_count);
- assert_eq!(command.compression_algorithm, compression_algorithm);
- assert_eq!(command.message_expiry, message_expiry);
- assert_eq!(command.max_topic_size, max_topic_size);
- assert_eq!(command.replication_factor.unwrap(), replication_factor);
- assert_eq!(command.partitions_count, partitions_count);
- }
-}
diff --git a/core/common/src/commands/topics/delete_topic.rs b/core/common/src/commands/topics/delete_topic.rs
deleted file mode 100644
index 45680311d..000000000
--- a/core/common/src/commands/topics/delete_topic.rs
+++ /dev/null
@@ -1,126 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Sizeable;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{Command, DELETE_TOPIC_CODE};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-
-/// `DeleteTopic` command is used to delete a topic from a stream.
-/// It has additional payload:
-/// - `stream_id` - unique stream ID (numeric or name).
-/// - `topic_id` - unique topic ID (numeric or name).
-#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
-pub struct DeleteTopic {
- /// Unique stream ID (numeric or name).
- #[serde(skip)]
- pub stream_id: Identifier,
- /// Unique topic ID (numeric or name).
- #[serde(skip)]
- pub topic_id: Identifier,
-}
-
-impl Command for DeleteTopic {
- fn code(&self) -> u32 {
- DELETE_TOPIC_CODE
- }
-}
-
-impl Validatable<IggyError> for DeleteTopic {
- fn validate(&self) -> Result<(), IggyError> {
- Ok(())
- }
-}
-
-impl BytesSerializable for DeleteTopic {
- fn to_bytes(&self) -> Bytes {
- let stream_id_bytes = self.stream_id.to_bytes();
- let topic_id_bytes = self.topic_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(stream_id_bytes.len() + topic_id_bytes.len());
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> std::result::Result<DeleteTopic, IggyError> {
- if bytes.len() < 10 {
- return Err(IggyError::InvalidCommand);
- }
-
- 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..))?;
- let command = DeleteTopic {
- stream_id,
- topic_id,
- };
- Ok(command)
- }
-}
-
-impl Display for DeleteTopic {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}|{}", self.stream_id, self.topic_id)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use bytes::BufMut;
-
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = DeleteTopic {
- stream_id: Identifier::numeric(1).unwrap(),
- topic_id: Identifier::numeric(2).unwrap(),
- };
-
- 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();
-
- assert!(!bytes.is_empty());
- assert_eq!(stream_id, command.stream_id);
- assert_eq!(topic_id, command.topic_id);
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let stream_id = Identifier::numeric(1).unwrap();
- let topic_id = Identifier::numeric(2).unwrap();
- let mut bytes = BytesMut::new();
- bytes.put(stream_id.to_bytes());
- bytes.put(topic_id.to_bytes());
- let command = DeleteTopic::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.stream_id, stream_id);
- assert_eq!(command.topic_id, topic_id);
- }
-}
diff --git a/core/common/src/commands/topics/purge_topic.rs b/core/common/src/commands/topics/purge_topic.rs
deleted file mode 100644
index 9473b38c7..000000000
--- a/core/common/src/commands/topics/purge_topic.rs
+++ /dev/null
@@ -1,124 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Sizeable;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{Command, PURGE_TOPIC_CODE};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-
-/// `PurgeTopic` command is used to purge topic data (its messages in all the partitions) from a stream.
-/// It has additional payload:
-/// - `stream_id` - unique stream ID (numeric or name).
-/// - `topic_id` - unique topic ID (numeric or name).
-#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
-pub struct PurgeTopic {
- /// Unique stream ID (numeric or name).
- #[serde(skip)]
- pub stream_id: Identifier,
- /// Unique topic ID (numeric or name).
- #[serde(skip)]
- pub topic_id: Identifier,
-}
-
-impl Command for PurgeTopic {
- fn code(&self) -> u32 {
- PURGE_TOPIC_CODE
- }
-}
-
-impl Validatable<IggyError> for PurgeTopic {
- fn validate(&self) -> Result<(), IggyError> {
- Ok(())
- }
-}
-
-impl BytesSerializable for PurgeTopic {
- fn to_bytes(&self) -> Bytes {
- let stream_id_bytes = self.stream_id.to_bytes();
- let topic_id_bytes = self.topic_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(stream_id_bytes.len() + topic_id_bytes.len());
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<PurgeTopic, IggyError> {
- if bytes.len() < 10 {
- return Err(IggyError::InvalidCommand);
- }
-
- 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..))?;
- let command = PurgeTopic {
- stream_id,
- topic_id,
- };
- Ok(command)
- }
-}
-
-impl Display for PurgeTopic {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}|{}", self.stream_id, self.topic_id)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = PurgeTopic {
- stream_id: Identifier::numeric(1).unwrap(),
- topic_id: Identifier::numeric(2).unwrap(),
- };
-
- 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();
-
- assert!(!bytes.is_empty());
- assert_eq!(stream_id, command.stream_id);
- assert_eq!(topic_id, command.topic_id);
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let stream_id = Identifier::numeric(1).unwrap();
- let topic_id = Identifier::numeric(2).unwrap();
- let mut bytes = BytesMut::new();
- bytes.put_slice(&stream_id.to_bytes());
- bytes.put_slice(&topic_id.to_bytes());
- let command = PurgeTopic::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.stream_id, stream_id);
- assert_eq!(command.topic_id, topic_id);
- }
-}
diff --git a/core/common/src/commands/topics/update_topic.rs b/core/common/src/commands/topics/update_topic.rs
deleted file mode 100644
index 6f7bf5a02..000000000
--- a/core/common/src/commands/topics/update_topic.rs
+++ /dev/null
@@ -1,302 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use super::MAX_NAME_LENGTH;
-use crate::BytesSerializable;
-use crate::CompressionAlgorithm;
-use crate::Identifier;
-use crate::Sizeable;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::utils::expiry::IggyExpiry;
-use crate::utils::topic_size::MaxTopicSize;
-use crate::{Command, UPDATE_TOPIC_CODE};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-use std::str::from_utf8;
-
-/// `UpdateTopic` command is used to update a topic in a stream.
-/// It has additional payload:
-/// - `stream_id` - unique stream ID (numeric or name).
-/// - `topic_id` - unique topic ID (numeric or name).
-/// - `message_expiry` - message expiry, if `NeverExpire` then messages will never expire.
-/// - `max_topic_size` - maximum size of the topic in bytes, if `Unlimited` then topic size is unlimited.
-/// Can't be lower than segment size in the config.
-/// - `replication_factor` - replication factor for the topic.
-/// - `name` - unique topic name, max length is 255 characters.
-#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
-pub struct UpdateTopic {
- /// Unique stream ID (numeric or name).
- #[serde(skip)]
- pub stream_id: Identifier,
- /// Unique topic ID (numeric or name).
- #[serde(skip)]
- pub topic_id: Identifier,
- /// Compression algorithm for the topic.
- pub compression_algorithm: CompressionAlgorithm,
- /// Message expiry, if `NeverExpire` then messages will never expire.
- pub message_expiry: IggyExpiry,
- /// Max topic size, if `Unlimited` then topic size is unlimited.
- /// Can't be lower than segment size in the config.
- pub max_topic_size: MaxTopicSize,
- /// Replication factor for the topic.
- pub replication_factor: Option<u8>,
- /// Unique topic name, max length is 255 characters.
- pub name: String,
-}
-
-impl Command for UpdateTopic {
- fn code(&self) -> u32 {
- UPDATE_TOPIC_CODE
- }
-}
-
-impl Default for UpdateTopic {
- fn default() -> Self {
- UpdateTopic {
- stream_id: Identifier::default(),
- topic_id: Identifier::default(),
- compression_algorithm: Default::default(),
- message_expiry: IggyExpiry::NeverExpire,
- max_topic_size: MaxTopicSize::ServerDefault,
- replication_factor: None,
- name: "topic".to_string(),
- }
- }
-}
-
-impl Validatable<IggyError> for UpdateTopic {
- fn validate(&self) -> Result<(), IggyError> {
- if self.name.is_empty() || self.name.len() > MAX_NAME_LENGTH {
- return Err(IggyError::InvalidTopicName);
- }
-
- if let Some(replication_factor) = self.replication_factor
- && replication_factor == 0
- {
- return Err(IggyError::InvalidReplicationFactor);
- }
-
- Ok(())
- }
-}
-
-impl BytesSerializable for UpdateTopic {
- fn to_bytes(&self) -> Bytes {
- let stream_id_bytes = self.stream_id.to_bytes();
- let topic_id_bytes = self.topic_id.to_bytes();
- let mut bytes = BytesMut::with_capacity(
- 19 + stream_id_bytes.len() + topic_id_bytes.len() + self.name.len(),
- );
- bytes.put_slice(&stream_id_bytes.clone());
- bytes.put_slice(&topic_id_bytes.clone());
- bytes.put_u8(self.compression_algorithm.as_code());
- bytes.put_u64_le(self.message_expiry.into());
- bytes.put_u64_le(self.max_topic_size.into());
- match self.replication_factor {
- Some(replication_factor) => bytes.put_u8(replication_factor),
- None => bytes.put_u8(0),
- }
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(self.name.len() as u8);
- bytes.put_slice(self.name.as_bytes());
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<UpdateTopic, IggyError> {
- if bytes.len() < 21 {
- return Err(IggyError::InvalidCommand);
- }
- 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 compression_algorithm = CompressionAlgorithm::from_code(
- *bytes.get(position).ok_or(IggyError::InvalidCommand)?,
- )?;
- position += 1;
- let message_expiry = u64::from_le_bytes(
- bytes
- .get(position..position + 8)
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let message_expiry: IggyExpiry = message_expiry.into();
- let max_topic_size = u64::from_le_bytes(
- bytes
- .get(position + 8..position + 16)
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- let max_topic_size: MaxTopicSize = max_topic_size.into();
- let replication_factor = match *bytes.get(position + 16).ok_or(IggyError::InvalidCommand)? {
- 0 => None,
- factor => Some(factor),
- };
- let name_length = *bytes.get(position + 17).ok_or(IggyError::InvalidCommand)? as usize;
- let name = from_utf8(
- bytes
- .get(position + 18..position + 18 + name_length)
- .ok_or(IggyError::InvalidCommand)?,
- )
- .map_err(|_| IggyError::InvalidUtf8)?
- .to_string();
- let command = UpdateTopic {
- stream_id,
- topic_id,
- compression_algorithm,
- message_expiry,
- max_topic_size,
- replication_factor,
- name,
- };
- Ok(command)
- }
-}
-
-impl Display for UpdateTopic {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(
- f,
- "{}|{}|{}|{}|{}|{}",
- self.stream_id,
- self.topic_id,
- self.message_expiry,
- self.max_topic_size,
- self.replication_factor.unwrap_or(0),
- self.name,
- )
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::utils::byte_size::IggyByteSize;
- use bytes::BufMut;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = UpdateTopic {
- stream_id: Identifier::numeric(1).unwrap(),
- topic_id: Identifier::numeric(2).unwrap(),
- compression_algorithm: CompressionAlgorithm::None,
- message_expiry: IggyExpiry::NeverExpire,
- max_topic_size: MaxTopicSize::ServerDefault,
- replication_factor: Some(1),
- name: "test".to_string(),
- };
-
- 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 compression_algorithm = CompressionAlgorithm::from_code(bytes[position]).unwrap();
- position += 1;
- let message_expiry = u64::from_le_bytes(bytes[position..position + 8].try_into().unwrap());
- let message_expiry: IggyExpiry = message_expiry.into();
- let max_topic_size =
- u64::from_le_bytes(bytes[position + 8..position + 16].try_into().unwrap());
- let max_topic_size: MaxTopicSize = max_topic_size.into();
- let replication_factor = bytes[position + 16];
- let name_length = bytes[position + 17];
- let name = from_utf8(&bytes[position + 18..position + 18 + name_length as usize])
- .unwrap()
- .to_string();
-
- assert!(!bytes.is_empty());
- assert_eq!(stream_id, command.stream_id);
- assert_eq!(topic_id, command.topic_id);
- assert_eq!(compression_algorithm, command.compression_algorithm);
- assert_eq!(message_expiry, command.message_expiry);
- assert_eq!(max_topic_size, command.max_topic_size);
- assert_eq!(replication_factor, command.replication_factor.unwrap());
- assert_eq!(name.len() as u8, command.name.len() as u8);
- assert_eq!(name, command.name);
- }
-
- #[test]
- fn from_bytes_should_fail_on_empty_input() {
- assert!(UpdateTopic::from_bytes(Bytes::new()).is_err());
- }
-
- #[test]
- fn from_bytes_should_fail_on_truncated_input() {
- let command = UpdateTopic {
- stream_id: Identifier::numeric(1).unwrap(),
- topic_id: Identifier::numeric(2).unwrap(),
- compression_algorithm: CompressionAlgorithm::None,
- message_expiry: IggyExpiry::NeverExpire,
- max_topic_size: MaxTopicSize::ServerDefault,
- replication_factor: Some(1),
- name: "test".to_string(),
- };
- let bytes = command.to_bytes();
- for i in 0..bytes.len() - 1 {
- let truncated = bytes.slice(..i);
- assert!(
- UpdateTopic::from_bytes(truncated).is_err(),
- "expected error for truncation at byte {i}"
- );
- }
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let stream_id = Identifier::numeric(1).unwrap();
- let topic_id = Identifier::numeric(2).unwrap();
- let compression_algorithm = CompressionAlgorithm::None;
- let name = "test".to_string();
- let message_expiry = IggyExpiry::NeverExpire;
- let max_topic_size = MaxTopicSize::Custom(IggyByteSize::from(100));
- let replication_factor = 1;
-
- let stream_id_bytes = stream_id.to_bytes();
- let topic_id_bytes = topic_id.to_bytes();
- let mut bytes =
- BytesMut::with_capacity(19 + stream_id_bytes.len() + topic_id_bytes.len() + name.len());
- bytes.put_slice(&stream_id_bytes);
- bytes.put_slice(&topic_id_bytes);
- bytes.put_u8(compression_algorithm.as_code());
- bytes.put_u64_le(message_expiry.into());
- bytes.put_u64_le(max_topic_size.as_bytes_u64());
- bytes.put_u8(replication_factor);
-
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(name.len() as u8);
- bytes.put_slice(name.as_bytes());
-
- let command = UpdateTopic::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.stream_id, stream_id);
- assert_eq!(command.topic_id, topic_id);
- assert_eq!(command.compression_algorithm, compression_algorithm);
- assert_eq!(command.message_expiry, message_expiry);
- assert_eq!(command.max_topic_size, max_topic_size);
- assert_eq!(command.replication_factor, Some(replication_factor));
- assert_eq!(command.name, name);
- }
-}
diff --git a/core/common/src/commands/users/change_password.rs b/core/common/src/commands/users/change_password.rs
deleted file mode 100644
index 9d5272433..000000000
--- a/core/common/src/commands/users/change_password.rs
+++ /dev/null
@@ -1,246 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use super::defaults::*;
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Sizeable;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{CHANGE_PASSWORD_CODE, Command};
-use bytes::{BufMut, Bytes, BytesMut};
-use secrecy::{ExposeSecret, SecretString};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-use std::str::from_utf8;
-
-/// `ChangePassword` command is used to change a user's password.
-/// It has additional payload:
-/// - `user_id` - unique user ID (numeric or name).
-/// - `current_password` - current password, must be between 3 and 100 characters long.
-/// - `new_password` - new password, must be between 3 and 100 characters long.
-#[derive(Debug, Serialize, Deserialize, Clone)]
-pub struct ChangePassword {
- /// Unique user ID (numeric or name).
- #[serde(skip)]
- pub user_id: Identifier,
- /// Current password, must be between 3 and 100 characters long.
- #[serde(serialize_with = "crate::utils::serde_secret::serialize_secret")]
- pub current_password: SecretString,
- /// New password, must be between 3 and 100 characters long.
- #[serde(serialize_with = "crate::utils::serde_secret::serialize_secret")]
- pub new_password: SecretString,
-}
-
-impl Command for ChangePassword {
- fn code(&self) -> u32 {
- CHANGE_PASSWORD_CODE
- }
-}
-
-impl Default for ChangePassword {
- fn default() -> Self {
- ChangePassword {
- user_id: Identifier::default(),
- current_password: SecretString::from("secret"),
- new_password: SecretString::from("topsecret"),
- }
- }
-}
-
-impl Validatable<IggyError> for ChangePassword {
- fn validate(&self) -> Result<(), IggyError> {
- let current_password = self.current_password.expose_secret();
- if current_password.is_empty()
- || current_password.len() > MAX_PASSWORD_LENGTH
- || current_password.len() < MIN_PASSWORD_LENGTH
- {
- return Err(IggyError::InvalidPassword);
- }
-
- let new_password = self.new_password.expose_secret();
- if new_password.is_empty()
- || new_password.len() > MAX_PASSWORD_LENGTH
- || new_password.len() < MIN_PASSWORD_LENGTH
- {
- return Err(IggyError::InvalidPassword);
- }
-
- Ok(())
- }
-}
-
-impl BytesSerializable for ChangePassword {
- fn to_bytes(&self) -> Bytes {
- let user_id_bytes = self.user_id.to_bytes();
- let current_password = self.current_password.expose_secret();
- let new_password = self.new_password.expose_secret();
- let mut bytes = BytesMut::new();
- bytes.put_slice(&user_id_bytes);
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(current_password.len() as u8);
- bytes.put_slice(current_password.as_bytes());
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(new_password.len() as u8);
- bytes.put_slice(new_password.as_bytes());
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<ChangePassword, IggyError> {
- if bytes.len() < 9 {
- return Err(IggyError::InvalidCommand);
- }
-
- let user_id = Identifier::from_bytes(bytes.clone())?;
- let mut position = user_id.get_size_bytes().as_bytes_usize();
- let current_password_length = *bytes.get(position).ok_or(IggyError::InvalidCommand)?;
- position += 1;
- let current_password = from_utf8(
- bytes
- .get(position..position + current_password_length as usize)
- .ok_or(IggyError::InvalidCommand)?,
- )
- .map_err(|_| IggyError::InvalidUtf8)?
- .to_string();
- position += current_password_length as usize;
- let new_password_length = *bytes.get(position).ok_or(IggyError::InvalidCommand)?;
- position += 1;
- let new_password = from_utf8(
- bytes
- .get(position..position + new_password_length as usize)
- .ok_or(IggyError::InvalidCommand)?,
- )
- .map_err(|_| IggyError::InvalidUtf8)?
- .to_string();
-
- let command = ChangePassword {
- user_id,
- current_password: SecretString::from(current_password),
- new_password: SecretString::from(new_password),
- };
- Ok(command)
- }
-}
-
-impl Display for ChangePassword {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}|******|******", self.user_id)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = ChangePassword {
- user_id: Identifier::numeric(1).unwrap(),
- current_password: SecretString::from("user"),
- new_password: SecretString::from("secret"),
- };
-
- let bytes = command.to_bytes();
- let user_id = Identifier::from_bytes(bytes.clone()).unwrap();
- let mut position = user_id.get_size_bytes().as_bytes_usize();
- let current_password_length = bytes[position];
- position += 1;
- let current_password =
- from_utf8(&bytes[position..position + current_password_length as usize]).unwrap();
- position += current_password_length as usize;
- let new_password_length = bytes[position];
- position += 1;
- let new_password =
- from_utf8(&bytes[position..position + new_password_length as usize]).unwrap();
-
- assert!(!bytes.is_empty());
- assert_eq!(user_id, command.user_id);
- assert_eq!(current_password, command.current_password.expose_secret());
- assert_eq!(new_password, command.new_password.expose_secret());
- }
-
- #[test]
- fn from_bytes_should_fail_on_empty_input() {
- assert!(ChangePassword::from_bytes(Bytes::new()).is_err());
- }
-
- #[test]
- fn from_bytes_should_fail_on_truncated_input() {
- let command = ChangePassword::default();
- let bytes = command.to_bytes();
- for i in 0..bytes.len() - 1 {
- let truncated = bytes.slice(..i);
- assert!(
- ChangePassword::from_bytes(truncated).is_err(),
- "expected error for truncation at byte {i}"
- );
- }
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let user_id = Identifier::numeric(1).unwrap();
- let current_password = "secret";
- let new_password = "topsecret";
- let mut bytes = BytesMut::new();
- bytes.put_slice(&user_id.to_bytes());
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(current_password.len() as u8);
- bytes.put_slice(current_password.as_bytes());
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(new_password.len() as u8);
- bytes.put_slice(new_password.as_bytes());
-
- let command = ChangePassword::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.user_id, user_id);
- assert_eq!(command.current_password.expose_secret(), current_password);
- assert_eq!(command.new_password.expose_secret(), new_password);
- }
-
- #[test]
- fn should_fail_validation_for_invalid_current_password() {
- for password in ["", "ab"] {
- let command = ChangePassword {
- current_password: SecretString::from(password),
- ..ChangePassword::default()
- };
- assert!(
- command.validate().is_err(),
- "expected validation error for current_password: {password:?}"
- );
- }
- }
-
- #[test]
- fn should_fail_validation_for_empty_new_password() {
- let command = ChangePassword {
- new_password: SecretString::from(""),
- ..ChangePassword::default()
- };
- assert!(command.validate().is_err());
- }
-
- #[test]
- fn should_pass_validation_for_valid_command() {
- let command = ChangePassword::default();
- assert!(command.validate().is_ok());
- }
-}
diff --git a/core/common/src/commands/users/create_user.rs b/core/common/src/commands/users/create_user.rs
deleted file mode 100644
index 3405bd486..000000000
--- a/core/common/src/commands/users/create_user.rs
+++ /dev/null
@@ -1,347 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use super::defaults::*;
-use crate::BytesSerializable;
-use crate::Permissions;
-use crate::UserStatus;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{CREATE_USER_CODE, Command};
-use bytes::{BufMut, Bytes, BytesMut};
-use secrecy::{ExposeSecret, SecretString};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-use std::str::from_utf8;
-
-/// `CreateUser` command is used to create a new user.
-/// It has additional payload:
-/// - `username` - unique name of the user, must be between 3 and 50 characters long.
-/// - `password` - password of the user, must be between 3 and 100 characters long.
-/// - `status` - status of the user, can be either `active` or `inactive`.
-/// - `permissions` - optional permissions of the user. If not provided, user will have no permissions.
-#[derive(Debug, Serialize, Deserialize, Clone)]
-pub struct CreateUser {
- /// Unique name of the user, must be between 3 and 50 characters long.
- pub username: String,
- /// Password of the user, must be between 3 and 100 characters long.
- #[serde(serialize_with = "crate::utils::serde_secret::serialize_secret")]
- pub password: SecretString,
- /// Status of the user, can be either `active` or `inactive`.
- pub status: UserStatus,
- /// Optional permissions of the user. If not provided, user will have no permissions.
- pub permissions: Option<Permissions>,
-}
-
-impl Command for CreateUser {
- fn code(&self) -> u32 {
- CREATE_USER_CODE
- }
-}
-
-impl Default for CreateUser {
- fn default() -> Self {
- CreateUser {
- username: "user".to_string(),
- password: SecretString::from("secret"),
- status: UserStatus::Active,
- permissions: None,
- }
- }
-}
-
-impl Validatable<IggyError> for CreateUser {
- fn validate(&self) -> Result<(), IggyError> {
- if self.username.is_empty()
- || self.username.len() > MAX_USERNAME_LENGTH
- || self.username.len() < MIN_USERNAME_LENGTH
- {
- return Err(IggyError::InvalidUsername);
- }
-
- let password = self.password.expose_secret();
- if password.is_empty()
- || password.len() > MAX_PASSWORD_LENGTH
- || password.len() < MIN_PASSWORD_LENGTH
- {
- return Err(IggyError::InvalidPassword);
- }
-
- Ok(())
- }
-}
-
-impl BytesSerializable for CreateUser {
- fn to_bytes(&self) -> Bytes {
- let password = self.password.expose_secret();
- let mut bytes = BytesMut::with_capacity(2 + self.username.len() + password.len());
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(self.username.len() as u8);
- bytes.put_slice(self.username.as_bytes());
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(password.len() as u8);
- bytes.put_slice(password.as_bytes());
- bytes.put_u8(self.status.as_code());
- if let Some(permissions) = &self.permissions {
- bytes.put_u8(1);
- let permissions = permissions.to_bytes();
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u32_le(permissions.len() as u32);
- bytes.put_slice(&permissions);
- } else {
- bytes.put_u8(0);
- }
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<CreateUser, IggyError> {
- if bytes.len() < 10 {
- return Err(IggyError::InvalidCommand);
- }
-
- let username_length = *bytes.first().ok_or(IggyError::InvalidCommand)? as usize;
- let username = from_utf8(
- bytes
- .get(1..1 + username_length)
- .ok_or(IggyError::InvalidCommand)?,
- )
- .map_err(|_| IggyError::InvalidUtf8)?
- .to_string();
-
- let mut position = 1 + username_length;
- let password_length = *bytes.get(position).ok_or(IggyError::InvalidCommand)? as usize;
- position += 1;
- let password = from_utf8(
- bytes
- .get(position..position + password_length)
- .ok_or(IggyError::InvalidCommand)?,
- )
- .map_err(|_| IggyError::InvalidUtf8)?
- .to_string();
-
- position += password_length;
- let status = UserStatus::from_code(*bytes.get(position).ok_or(IggyError::InvalidCommand)?)?;
- position += 1;
- let has_permissions = *bytes.get(position).ok_or(IggyError::InvalidCommand)?;
- if has_permissions > 1 {
- return Err(IggyError::InvalidCommand);
- }
-
- position += 1;
- let permissions = if has_permissions == 1 {
- let permissions_length = u32::from_le_bytes(
- bytes
- .get(position..position + 4)
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- position += 4;
- let end = position
- .checked_add(permissions_length as usize)
- .ok_or(IggyError::InvalidCommand)?;
- if end > bytes.len() {
- return Err(IggyError::InvalidCommand);
- }
- Some(Permissions::from_bytes(bytes.slice(position..end))?)
- } else {
- None
- };
-
- let command = CreateUser {
- username,
- password: SecretString::from(password),
- status,
- permissions,
- };
- Ok(command)
- }
-}
-
-impl Display for CreateUser {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let permissions = if let Some(permissions) = &self.permissions {
- permissions.to_string()
- } else {
- "no_permissions".to_string()
- };
- write!(
- f,
- "{}|******|{}|{}",
- self.username, self.status, permissions
- )
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::GlobalPermissions;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = CreateUser {
- username: "user".to_string(),
- password: SecretString::from("secret"),
- status: UserStatus::Active,
- permissions: Some(Permissions {
- global: GlobalPermissions {
- manage_servers: false,
- read_servers: true,
- manage_users: false,
- read_users: true,
- manage_streams: false,
- read_streams: true,
- manage_topics: false,
- read_topics: true,
- poll_messages: true,
- send_messages: true,
- },
- streams: None,
- }),
- };
-
- let bytes = command.to_bytes();
- let username_length = bytes[0];
- let username = from_utf8(&bytes[1..1 + username_length as usize]).unwrap();
- let mut position = 1 + username_length as usize;
- let password_length = bytes[position];
- position += 1;
- let password = from_utf8(&bytes[position..position + password_length as usize]).unwrap();
- position += password_length as usize;
- let status = UserStatus::from_code(bytes[position]).unwrap();
- position += 1;
- let has_permissions = bytes[3 + username_length as usize + password_length as usize];
- position += 1;
-
- let permissions_length =
- u32::from_le_bytes(bytes[position..position + 4].try_into().unwrap());
- position += 4;
- let permissions =
- Permissions::from_bytes(bytes.slice(position..position + permissions_length as usize))
- .unwrap();
-
- assert!(!bytes.is_empty());
- assert_eq!(username, command.username);
- assert_eq!(password, command.password.expose_secret());
- assert_eq!(status, command.status);
- assert_eq!(has_permissions, 1);
- assert_eq!(permissions, command.permissions.unwrap());
- }
-
- #[test]
- fn from_bytes_should_fail_on_empty_input() {
- assert!(CreateUser::from_bytes(Bytes::new()).is_err());
- }
-
- #[test]
- fn from_bytes_should_fail_on_truncated_input() {
- let command = CreateUser::default();
- let bytes = command.to_bytes();
- for i in 0..bytes.len() - 1 {
- let truncated = bytes.slice(..i);
- assert!(
- CreateUser::from_bytes(truncated).is_err(),
- "expected error for truncation at byte {i}"
- );
- }
- }
-
- #[test]
- fn from_bytes_should_fail_on_corrupted_username_length() {
- let mut buf = BytesMut::new();
- buf.put_u8(255);
- buf.put_slice(b"short");
- assert!(CreateUser::from_bytes(buf.freeze()).is_err());
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let username = "user";
- let password = "secret";
- let status = UserStatus::Active;
- let has_permissions = 1u8;
- let permissions = Permissions {
- global: GlobalPermissions {
- manage_servers: false,
- read_servers: true,
- manage_users: false,
- read_users: true,
- manage_streams: false,
- read_streams: true,
- manage_topics: false,
- read_topics: true,
- poll_messages: true,
- send_messages: true,
- },
- streams: None,
- };
- let mut bytes = BytesMut::new();
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(username.len() as u8);
- bytes.put_slice(username.as_bytes());
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(password.len() as u8);
- bytes.put_slice(password.as_bytes());
- bytes.put_u8(status.as_code());
- bytes.put_u8(has_permissions);
- let permissions_bytes = permissions.to_bytes();
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u32_le(permissions_bytes.len() as u32);
- bytes.put_slice(&permissions_bytes);
-
- let command = CreateUser::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.username, username);
- assert_eq!(command.password.expose_secret(), password);
- assert_eq!(command.status, status);
- assert!(command.permissions.is_some());
- assert_eq!(command.permissions.unwrap(), permissions);
- }
-
- #[test]
- fn should_fail_validation_for_empty_username() {
- let command = CreateUser {
- username: "".to_string(),
- ..CreateUser::default()
- };
- assert!(command.validate().is_err());
- }
-
- #[test]
- fn should_fail_validation_for_invalid_password() {
- for password in ["", "ab"] {
- let command = CreateUser {
- password: SecretString::from(password),
- ..CreateUser::default()
- };
- assert!(
- command.validate().is_err(),
- "expected validation error for password: {password:?}"
- );
- }
- }
-
- #[test]
- fn should_pass_validation_for_valid_command() {
- let command = CreateUser::default();
- assert!(command.validate().is_ok());
- }
-}
diff --git a/core/common/src/commands/users/delete_user.rs b/core/common/src/commands/users/delete_user.rs
deleted file mode 100644
index 3cc5682a6..000000000
--- a/core/common/src/commands/users/delete_user.rs
+++ /dev/null
@@ -1,99 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{Command, DELETE_USER_CODE};
-use bytes::Bytes;
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-
-/// `DeleteUser` command is used to delete a user by unique ID.
-/// It has additional payload:
-/// - `user_id` - unique user ID (numeric or name).
-#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
-pub struct DeleteUser {
- /// Unique user ID (numeric or name).
- #[serde(skip)]
- pub user_id: Identifier,
-}
-
-impl Command for DeleteUser {
- fn code(&self) -> u32 {
- DELETE_USER_CODE
- }
-}
-
-impl Validatable<IggyError> for DeleteUser {
- fn validate(&self) -> Result<(), IggyError> {
- Ok(())
- }
-}
-
-impl BytesSerializable for DeleteUser {
- fn to_bytes(&self) -> Bytes {
- self.user_id.to_bytes()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<DeleteUser, IggyError> {
- if bytes.len() < 3 {
- return Err(IggyError::InvalidCommand);
- }
-
- let user_id = Identifier::from_bytes(bytes)?;
- let command = DeleteUser { user_id };
- Ok(command)
- }
-}
-
-impl Display for DeleteUser {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}", self.user_id)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = DeleteUser {
- user_id: Identifier::numeric(1).unwrap(),
- };
-
- let bytes = command.to_bytes();
- let user_id = Identifier::from_bytes(bytes.clone()).unwrap();
-
- assert!(!bytes.is_empty());
- assert_eq!(user_id, command.user_id);
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let user_id = Identifier::numeric(1).unwrap();
- let bytes = user_id.to_bytes();
- let command = DeleteUser::from_bytes(bytes);
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.user_id, user_id);
- }
-}
diff --git a/core/common/src/commands/users/update_permissions.rs b/core/common/src/commands/users/update_permissions.rs
deleted file mode 100644
index 00510230a..000000000
--- a/core/common/src/commands/users/update_permissions.rs
+++ /dev/null
@@ -1,189 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Permissions;
-use crate::Sizeable;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{Command, UPDATE_PERMISSIONS_CODE};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-
-/// `UpdatePermissions` command is used to update a user's permissions.
-/// It has additional payload:
-/// - `user_id` - unique user ID (numeric or name).
-/// - `permissions` - new permissions (optional)
-#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
-pub struct UpdatePermissions {
- /// Unique user ID (numeric or name).
- #[serde(skip)]
- pub user_id: Identifier,
- /// New permissions if `None` is provided, then the existing user's permissions will be removed.
- pub permissions: Option<Permissions>,
-}
-
-impl Command for UpdatePermissions {
- fn code(&self) -> u32 {
- UPDATE_PERMISSIONS_CODE
- }
-}
-
-impl Validatable<IggyError> for UpdatePermissions {
- fn validate(&self) -> Result<(), IggyError> {
- Ok(())
- }
-}
-
-impl BytesSerializable for UpdatePermissions {
- fn to_bytes(&self) -> Bytes {
- let user_id_bytes = self.user_id.to_bytes();
- let mut bytes = BytesMut::new();
- bytes.put_slice(&user_id_bytes);
- if let Some(permissions) = &self.permissions {
- bytes.put_u8(1);
- bytes.put_u32_le(permissions.to_bytes().len() as u32);
- bytes.put_slice(&permissions.to_bytes());
- } else {
- bytes.put_u8(0);
- }
-
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<UpdatePermissions, IggyError> {
- if bytes.len() < 4 {
- return Err(IggyError::InvalidCommand);
- }
-
- let user_id = Identifier::from_bytes(bytes.clone())?;
- let mut position = user_id.get_size_bytes().as_bytes_usize();
- let has_permissions = *bytes.get(position).ok_or(IggyError::InvalidCommand)?;
- if has_permissions > 1 {
- return Err(IggyError::InvalidCommand);
- }
-
- position += 1;
- let permissions = if has_permissions == 1 {
- let permissions_length = u32::from_le_bytes(
- bytes
- .get(position..position + 4)
- .ok_or(IggyError::InvalidCommand)?
- .try_into()
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- position += 4;
- let end = position
- .checked_add(permissions_length as usize)
- .ok_or(IggyError::InvalidCommand)?;
- if end > bytes.len() {
- return Err(IggyError::InvalidCommand);
- }
- let permissions = Permissions::from_bytes(bytes.slice(position..end))?;
- Some(permissions)
- } else {
- None
- };
-
- let command = UpdatePermissions {
- user_id,
- permissions,
- };
- Ok(command)
- }
-}
-
-impl Display for UpdatePermissions {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let permissions = if let Some(permissions) = &self.permissions {
- permissions.to_string()
- } else {
- "no_permissions".to_string()
- };
- write!(f, "{}|{}", self.user_id, permissions)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::GlobalPermissions;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = UpdatePermissions {
- user_id: Identifier::numeric(1).unwrap(),
- permissions: Some(get_permissions()),
- };
- let bytes = command.to_bytes();
- let user_id = Identifier::from_bytes(bytes.clone()).unwrap();
- let mut position = user_id.get_size_bytes().as_bytes_usize();
- let has_permissions = bytes[position];
- position += 1;
- let permissions_length =
- u32::from_le_bytes(bytes[position..position + 4].try_into().unwrap());
- position += 4;
- let permissions =
- Permissions::from_bytes(bytes.slice(position..position + permissions_length as usize))
- .unwrap();
-
- assert!(!bytes.is_empty());
- assert_eq!(user_id, command.user_id);
- assert_eq!(has_permissions, 1);
- assert_eq!(permissions, command.permissions.unwrap());
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let user_id = Identifier::numeric(1).unwrap();
- let permissions = get_permissions();
- let permissions_bytes = permissions.to_bytes();
- let mut bytes = BytesMut::new();
- bytes.put_slice(&user_id.to_bytes());
- bytes.put_u8(1);
- bytes.put_u32_le(permissions_bytes.len() as u32);
- bytes.put_slice(&permissions_bytes);
-
- let command = UpdatePermissions::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.user_id, user_id);
- assert_eq!(command.permissions.unwrap(), permissions);
- }
-
- fn get_permissions() -> Permissions {
- Permissions {
- global: GlobalPermissions {
- manage_servers: true,
- read_servers: true,
- manage_users: true,
- read_users: true,
- manage_streams: false,
- read_streams: true,
- manage_topics: false,
- read_topics: true,
- poll_messages: true,
- send_messages: false,
- },
- streams: None,
- }
- }
-}
diff --git a/core/common/src/commands/users/update_user.rs b/core/common/src/commands/users/update_user.rs
deleted file mode 100644
index b6df319a7..000000000
--- a/core/common/src/commands/users/update_user.rs
+++ /dev/null
@@ -1,231 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-use super::defaults::*;
-use crate::BytesSerializable;
-use crate::Identifier;
-use crate::Sizeable;
-use crate::UserStatus;
-use crate::Validatable;
-use crate::error::IggyError;
-use crate::{Command, UPDATE_USER_CODE};
-use bytes::{BufMut, Bytes, BytesMut};
-use serde::{Deserialize, Serialize};
-use std::fmt::Display;
-use std::str::from_utf8;
-
-/// `UpdateUser` command is used to update a user's username and status.
-/// It has additional payload:
-/// - `user_id` - unique user ID (numeric or name).
-/// - `username` - new username (optional), if provided, must be between 3 and 50 characters long.
-/// - `status` - new status (optional)
-#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
-pub struct UpdateUser {
- #[serde(skip)]
- pub user_id: Identifier,
- pub username: Option<String>,
- pub status: Option<UserStatus>,
-}
-
-impl Command for UpdateUser {
- fn code(&self) -> u32 {
- UPDATE_USER_CODE
- }
-}
-
-impl Validatable<IggyError> for UpdateUser {
- fn validate(&self) -> Result<(), IggyError> {
- if self.username.is_none() {
- return Ok(());
- }
-
- let username = self.username.as_ref().unwrap();
- if username.is_empty()
- || username.len() > MAX_USERNAME_LENGTH
- || username.len() < MIN_USERNAME_LENGTH
- {
- return Err(IggyError::InvalidUsername);
- }
-
- Ok(())
- }
-}
-
-impl BytesSerializable for UpdateUser {
- fn to_bytes(&self) -> Bytes {
- let user_id_bytes = self.user_id.to_bytes();
- let mut bytes = BytesMut::new();
- bytes.put_slice(&user_id_bytes);
- if let Some(username) = &self.username {
- bytes.put_u8(1);
- #[allow(clippy::cast_possible_truncation)]
- bytes.put_u8(username.len() as u8);
- bytes.put_slice(username.as_bytes());
- } else {
- bytes.put_u8(0);
- }
- if let Some(status) = &self.status {
- bytes.put_u8(1);
- bytes.put_u8(status.as_code());
- } else {
- bytes.put_u8(0);
- }
-
- bytes.freeze()
- }
-
- fn from_bytes(bytes: Bytes) -> Result<UpdateUser, IggyError> {
- if bytes.len() < 5 {
- return Err(IggyError::InvalidCommand);
- }
-
- let user_id = Identifier::from_bytes(bytes.clone())?;
- let mut position = user_id.get_size_bytes().as_bytes_usize();
- let has_username = *bytes.get(position).ok_or(IggyError::InvalidCommand)?;
- if has_username > 1 {
- return Err(IggyError::InvalidCommand);
- }
-
- position += 1;
- let username = if has_username == 1 {
- let username_length = *bytes.get(position).ok_or(IggyError::InvalidCommand)?;
- position += 1;
- let username = from_utf8(
- bytes
- .get(position..position + username_length as usize)
- .ok_or(IggyError::InvalidCommand)?,
- )
- .map_err(|_| IggyError::InvalidUtf8)?
- .to_string();
- position += username_length as usize;
- Some(username)
- } else {
- None
- };
-
- let has_status = *bytes.get(position).ok_or(IggyError::InvalidCommand)?;
- if has_status > 1 {
- return Err(IggyError::InvalidCommand);
- }
-
- let status = if has_status == 1 {
- position += 1;
- let status =
- UserStatus::from_code(*bytes.get(position).ok_or(IggyError::InvalidCommand)?)?;
- Some(status)
- } else {
- None
- };
-
- let command = UpdateUser {
- user_id,
- username,
- status,
- };
- Ok(command)
- }
-}
-
-impl Display for UpdateUser {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let username = self.username.as_deref().unwrap_or("");
- let status = self
- .status
- .as_ref()
- .map_or_else(String::new, |s| s.to_string());
- write!(f, "{}|{username}|{status}", self.user_id)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn should_be_serialized_as_bytes() {
- let command = UpdateUser {
- user_id: Identifier::numeric(1).unwrap(),
- username: Some("user".to_string()),
- status: Some(UserStatus::Active),
- };
-
- let bytes = command.to_bytes();
- let user_id = Identifier::from_bytes(bytes.clone()).unwrap();
- let mut position = user_id.get_size_bytes().as_bytes_usize();
- let has_username = bytes[position];
- position += 1;
- let username_length = bytes[position];
- position += 1;
- let username = from_utf8(&bytes[position..position + username_length as usize]).unwrap();
- position += username_length as usize;
- let has_status = bytes[position];
- position += 1;
- let status = UserStatus::from_code(bytes[position]).unwrap();
-
- assert!(!bytes.is_empty());
- assert_eq!(user_id, command.user_id);
- assert_eq!(has_username, 1);
- assert_eq!(username, command.username.unwrap());
- assert_eq!(has_status, 1);
- assert_eq!(status, command.status.unwrap());
- }
-
- #[test]
- fn from_bytes_should_fail_on_empty_input() {
- assert!(UpdateUser::from_bytes(Bytes::new()).is_err());
- }
-
- #[test]
- fn from_bytes_should_fail_on_truncated_input() {
- let command = UpdateUser {
- user_id: Identifier::numeric(1).unwrap(),
- username: Some("user".to_string()),
- status: Some(UserStatus::Active),
- };
- let bytes = command.to_bytes();
- for i in 0..bytes.len() - 1 {
- let truncated = bytes.slice(..i);
- assert!(
- UpdateUser::from_bytes(truncated).is_err(),
- "expected error for truncation at byte {i}"
- );
- }
- }
-
- #[test]
- fn should_be_deserialized_from_bytes() {
- let user_id = Identifier::numeric(1).unwrap();
- let username = "user";
- let status = UserStatus::Active;
- let mut bytes = BytesMut::new();
- bytes.put_slice(&user_id.to_bytes());
- bytes.put_u8(1);
- bytes.put_u8(username.len() as u8);
- bytes.put_slice(username.as_bytes());
- bytes.put_u8(1);
- bytes.put_u8(status.as_code());
-
- let command = UpdateUser::from_bytes(bytes.freeze());
- assert!(command.is_ok());
-
- let command = command.unwrap();
- assert_eq!(command.user_id, user_id);
- assert_eq!(command.username.unwrap(), username);
- assert_eq!(command.status.unwrap(), status);
- }
-}
diff --git a/core/common/src/http/consumer_groups/create_consumer_group.rs b/core/common/src/http/consumer_groups/create_consumer_group.rs
new file mode 100644
index 000000000..114094750
--- /dev/null
+++ b/core/common/src/http/consumer_groups/create_consumer_group.rs
@@ -0,0 +1,60 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::MAX_NAME_LENGTH;
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
+
+/// `CreateConsumerGroup` command creates a new consumer group for the topic.
+/// It has additional payload:
+/// - `stream_id` - unique stream ID (numeric or name).
+/// - `topic_id` - unique topic ID (numeric or name).
+/// - `name` - unique consumer group name, max length is 255 characters.
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+pub struct CreateConsumerGroup {
+ /// Unique stream ID (numeric or name).
+ #[serde(skip)]
+ pub stream_id: Identifier,
+ /// Unique topic ID (numeric or name).
+ #[serde(skip)]
+ pub topic_id: Identifier,
+ /// Unique consumer group name, max length is 255 characters.
+ pub name: String,
+}
+
+impl Default for CreateConsumerGroup {
+ fn default() -> Self {
+ CreateConsumerGroup {
+ stream_id: Identifier::default(),
+ topic_id: Identifier::default(),
+ name: "consumer_group_1".to_string(),
+ }
+ }
+}
+
+impl Validatable<IggyError> for CreateConsumerGroup {
+ fn validate(&self) -> Result<(), IggyError> {
+ if self.name.is_empty() || self.name.len() > MAX_NAME_LENGTH {
+ return Err(IggyError::InvalidConsumerGroupName);
+ }
+
+ Ok(())
+ }
+}
diff --git a/core/common/src/http/consumer_groups/delete_consumer_group.rs b/core/common/src/http/consumer_groups/delete_consumer_group.rs
new file mode 100644
index 000000000..fe1b73975
--- /dev/null
+++ b/core/common/src/http/consumer_groups/delete_consumer_group.rs
@@ -0,0 +1,46 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
+
+/// `DeleteConsumerGroup` command deletes an existing consumer group from the topic.
+/// It has additional payload:
+/// - `stream_id` - unique stream ID (numeric or name).
+/// - `topic_id` - unique topic ID (numeric or name).
+/// - `group_id` - unique consumer group ID (numeric or name).
+#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
+pub struct DeleteConsumerGroup {
+ /// Unique stream ID (numeric or name).
+ #[serde(skip)]
+ pub stream_id: Identifier,
+ /// Unique topic ID (numeric or name).
+ #[serde(skip)]
+ pub topic_id: Identifier,
+ /// Unique consumer group ID (numeric or name).
+ #[serde(skip)]
+ pub group_id: Identifier,
+}
+
+impl Validatable<IggyError> for DeleteConsumerGroup {
+ fn validate(&self) -> Result<(), IggyError> {
+ Ok(())
+ }
+}
diff --git a/core/common/src/commands/consumer_groups/mod.rs b/core/common/src/http/consumer_groups/mod.rs
similarity index 100%
rename from core/common/src/commands/consumer_groups/mod.rs
rename to core/common/src/http/consumer_groups/mod.rs
diff --git a/core/common/src/commands/consumer_offsets/mod.rs b/core/common/src/http/consumer_offsets/mod.rs
similarity index 100%
rename from core/common/src/commands/consumer_offsets/mod.rs
rename to core/common/src/http/consumer_offsets/mod.rs
diff --git a/core/common/src/commands/messages/mod.rs b/core/common/src/http/messages/mod.rs
similarity index 100%
rename from core/common/src/commands/messages/mod.rs
rename to core/common/src/http/messages/mod.rs
diff --git a/core/common/src/http/messages/poll_messages.rs b/core/common/src/http/messages/poll_messages.rs
new file mode 100644
index 000000000..e8ca86539
--- /dev/null
+++ b/core/common/src/http/messages/poll_messages.rs
@@ -0,0 +1,131 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use crate::Consumer;
+use crate::error::IggyError;
+use crate::{BytesSerializable, Identifier, PollingStrategy, Validatable};
+use bytes::{BufMut, Bytes, BytesMut};
+use serde::{Deserialize, Serialize};
+
+pub const DEFAULT_PARTITION_ID: u32 = 0;
+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.
+/// - `stream_id` - unique stream ID (numeric or name).
+/// - `topic_id` - unique topic ID (numeric or name).
+/// - `partition_id` - partition ID from which messages will be polled. Has to be specified for the regular consumer. For consumer group it is ignored (use `None`).
+/// - `strategy` - polling strategy which specifies from where to start polling messages.
+/// - `count` - number of messages to poll.
+/// - `auto_commit` - whether to commit offset on the server automatically after polling the messages.
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+pub struct PollMessages {
+ /// Consumer which will poll messages. Either regular consumer or consumer group.
+ #[serde(flatten)]
+ pub consumer: Consumer,
+ /// Unique stream ID (numeric or name).
+ #[serde(skip)]
+ pub stream_id: Identifier,
+ /// Unique topic ID (numeric or name).
+ #[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 = "PollMessages::default_partition_id")]
+ pub partition_id: Option<u32>,
+ /// Polling strategy which specifies from where to start polling messages.
+ #[serde(default = "PollingStrategy::default", flatten)]
+ pub strategy: PollingStrategy,
+ /// Number of messages to poll.
+ #[serde(default = "PollMessages::default_number_of_messages_to_poll")]
+ pub count: u32,
+ /// Whether to commit offset on the server automatically after polling the messages.
+ #[serde(default)]
+ pub auto_commit: bool,
+}
+
+impl PollMessages {
+ pub fn bytes(
+ stream_id: &Identifier,
+ topic_id: &Identifier,
+ partition_id: Option<u32>,
+ consumer: &Consumer,
+ strategy: &PollingStrategy,
+ count: u32,
+ auto_commit: bool,
+ ) -> Bytes {
+ let consumer_bytes = consumer.to_bytes();
+ let stream_id_bytes = stream_id.to_bytes();
+ let topic_id_bytes = topic_id.to_bytes();
+ let strategy_bytes = strategy.to_bytes();
+ let mut bytes = BytesMut::with_capacity(
+ 10 + consumer_bytes.len()
+ + stream_id_bytes.len()
+ + topic_id_bytes.len()
+ + strategy_bytes.len(),
+ );
+ bytes.put_slice(&consumer_bytes);
+ bytes.put_slice(&stream_id_bytes);
+ bytes.put_slice(&topic_id_bytes);
+ // Encode partition_id with a flag byte: 1 = Some, 0 = None
+ if let Some(partition_id) = partition_id {
+ bytes.put_u8(1);
+ bytes.put_u32_le(partition_id);
+ } else {
+ bytes.put_u8(0);
+ bytes.put_u32_le(0); // Padding to keep structure consistent
+ }
+ bytes.put_slice(&strategy_bytes);
+ bytes.put_u32_le(count);
+ if auto_commit {
+ bytes.put_u8(1);
+ } else {
+ bytes.put_u8(0);
+ }
+
+ bytes.freeze()
+ }
+
+ pub fn default_number_of_messages_to_poll() -> u32 {
+ DEFAULT_NUMBER_OF_MESSAGES_TO_POLL
+ }
+
+ pub fn default_partition_id() -> Option<u32> {
+ Some(DEFAULT_PARTITION_ID)
+ }
+}
+
+impl Default for PollMessages {
+ fn default() -> Self {
+ Self {
+ consumer: Consumer::default(),
+ stream_id: Identifier::numeric(1).unwrap(),
+ topic_id: Identifier::numeric(1).unwrap(),
+ partition_id: PollMessages::default_partition_id(),
+ strategy: PollingStrategy::default(),
+ count: PollMessages::default_number_of_messages_to_poll(),
+ auto_commit: false,
+ }
+ }
+}
+
+impl Validatable<IggyError> for PollMessages {
+ fn validate(&self) -> Result<(), IggyError> {
+ Ok(())
+ }
+}
diff --git a/core/common/src/commands/messages/send_messages.rs b/core/common/src/http/messages/send_messages.rs
similarity index 96%
rename from core/common/src/commands/messages/send_messages.rs
rename to core/common/src/http/messages/send_messages.rs
index 2943340e9..0168caa2d 100644
--- a/core/common/src/commands/messages/send_messages.rs
+++ b/core/common/src/http/messages/send_messages.rs
@@ -25,7 +25,6 @@ use crate::Validatable;
use crate::error::IggyError;
use crate::types::message::HeaderEntry;
use crate::types::message::partitioning::Partitioning;
-use crate::{Command, SEND_MESSAGES_CODE};
use crate::{INDEX_SIZE, IggyMessage, IggyMessagesBatch};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use bytes::{BufMut, Bytes, BytesMut};
@@ -33,7 +32,7 @@ use serde::de::{self, MapAccess, Visitor};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
-use std::fmt::{Display, Formatter};
+use std::fmt::Formatter;
/// `SendMessages` command is used to send messages to a topic in a stream.
/// It has additional payload:
@@ -140,12 +139,6 @@ impl Default for SendMessages {
}
}
-impl Command for SendMessages {
- fn code(&self) -> u32 {
- SEND_MESSAGES_CODE
- }
-}
-
impl Validatable<IggyError> for SendMessages {
fn validate(&self) -> Result<(), IggyError> {
if self.partitioning.value.len() > 255
@@ -161,28 +154,6 @@ impl Validatable<IggyError> for SendMessages {
}
}
-impl BytesSerializable for SendMessages {
- fn to_bytes(&self) -> Bytes {
- panic!("should not be used")
- }
-
- fn from_bytes(_bytes: Bytes) -> Result<SendMessages, IggyError> {
- panic!("should not be used")
- }
-}
-
-impl Display for SendMessages {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- let messages_count = self.batch.count();
- let messages_size = self.batch.size();
- write!(
- f,
- "{}|{}|{}|messages_count:{}|messages_size:{}",
- self.stream_id, self.topic_id, self.partitioning, messages_count, messages_size
- )
- }
-}
-
impl Serialize for SendMessages {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
diff --git a/core/common/src/commands/mod.rs b/core/common/src/http/mod.rs
similarity index 100%
rename from core/common/src/commands/mod.rs
rename to core/common/src/http/mod.rs
diff --git a/core/common/src/http/partitions/create_partitions.rs b/core/common/src/http/partitions/create_partitions.rs
new file mode 100644
index 000000000..392c3e8d0
--- /dev/null
+++ b/core/common/src/http/partitions/create_partitions.rs
@@ -0,0 +1,60 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::MAX_PARTITIONS_COUNT;
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
+
+/// `CreatePartitions` command is used to create new partitions for a topic.
+/// It has additional payload:
+/// - `stream_id` - unique stream ID (numeric or name).
+/// - `topic_id` - unique topic ID (numeric or name).
+/// - `partitions_count` - number of partitions in the topic to create, max value is 1000.
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+pub struct CreatePartitions {
+ /// Unique stream ID (numeric or name).
+ #[serde(skip)]
+ pub stream_id: Identifier,
+ /// Unique topic ID (numeric or name).
+ #[serde(skip)]
+ pub topic_id: Identifier,
+ /// Number of partitions in the topic to create, max value is 1000.
+ pub partitions_count: u32,
+}
+
+impl Default for CreatePartitions {
+ fn default() -> Self {
+ CreatePartitions {
+ stream_id: Identifier::default(),
+ topic_id: Identifier::default(),
+ partitions_count: 1,
+ }
+ }
+}
+
+impl Validatable<IggyError> for CreatePartitions {
+ fn validate(&self) -> Result<(), IggyError> {
+ if !(1..=MAX_PARTITIONS_COUNT).contains(&self.partitions_count) {
+ return Err(IggyError::TooManyPartitions);
+ }
+
+ Ok(())
+ }
+}
diff --git a/core/common/src/http/partitions/delete_partitions.rs b/core/common/src/http/partitions/delete_partitions.rs
new file mode 100644
index 000000000..6c184cb65
--- /dev/null
+++ b/core/common/src/http/partitions/delete_partitions.rs
@@ -0,0 +1,60 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::MAX_PARTITIONS_COUNT;
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
+
+/// `DeletePartitions` command is used to delete partitions from a topic.
+/// It has additional payload:
+/// - `stream_id` - unique stream ID (numeric or name).
+/// - `topic_id` - unique topic ID (numeric or name).
+/// - `partitions_count` - number of partitions in the topic to delete, max value is 1000.
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+pub struct DeletePartitions {
+ /// Unique stream ID (numeric or name).
+ #[serde(skip)]
+ pub stream_id: Identifier,
+ /// Unique topic ID (numeric or name).
+ #[serde(skip)]
+ pub topic_id: Identifier,
+ /// Number of partitions in the topic to delete, max value is 1000.
+ pub partitions_count: u32,
+}
+
+impl Default for DeletePartitions {
+ fn default() -> Self {
+ DeletePartitions {
+ stream_id: Identifier::default(),
+ topic_id: Identifier::default(),
+ partitions_count: 1,
+ }
+ }
+}
+
+impl Validatable<IggyError> for DeletePartitions {
+ fn validate(&self) -> Result<(), IggyError> {
+ if !(1..=MAX_PARTITIONS_COUNT).contains(&self.partitions_count) {
+ return Err(IggyError::TooManyPartitions);
+ }
+
+ Ok(())
+ }
+}
diff --git a/core/common/src/commands/partitions/mod.rs b/core/common/src/http/partitions/mod.rs
similarity index 100%
rename from core/common/src/commands/partitions/mod.rs
rename to core/common/src/http/partitions/mod.rs
diff --git a/core/common/src/http/personal_access_tokens/create_personal_access_token.rs b/core/common/src/http/personal_access_tokens/create_personal_access_token.rs
new file mode 100644
index 000000000..f8948a380
--- /dev/null
+++ b/core/common/src/http/personal_access_tokens/create_personal_access_token.rs
@@ -0,0 +1,57 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use crate::Validatable;
+use crate::defaults::*;
+use crate::error::IggyError;
+use crate::utils::expiry::IggyExpiry;
+use serde::{Deserialize, Serialize};
+
+/// `CreatePersonalAccessToken` command is used to create a new personal access token for the authenticated user.
+/// It has additional payload:
+/// - `name` - unique name of the token, must be between 3 and 30 characters long.
+/// - `expiry` - expiry of the token.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct CreatePersonalAccessToken {
+ /// Unique name of the token, must be between 3 and 30 characters long.
+ pub name: String,
+ /// Expiry of the token.
+ pub expiry: IggyExpiry,
+}
+
+impl Default for CreatePersonalAccessToken {
+ fn default() -> Self {
+ CreatePersonalAccessToken {
+ name: "token".to_string(),
+ expiry: IggyExpiry::NeverExpire,
+ }
+ }
+}
+
+impl Validatable<IggyError> for CreatePersonalAccessToken {
+ fn validate(&self) -> Result<(), IggyError> {
+ if self.name.is_empty()
+ || self.name.len() > MAX_PERSONAL_ACCESS_TOKEN_NAME_LENGTH
+ || self.name.len() < MIN_PERSONAL_ACCESS_TOKEN_NAME_LENGTH
+ {
+ return Err(IggyError::InvalidPersonalAccessTokenName);
+ }
+
+ Ok(())
+ }
+}
diff --git a/core/common/src/http/personal_access_tokens/delete_personal_access_token.rs b/core/common/src/http/personal_access_tokens/delete_personal_access_token.rs
new file mode 100644
index 000000000..4c6106fe7
--- /dev/null
+++ b/core/common/src/http/personal_access_tokens/delete_personal_access_token.rs
@@ -0,0 +1,52 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use crate::Validatable;
+use crate::defaults::*;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
+
+/// `DeletePersonalAccessToken` command is used to delete a personal access token for the authenticated user.
+/// It has additional payload:
+/// - `name` - unique name of the token, must be between 3 and 30 characters long.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct DeletePersonalAccessToken {
+ /// Unique name of the token, must be between 3 and 30 characters long.
+ pub name: String,
+}
+
+impl Default for DeletePersonalAccessToken {
+ fn default() -> Self {
+ DeletePersonalAccessToken {
+ name: "token".to_string(),
+ }
+ }
+}
+
+impl Validatable<IggyError> for DeletePersonalAccessToken {
+ fn validate(&self) -> Result<(), IggyError> {
+ if self.name.is_empty()
+ || self.name.len() > MAX_PERSONAL_ACCESS_TOKEN_NAME_LENGTH
+ || self.name.len() < MIN_PERSONAL_ACCESS_TOKEN_NAME_LENGTH
+ {
+ return Err(IggyError::InvalidPersonalAccessTokenName);
+ }
+
+ Ok(())
+ }
+}
diff --git a/core/common/src/commands/personal_access_tokens/mod.rs b/core/common/src/http/personal_access_tokens/mod.rs
similarity index 100%
rename from core/common/src/commands/personal_access_tokens/mod.rs
rename to core/common/src/http/personal_access_tokens/mod.rs
diff --git a/core/common/src/http/segments/delete_segments.rs b/core/common/src/http/segments/delete_segments.rs
new file mode 100644
index 000000000..9c4fa6cf8
--- /dev/null
+++ b/core/common/src/http/segments/delete_segments.rs
@@ -0,0 +1,59 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
+
+/// `DeleteSegments` command is used to delete segments from a partition.
+/// It has additional payload:
+/// - `stream_id` - unique stream ID (numeric or name).
+/// - `topic_id` - unique topic ID (numeric or name).
+/// - `partition_id` - unique partition ID (numeric or name).
+/// - `segments_count` - number of segments in the partition to delete.
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+pub struct DeleteSegments {
+ /// Unique stream ID (numeric or name).
+ #[serde(skip)]
+ pub stream_id: Identifier,
+ /// Unique topic ID (numeric or name).
+ #[serde(skip)]
+ pub topic_id: Identifier,
+ /// Unique partition ID (numeric or name).
+ #[serde(skip)]
+ pub partition_id: u32,
+ /// Number of segments in the partition to delete, max value is 1000.
+ pub segments_count: u32,
+}
+
+impl Default for DeleteSegments {
+ fn default() -> Self {
+ DeleteSegments {
+ segments_count: 1,
+ stream_id: Identifier::default(),
+ topic_id: Identifier::default(),
+ partition_id: u32::default(),
+ }
+ }
+}
+
+impl Validatable<IggyError> for DeleteSegments {
+ fn validate(&self) -> Result<(), IggyError> {
+ Ok(())
+ }
+}
diff --git a/core/common/src/commands/segments/mod.rs b/core/common/src/http/segments/mod.rs
similarity index 100%
rename from core/common/src/commands/segments/mod.rs
rename to core/common/src/http/segments/mod.rs
diff --git a/core/common/src/http/streams/create_stream.rs b/core/common/src/http/streams/create_stream.rs
new file mode 100644
index 000000000..1c9cc4967
--- /dev/null
+++ b/core/common/src/http/streams/create_stream.rs
@@ -0,0 +1,49 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::MAX_NAME_LENGTH;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
+
+/// `CreateStream` command is used to create a new stream.
+/// It has additional payload:
+/// - `name` - unique stream name (string), max length is 255 characters.
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+pub struct CreateStream {
+ /// Unique stream name (string), max length is 255 characters.
+ pub name: String,
+}
+
+impl Default for CreateStream {
+ fn default() -> Self {
+ CreateStream {
+ name: "stream".to_string(),
+ }
+ }
+}
+
+impl Validatable<IggyError> for CreateStream {
+ fn validate(&self) -> Result<(), IggyError> {
+ if self.name.is_empty() || self.name.len() > MAX_NAME_LENGTH {
+ return Err(IggyError::InvalidStreamName);
+ }
+
+ Ok(())
+ }
+}
diff --git a/core/common/src/commands/streams/mod.rs b/core/common/src/http/streams/delete_stream.rs
similarity index 58%
copy from core/common/src/commands/streams/mod.rs
copy to core/common/src/http/streams/delete_stream.rs
index 429b4ed2d..b683cc88f 100644
--- a/core/common/src/commands/streams/mod.rs
+++ b/core/common/src/http/streams/delete_stream.rs
@@ -16,9 +16,23 @@
* under the License.
*/
-pub mod create_stream;
-pub mod delete_stream;
-pub mod purge_stream;
-pub mod update_stream;
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
-const MAX_NAME_LENGTH: usize = 255;
+/// `DeleteStream` command is used to delete an existing stream.
+/// It has additional payload:
+/// - `stream_id` - unique stream ID (numeric or name).
+#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
+pub struct DeleteStream {
+ /// Unique stream ID (numeric or name).
+ #[serde(skip)]
+ pub stream_id: Identifier,
+}
+
+impl Validatable<IggyError> for DeleteStream {
+ fn validate(&self) -> Result<(), IggyError> {
+ Ok(())
+ }
+}
diff --git a/core/common/src/commands/streams/mod.rs b/core/common/src/http/streams/mod.rs
similarity index 100%
copy from core/common/src/commands/streams/mod.rs
copy to core/common/src/http/streams/mod.rs
diff --git a/core/common/src/commands/streams/mod.rs b/core/common/src/http/streams/purge_stream.rs
similarity index 57%
copy from core/common/src/commands/streams/mod.rs
copy to core/common/src/http/streams/purge_stream.rs
index 429b4ed2d..c77f2a1da 100644
--- a/core/common/src/commands/streams/mod.rs
+++ b/core/common/src/http/streams/purge_stream.rs
@@ -16,9 +16,23 @@
* under the License.
*/
-pub mod create_stream;
-pub mod delete_stream;
-pub mod purge_stream;
-pub mod update_stream;
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
-const MAX_NAME_LENGTH: usize = 255;
+/// `PurgeStream` command is used to purge stream data (all the messages from its topics).
+/// It has additional payload:
+/// - `stream_id` - unique stream ID (numeric or name).
+#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
+pub struct PurgeStream {
+ /// Unique stream ID (numeric or name).
+ #[serde(skip)]
+ pub stream_id: Identifier,
+}
+
+impl Validatable<IggyError> for PurgeStream {
+ fn validate(&self) -> Result<(), IggyError> {
+ Ok(())
+ }
+}
diff --git a/core/common/src/http/streams/update_stream.rs b/core/common/src/http/streams/update_stream.rs
new file mode 100644
index 000000000..b99e02cce
--- /dev/null
+++ b/core/common/src/http/streams/update_stream.rs
@@ -0,0 +1,55 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::MAX_NAME_LENGTH;
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
+
+/// `UpdateStream` command is used to update an existing stream.
+/// It has additional payload:
+/// - `stream_id` - unique stream ID (numeric or name).
+/// - `name` - unique stream name (string), max length is 255 characters.
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+pub struct UpdateStream {
+ /// Unique stream ID (numeric or name).
+ #[serde(skip)]
+ pub stream_id: Identifier,
+ /// Unique stream name (string), max length is 255 characters.
+ pub name: String,
+}
+
+impl Default for UpdateStream {
+ fn default() -> Self {
+ UpdateStream {
+ stream_id: Identifier::default(),
+ name: "stream".to_string(),
+ }
+ }
+}
+
+impl Validatable<IggyError> for UpdateStream {
+ fn validate(&self) -> Result<(), IggyError> {
+ if self.name.is_empty() || self.name.len() > MAX_NAME_LENGTH {
+ return Err(IggyError::InvalidStreamName);
+ }
+
+ Ok(())
+ }
+}
diff --git a/core/common/src/commands/system/mod.rs b/core/common/src/http/system/mod.rs
similarity index 100%
rename from core/common/src/commands/system/mod.rs
rename to core/common/src/http/system/mod.rs
diff --git a/core/common/src/http/topics/create_topic.rs b/core/common/src/http/topics/create_topic.rs
new file mode 100644
index 000000000..94dd38fd5
--- /dev/null
+++ b/core/common/src/http/topics/create_topic.rs
@@ -0,0 +1,89 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::{MAX_NAME_LENGTH, MAX_PARTITIONS_COUNT};
+use crate::CompressionAlgorithm;
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use crate::utils::expiry::IggyExpiry;
+use crate::utils::topic_size::MaxTopicSize;
+use serde::{Deserialize, Serialize};
+
+/// `CreateTopic` command is used to create a new topic in a stream.
+/// It has additional payload:
+/// - `stream_id` - unique stream ID (numeric or name).
+/// - `partitions_count` - number of partitions in the topic, max value is 1000.
+/// - `message_expiry` - message expiry, if `NeverExpire` then messages will never expire.
+/// - `max_topic_size` - maximum size of the topic, if `Unlimited` then topic size is unlimited.
+/// Can't be lower than segment size in the config.
+/// - `replication_factor` - replication factor for the topic.
+/// - `name` - unique topic name, max length is 255 characters.
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+pub struct CreateTopic {
+ /// Unique stream ID (numeric or name).
+ #[serde(skip)]
+ pub stream_id: Identifier,
+ /// Number of partitions in the topic, max value is 1000.
+ pub partitions_count: u32,
+ /// Compression algorithm for the topic.
+ pub compression_algorithm: CompressionAlgorithm,
+ /// Message expiry, if `NeverExpire` then messages will never expire.
+ pub message_expiry: IggyExpiry,
+ /// Max topic size, if `Unlimited` then topic size is unlimited.
+ /// Can't be lower than segment size in the config.
+ pub max_topic_size: MaxTopicSize,
+ /// Replication factor for the topic.
+ pub replication_factor: Option<u8>,
+ /// Unique topic name, max length is 255 characters.
+ pub name: String,
+}
+
+impl Default for CreateTopic {
+ fn default() -> Self {
+ CreateTopic {
+ stream_id: Identifier::default(),
+ partitions_count: 1,
+ compression_algorithm: CompressionAlgorithm::None,
+ message_expiry: IggyExpiry::NeverExpire,
+ max_topic_size: MaxTopicSize::ServerDefault,
+ replication_factor: None,
+ name: "topic".to_string(),
+ }
+ }
+}
+
+impl Validatable<IggyError> for CreateTopic {
+ fn validate(&self) -> Result<(), IggyError> {
+ if self.name.is_empty() || self.name.len() > MAX_NAME_LENGTH {
+ return Err(IggyError::InvalidTopicName);
+ }
+
+ if !(0..=MAX_PARTITIONS_COUNT).contains(&self.partitions_count) {
+ return Err(IggyError::TooManyPartitions);
+ }
+
+ if let Some(replication_factor) = self.replication_factor
+ && replication_factor == 0
+ {
+ return Err(IggyError::InvalidReplicationFactor);
+ }
+
+ Ok(())
+ }
+}
diff --git a/core/common/src/commands/streams/mod.rs b/core/common/src/http/topics/delete_topic.rs
similarity index 52%
copy from core/common/src/commands/streams/mod.rs
copy to core/common/src/http/topics/delete_topic.rs
index 429b4ed2d..84635ba91 100644
--- a/core/common/src/commands/streams/mod.rs
+++ b/core/common/src/http/topics/delete_topic.rs
@@ -16,9 +16,27 @@
* under the License.
*/
-pub mod create_stream;
-pub mod delete_stream;
-pub mod purge_stream;
-pub mod update_stream;
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
-const MAX_NAME_LENGTH: usize = 255;
+/// `DeleteTopic` command is used to delete a topic from a stream.
+/// It has additional payload:
+/// - `stream_id` - unique stream ID (numeric or name).
+/// - `topic_id` - unique topic ID (numeric or name).
+#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
+pub struct DeleteTopic {
+ /// Unique stream ID (numeric or name).
+ #[serde(skip)]
+ pub stream_id: Identifier,
+ /// Unique topic ID (numeric or name).
+ #[serde(skip)]
+ pub topic_id: Identifier,
+}
+
+impl Validatable<IggyError> for DeleteTopic {
+ fn validate(&self) -> Result<(), IggyError> {
+ Ok(())
+ }
+}
diff --git a/core/common/src/commands/topics/mod.rs b/core/common/src/http/topics/mod.rs
similarity index 100%
rename from core/common/src/commands/topics/mod.rs
rename to core/common/src/http/topics/mod.rs
diff --git a/core/common/src/commands/streams/mod.rs b/core/common/src/http/topics/purge_topic.rs
similarity index 51%
copy from core/common/src/commands/streams/mod.rs
copy to core/common/src/http/topics/purge_topic.rs
index 429b4ed2d..327222438 100644
--- a/core/common/src/commands/streams/mod.rs
+++ b/core/common/src/http/topics/purge_topic.rs
@@ -16,9 +16,27 @@
* under the License.
*/
-pub mod create_stream;
-pub mod delete_stream;
-pub mod purge_stream;
-pub mod update_stream;
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
-const MAX_NAME_LENGTH: usize = 255;
+/// `PurgeTopic` command is used to purge topic data (its messages in all the partitions) from a stream.
+/// It has additional payload:
+/// - `stream_id` - unique stream ID (numeric or name).
+/// - `topic_id` - unique topic ID (numeric or name).
+#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
+pub struct PurgeTopic {
+ /// Unique stream ID (numeric or name).
+ #[serde(skip)]
+ pub stream_id: Identifier,
+ /// Unique topic ID (numeric or name).
+ #[serde(skip)]
+ pub topic_id: Identifier,
+}
+
+impl Validatable<IggyError> for PurgeTopic {
+ fn validate(&self) -> Result<(), IggyError> {
+ Ok(())
+ }
+}
diff --git a/core/common/src/http/topics/update_topic.rs b/core/common/src/http/topics/update_topic.rs
new file mode 100644
index 000000000..67385a831
--- /dev/null
+++ b/core/common/src/http/topics/update_topic.rs
@@ -0,0 +1,86 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::MAX_NAME_LENGTH;
+use crate::CompressionAlgorithm;
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use crate::utils::expiry::IggyExpiry;
+use crate::utils::topic_size::MaxTopicSize;
+use serde::{Deserialize, Serialize};
+
+/// `UpdateTopic` command is used to update a topic in a stream.
+/// It has additional payload:
+/// - `stream_id` - unique stream ID (numeric or name).
+/// - `topic_id` - unique topic ID (numeric or name).
+/// - `message_expiry` - message expiry, if `NeverExpire` then messages will never expire.
+/// - `max_topic_size` - maximum size of the topic in bytes, if `Unlimited` then topic size is unlimited.
+/// Can't be lower than segment size in the config.
+/// - `replication_factor` - replication factor for the topic.
+/// - `name` - unique topic name, max length is 255 characters.
+#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
+pub struct UpdateTopic {
+ /// Unique stream ID (numeric or name).
+ #[serde(skip)]
+ pub stream_id: Identifier,
+ /// Unique topic ID (numeric or name).
+ #[serde(skip)]
+ pub topic_id: Identifier,
+ /// Compression algorithm for the topic.
+ pub compression_algorithm: CompressionAlgorithm,
+ /// Message expiry, if `NeverExpire` then messages will never expire.
+ pub message_expiry: IggyExpiry,
+ /// Max topic size, if `Unlimited` then topic size is unlimited.
+ /// Can't be lower than segment size in the config.
+ pub max_topic_size: MaxTopicSize,
+ /// Replication factor for the topic.
+ pub replication_factor: Option<u8>,
+ /// Unique topic name, max length is 255 characters.
+ pub name: String,
+}
+
+impl Default for UpdateTopic {
+ fn default() -> Self {
+ UpdateTopic {
+ stream_id: Identifier::default(),
+ topic_id: Identifier::default(),
+ compression_algorithm: Default::default(),
+ message_expiry: IggyExpiry::NeverExpire,
+ max_topic_size: MaxTopicSize::ServerDefault,
+ replication_factor: None,
+ name: "topic".to_string(),
+ }
+ }
+}
+
+impl Validatable<IggyError> for UpdateTopic {
+ fn validate(&self) -> Result<(), IggyError> {
+ if self.name.is_empty() || self.name.len() > MAX_NAME_LENGTH {
+ return Err(IggyError::InvalidTopicName);
+ }
+
+ if let Some(replication_factor) = self.replication_factor
+ && replication_factor == 0
+ {
+ return Err(IggyError::InvalidReplicationFactor);
+ }
+
+ Ok(())
+ }
+}
diff --git a/core/common/src/http/users/change_password.rs b/core/common/src/http/users/change_password.rs
new file mode 100644
index 000000000..f1936fac4
--- /dev/null
+++ b/core/common/src/http/users/change_password.rs
@@ -0,0 +1,74 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::defaults::*;
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use secrecy::{ExposeSecret, SecretString};
+use serde::{Deserialize, Serialize};
+
+/// `ChangePassword` command is used to change a user's password.
+/// It has additional payload:
+/// - `user_id` - unique user ID (numeric or name).
+/// - `current_password` - current password, must be between 3 and 100 characters long.
+/// - `new_password` - new password, must be between 3 and 100 characters long.
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct ChangePassword {
+ /// Unique user ID (numeric or name).
+ #[serde(skip)]
+ pub user_id: Identifier,
+ /// Current password, must be between 3 and 100 characters long.
+ #[serde(serialize_with = "crate::utils::serde_secret::serialize_secret")]
+ pub current_password: SecretString,
+ /// New password, must be between 3 and 100 characters long.
+ #[serde(serialize_with = "crate::utils::serde_secret::serialize_secret")]
+ pub new_password: SecretString,
+}
+
+impl Default for ChangePassword {
+ fn default() -> Self {
+ ChangePassword {
+ user_id: Identifier::default(),
+ current_password: SecretString::from("secret"),
+ new_password: SecretString::from("topsecret"),
+ }
+ }
+}
+
+impl Validatable<IggyError> for ChangePassword {
+ fn validate(&self) -> Result<(), IggyError> {
+ let current_password = self.current_password.expose_secret();
+ if current_password.is_empty()
+ || current_password.len() > MAX_PASSWORD_LENGTH
+ || current_password.len() < MIN_PASSWORD_LENGTH
+ {
+ return Err(IggyError::InvalidPassword);
+ }
+
+ let new_password = self.new_password.expose_secret();
+ if new_password.is_empty()
+ || new_password.len() > MAX_PASSWORD_LENGTH
+ || new_password.len() < MIN_PASSWORD_LENGTH
+ {
+ return Err(IggyError::InvalidPassword);
+ }
+
+ Ok(())
+ }
+}
diff --git a/core/common/src/http/users/create_user.rs b/core/common/src/http/users/create_user.rs
new file mode 100644
index 000000000..c357ee2ce
--- /dev/null
+++ b/core/common/src/http/users/create_user.rs
@@ -0,0 +1,76 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::defaults::*;
+use crate::Permissions;
+use crate::UserStatus;
+use crate::Validatable;
+use crate::error::IggyError;
+use secrecy::{ExposeSecret, SecretString};
+use serde::{Deserialize, Serialize};
+
+/// `CreateUser` command is used to create a new user.
+/// It has additional payload:
+/// - `username` - unique name of the user, must be between 3 and 50 characters long.
+/// - `password` - password of the user, must be between 3 and 100 characters long.
+/// - `status` - status of the user, can be either `active` or `inactive`.
+/// - `permissions` - optional permissions of the user. If not provided, user will have no permissions.
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct CreateUser {
+ /// Unique name of the user, must be between 3 and 50 characters long.
+ pub username: String,
+ /// Password of the user, must be between 3 and 100 characters long.
+ #[serde(serialize_with = "crate::utils::serde_secret::serialize_secret")]
+ pub password: SecretString,
+ /// Status of the user, can be either `active` or `inactive`.
+ pub status: UserStatus,
+ /// Optional permissions of the user. If not provided, user will have no permissions.
+ pub permissions: Option<Permissions>,
+}
+
+impl Default for CreateUser {
+ fn default() -> Self {
+ CreateUser {
+ username: "user".to_string(),
+ password: SecretString::from("secret"),
+ status: UserStatus::Active,
+ permissions: None,
+ }
+ }
+}
+
+impl Validatable<IggyError> for CreateUser {
+ fn validate(&self) -> Result<(), IggyError> {
+ if self.username.is_empty()
+ || self.username.len() > MAX_USERNAME_LENGTH
+ || self.username.len() < MIN_USERNAME_LENGTH
+ {
+ return Err(IggyError::InvalidUsername);
+ }
+
+ let password = self.password.expose_secret();
+ if password.is_empty()
+ || password.len() > MAX_PASSWORD_LENGTH
+ || password.len() < MIN_PASSWORD_LENGTH
+ {
+ return Err(IggyError::InvalidPassword);
+ }
+
+ Ok(())
+ }
+}
diff --git a/core/common/src/commands/users/defaults.rs b/core/common/src/http/users/defaults.rs
similarity index 100%
rename from core/common/src/commands/users/defaults.rs
rename to core/common/src/http/users/defaults.rs
diff --git a/core/common/src/commands/streams/mod.rs b/core/common/src/http/users/delete_user.rs
similarity index 58%
copy from core/common/src/commands/streams/mod.rs
copy to core/common/src/http/users/delete_user.rs
index 429b4ed2d..cfe47f0cc 100644
--- a/core/common/src/commands/streams/mod.rs
+++ b/core/common/src/http/users/delete_user.rs
@@ -16,9 +16,23 @@
* under the License.
*/
-pub mod create_stream;
-pub mod delete_stream;
-pub mod purge_stream;
-pub mod update_stream;
+use crate::Identifier;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
-const MAX_NAME_LENGTH: usize = 255;
+/// `DeleteUser` command is used to delete a user by unique ID.
+/// It has additional payload:
+/// - `user_id` - unique user ID (numeric or name).
+#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
+pub struct DeleteUser {
+ /// Unique user ID (numeric or name).
+ #[serde(skip)]
+ pub user_id: Identifier,
+}
+
+impl Validatable<IggyError> for DeleteUser {
+ fn validate(&self) -> Result<(), IggyError> {
+ Ok(())
+ }
+}
diff --git a/core/common/src/commands/users/mod.rs b/core/common/src/http/users/mod.rs
similarity index 100%
rename from core/common/src/commands/users/mod.rs
rename to core/common/src/http/users/mod.rs
diff --git a/core/common/src/commands/streams/mod.rs b/core/common/src/http/users/update_permissions.rs
similarity index 50%
rename from core/common/src/commands/streams/mod.rs
rename to core/common/src/http/users/update_permissions.rs
index 429b4ed2d..c904d7994 100644
--- a/core/common/src/commands/streams/mod.rs
+++ b/core/common/src/http/users/update_permissions.rs
@@ -16,9 +16,27 @@
* under the License.
*/
-pub mod create_stream;
-pub mod delete_stream;
-pub mod purge_stream;
-pub mod update_stream;
+use crate::Identifier;
+use crate::Permissions;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
-const MAX_NAME_LENGTH: usize = 255;
+/// `UpdatePermissions` command is used to update a user's permissions.
+/// It has additional payload:
+/// - `user_id` - unique user ID (numeric or name).
+/// - `permissions` - new permissions (optional)
+#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
+pub struct UpdatePermissions {
+ /// Unique user ID (numeric or name).
+ #[serde(skip)]
+ pub user_id: Identifier,
+ /// New permissions if `None` is provided, then the existing user's permissions will be removed.
+ pub permissions: Option<Permissions>,
+}
+
+impl Validatable<IggyError> for UpdatePermissions {
+ fn validate(&self) -> Result<(), IggyError> {
+ Ok(())
+ }
+}
diff --git a/core/common/src/http/users/update_user.rs b/core/common/src/http/users/update_user.rs
new file mode 100644
index 000000000..ba213db2f
--- /dev/null
+++ b/core/common/src/http/users/update_user.rs
@@ -0,0 +1,55 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::defaults::*;
+use crate::Identifier;
+use crate::UserStatus;
+use crate::Validatable;
+use crate::error::IggyError;
+use serde::{Deserialize, Serialize};
+
+/// `UpdateUser` command is used to update a user's username and status.
+/// It has additional payload:
+/// - `user_id` - unique user ID (numeric or name).
+/// - `username` - new username (optional), if provided, must be between 3 and 50 characters long.
+/// - `status` - new status (optional)
+#[derive(Debug, Serialize, Deserialize, PartialEq, Default, Clone)]
+pub struct UpdateUser {
+ #[serde(skip)]
+ pub user_id: Identifier,
+ pub username: Option<String>,
+ pub status: Option<UserStatus>,
+}
+
+impl Validatable<IggyError> for UpdateUser {
+ fn validate(&self) -> Result<(), IggyError> {
+ if self.username.is_none() {
+ return Ok(());
+ }
+
+ let username = self.username.as_ref().unwrap();
+ if username.is_empty()
+ || username.len() > MAX_USERNAME_LENGTH
+ || username.len() < MIN_USERNAME_LENGTH
+ {
+ return Err(IggyError::InvalidUsername);
+ }
+
+ Ok(())
+ }
+}
diff --git a/core/common/src/lib.rs b/core/common/src/lib.rs
index 4a2f8a87f..6cdd1f821 100644
--- a/core/common/src/lib.rs
+++ b/core/common/src/lib.rs
@@ -19,9 +19,9 @@
mod alloc;
mod certificates;
-mod commands;
mod deduplication;
mod error;
+pub mod http;
mod macros;
mod sender;
pub mod sharding;
@@ -38,15 +38,15 @@ pub use alloc::buffer::PooledBuffer;
pub use alloc::memory_pool::{MEMORY_POOL, MemoryPool, MemoryPoolConfigOther, memory_pool};
pub use certificates::generate_self_signed_certificate;
pub use chrono::{DateTime, Duration as ChronoDuration, Utc};
-pub use commands::consumer_groups::*;
-pub use commands::messages::*;
-pub use commands::partitions::*;
-pub use commands::personal_access_tokens::*;
-pub use commands::segments::*;
-pub use commands::streams::*;
-pub use commands::topics::*;
-pub use commands::users::*;
pub use deduplication::MessageDeduplicator;
+pub use http::consumer_groups::*;
+pub use http::messages::*;
+pub use http::partitions::*;
+pub use http::personal_access_tokens::*;
+pub use http::segments::*;
+pub use http::streams::*;
+pub use http::topics::*;
+pub use http::users::*;
pub use sender::{
QuicSender, Sender, SenderKind, TcpSender, TcpTlsSender, WebSocketSender, WebSocketTlsSender,
};
@@ -72,7 +72,6 @@ pub use types::args::*;
pub use types::client::client_info::*;
pub use types::client_state::ClientState;
pub use types::cluster::*;
-pub use types::command::*;
pub use types::compression::compression_algorithm::*;
pub use types::configuration::auth_config::auto_login::*;
pub use types::configuration::auth_config::connection_string::*;
diff --git a/core/common/src/types/command/mod.rs b/core/common/src/types/command/mod.rs
index 2ba735b84..31bd66e6e 100644
--- a/core/common/src/types/command/mod.rs
+++ b/core/common/src/types/command/mod.rs
@@ -15,159 +15,3 @@
* specific language governing permissions and limitations
* under the License.
*/
-
-use crate::BytesSerializable;
-use crate::Validatable;
-use crate::error::IggyError;
-use std::fmt::Display;
-
-pub trait Command: BytesSerializable + Validatable<IggyError> + Send + Sync + Display {
- fn code(&self) -> u32;
-}
-
-pub const PING: &str = "ping";
-pub const PING_CODE: u32 = 1;
-pub const GET_STATS: &str = "stats";
-pub const GET_STATS_CODE: u32 = 10;
-pub const GET_SNAPSHOT_FILE: &str = "snapshot";
-pub const GET_SNAPSHOT_FILE_CODE: u32 = 11;
-pub const GET_CLUSTER_METADATA: &str = "cluster.metadata";
-pub const GET_CLUSTER_METADATA_CODE: u32 = 12;
-pub const GET_ME: &str = "me";
-pub const GET_ME_CODE: u32 = 20;
-pub const GET_CLIENT: &str = "client.get";
-pub const GET_CLIENT_CODE: u32 = 21;
-pub const GET_CLIENTS: &str = "client.list";
-pub const GET_CLIENTS_CODE: u32 = 22;
-pub const GET_USER: &str = "user.get";
-pub const GET_USER_CODE: u32 = 31;
-pub const GET_USERS: &str = "user.list";
-pub const GET_USERS_CODE: u32 = 32;
-pub const CREATE_USER: &str = "user.create";
-pub const CREATE_USER_CODE: u32 = 33;
-pub const DELETE_USER: &str = "user.delete";
-pub const DELETE_USER_CODE: u32 = 34;
-pub const UPDATE_USER: &str = "user.update";
-pub const UPDATE_USER_CODE: u32 = 35;
-pub const UPDATE_PERMISSIONS: &str = "user.permissions";
-pub const UPDATE_PERMISSIONS_CODE: u32 = 36;
-pub const CHANGE_PASSWORD: &str = "user.password";
-pub const CHANGE_PASSWORD_CODE: u32 = 37;
-pub const LOGIN_USER: &str = "user.login";
-pub const LOGIN_USER_CODE: u32 = 38;
-pub const LOGOUT_USER: &str = "user.logout";
-pub const LOGOUT_USER_CODE: u32 = 39;
-pub const GET_PERSONAL_ACCESS_TOKENS: &str = "personal_access_token.list";
-pub const GET_PERSONAL_ACCESS_TOKENS_CODE: u32 = 41;
-pub const CREATE_PERSONAL_ACCESS_TOKEN: &str = "personal_access_token.create";
-pub const CREATE_PERSONAL_ACCESS_TOKEN_CODE: u32 = 42;
-pub const DELETE_PERSONAL_ACCESS_TOKEN: &str = "personal_access_token.delete";
-pub const DELETE_PERSONAL_ACCESS_TOKEN_CODE: u32 = 43;
-pub const LOGIN_WITH_PERSONAL_ACCESS_TOKEN: &str = "personal_access_token.login";
-pub const LOGIN_WITH_PERSONAL_ACCESS_TOKEN_CODE: u32 = 44;
-pub const POLL_MESSAGES: &str = "message.poll";
-pub const POLL_MESSAGES_CODE: u32 = 100;
-pub const SEND_MESSAGES: &str = "message.send";
-pub const SEND_MESSAGES_CODE: u32 = 101;
-pub const FLUSH_UNSAVED_BUFFER: &str = "message.flush_unsaved_buffer";
-pub const FLUSH_UNSAVED_BUFFER_CODE: u32 = 102;
-pub const GET_CONSUMER_OFFSET: &str = "consumer_offset.get";
-pub const GET_CONSUMER_OFFSET_CODE: u32 = 120;
-pub const STORE_CONSUMER_OFFSET: &str = "consumer_offset.store";
-pub const STORE_CONSUMER_OFFSET_CODE: u32 = 121;
-pub const DELETE_CONSUMER_OFFSET: &str = "consumer_offset.delete";
-pub const DELETE_CONSUMER_OFFSET_CODE: u32 = 122;
-pub const GET_STREAM: &str = "stream.get";
-pub const GET_STREAM_CODE: u32 = 200;
-pub const GET_STREAMS: &str = "stream.list";
-pub const GET_STREAMS_CODE: u32 = 201;
-pub const CREATE_STREAM: &str = "stream.create";
-pub const CREATE_STREAM_CODE: u32 = 202;
-pub const DELETE_STREAM: &str = "stream.delete";
-pub const DELETE_STREAM_CODE: u32 = 203;
-pub const UPDATE_STREAM: &str = "stream.update";
-pub const UPDATE_STREAM_CODE: u32 = 204;
-pub const PURGE_STREAM: &str = "stream.purge";
-pub const PURGE_STREAM_CODE: u32 = 205;
-pub const GET_TOPIC: &str = "topic.get";
-pub const GET_TOPIC_CODE: u32 = 300;
-pub const GET_TOPICS: &str = "topic.list";
-pub const GET_TOPICS_CODE: u32 = 301;
-pub const CREATE_TOPIC: &str = "topic.create";
-pub const CREATE_TOPIC_CODE: u32 = 302;
-pub const DELETE_TOPIC: &str = "topic.delete";
-pub const DELETE_TOPIC_CODE: u32 = 303;
-pub const UPDATE_TOPIC: &str = "topic.update";
-pub const UPDATE_TOPIC_CODE: u32 = 304;
-pub const PURGE_TOPIC: &str = "topic.purge";
-pub const PURGE_TOPIC_CODE: u32 = 305;
-pub const CREATE_PARTITIONS: &str = "partition.create";
-pub const CREATE_PARTITIONS_CODE: u32 = 402;
-pub const DELETE_PARTITIONS: &str = "partition.delete";
-pub const DELETE_PARTITIONS_CODE: u32 = 403;
-pub const DELETE_SEGMENTS: &str = "segment.delete";
-pub const DELETE_SEGMENTS_CODE: u32 = 503;
-pub const GET_CONSUMER_GROUP: &str = "consumer_group.get";
-pub const GET_CONSUMER_GROUP_CODE: u32 = 600;
-pub const GET_CONSUMER_GROUPS: &str = "consumer_group.list";
-pub const GET_CONSUMER_GROUPS_CODE: u32 = 601;
-pub const CREATE_CONSUMER_GROUP: &str = "consumer_group.create";
-pub const CREATE_CONSUMER_GROUP_CODE: u32 = 602;
-pub const DELETE_CONSUMER_GROUP: &str = "consumer_group.delete";
-pub const DELETE_CONSUMER_GROUP_CODE: u32 = 603;
-pub const JOIN_CONSUMER_GROUP: &str = "consumer_group.join";
-pub const JOIN_CONSUMER_GROUP_CODE: u32 = 604;
-pub const LEAVE_CONSUMER_GROUP: &str = "consumer_group.leave";
-pub const LEAVE_CONSUMER_GROUP_CODE: u32 = 605;
-
-pub fn get_name_from_code(code: u32) -> Result<&'static str, IggyError> {
- match code {
- PING_CODE => Ok(PING),
- GET_STATS_CODE => Ok(GET_STATS),
- GET_ME_CODE => Ok(GET_ME),
- GET_CLIENT_CODE => Ok(GET_CLIENT),
- GET_CLIENTS_CODE => Ok(GET_CLIENTS),
- GET_USER_CODE => Ok(GET_USER),
- GET_USERS_CODE => Ok(GET_USERS),
- CREATE_USER_CODE => Ok(CREATE_USER),
- DELETE_USER_CODE => Ok(DELETE_USER),
- UPDATE_USER_CODE => Ok(UPDATE_USER),
- UPDATE_PERMISSIONS_CODE => Ok(UPDATE_PERMISSIONS),
- CHANGE_PASSWORD_CODE => Ok(CHANGE_PASSWORD),
- LOGIN_USER_CODE => Ok(LOGIN_USER),
- LOGOUT_USER_CODE => Ok(LOGOUT_USER),
- GET_PERSONAL_ACCESS_TOKENS_CODE => Ok(GET_PERSONAL_ACCESS_TOKENS),
- CREATE_PERSONAL_ACCESS_TOKEN_CODE => Ok(CREATE_PERSONAL_ACCESS_TOKEN),
- DELETE_PERSONAL_ACCESS_TOKEN_CODE => Ok(DELETE_PERSONAL_ACCESS_TOKEN),
- LOGIN_WITH_PERSONAL_ACCESS_TOKEN_CODE => Ok(LOGIN_WITH_PERSONAL_ACCESS_TOKEN),
- SEND_MESSAGES_CODE => Ok(SEND_MESSAGES),
- POLL_MESSAGES_CODE => Ok(POLL_MESSAGES),
- FLUSH_UNSAVED_BUFFER_CODE => Ok(FLUSH_UNSAVED_BUFFER),
- STORE_CONSUMER_OFFSET_CODE => Ok(STORE_CONSUMER_OFFSET),
- GET_CONSUMER_OFFSET_CODE => Ok(GET_CONSUMER_OFFSET),
- GET_STREAM_CODE => Ok(GET_STREAM),
- GET_STREAMS_CODE => Ok(GET_STREAMS),
- CREATE_STREAM_CODE => Ok(CREATE_STREAM),
- DELETE_STREAM_CODE => Ok(DELETE_STREAM),
- UPDATE_STREAM_CODE => Ok(UPDATE_STREAM),
- PURGE_STREAM_CODE => Ok(PURGE_STREAM),
- GET_TOPIC_CODE => Ok(GET_TOPIC),
- GET_TOPICS_CODE => Ok(GET_TOPICS),
- CREATE_TOPIC_CODE => Ok(CREATE_TOPIC),
- DELETE_TOPIC_CODE => Ok(DELETE_TOPIC),
- UPDATE_TOPIC_CODE => Ok(UPDATE_TOPIC),
- PURGE_TOPIC_CODE => Ok(PURGE_TOPIC),
- CREATE_PARTITIONS_CODE => Ok(CREATE_PARTITIONS),
- DELETE_PARTITIONS_CODE => Ok(DELETE_PARTITIONS),
- DELETE_SEGMENTS_CODE => Ok(DELETE_SEGMENTS),
- GET_CONSUMER_GROUP_CODE => Ok(GET_CONSUMER_GROUP),
- GET_CONSUMER_GROUPS_CODE => Ok(GET_CONSUMER_GROUPS),
- CREATE_CONSUMER_GROUP_CODE => Ok(CREATE_CONSUMER_GROUP),
- DELETE_CONSUMER_GROUP_CODE => Ok(DELETE_CONSUMER_GROUP),
- JOIN_CONSUMER_GROUP_CODE => Ok(JOIN_CONSUMER_GROUP),
- LEAVE_CONSUMER_GROUP_CODE => Ok(LEAVE_CONSUMER_GROUP),
- GET_SNAPSHOT_FILE_CODE => Ok(GET_SNAPSHOT_FILE),
- GET_CLUSTER_METADATA_CODE => Ok(GET_CLUSTER_METADATA),
- _ => Err(IggyError::InvalidCommand),
- }
-}
diff --git a/core/common/src/types/message/mod.rs b/core/common/src/types/message/mod.rs
index 5094c1e26..281cc3273 100644
--- a/core/common/src/types/message/mod.rs
+++ b/core/common/src/types/message/mod.rs
@@ -41,8 +41,8 @@ mod user_headers;
pub const INDEX_SIZE: usize = 16;
-pub use crate::commands::messages::poll_messages::PollMessages;
-pub use crate::commands::messages::send_messages::SendMessages;
+pub use crate::http::messages::poll_messages::PollMessages;
+pub use crate::http::messages::send_messages::SendMessages;
pub use iggy_message::{IggyMessage, MAX_PAYLOAD_SIZE, MAX_USER_HEADERS_SIZE};
pub use in_flight::IggyMessagesBatchSetInFlight;
pub use index::IggyIndex;
diff --git a/core/integration/tests/state/file.rs b/core/integration/tests/state/file.rs
index 838c8d4a6..944f9a0e1 100644
--- a/core/integration/tests/state/file.rs
+++ b/core/integration/tests/state/file.rs
@@ -19,9 +19,8 @@
use crate::state::StateSetup;
use bytes::Bytes;
use iggy::prelude::BytesSerializable;
-use iggy_common::create_stream::CreateStream;
-use iggy_common::create_user::CreateUser;
-use secrecy::SecretString;
+use iggy_binary_protocol::WireName;
+use iggy_binary_protocol::requests::{streams::CreateStreamRequest, users::CreateUserRequest};
use server::state::command::EntryCommand;
use server::state::entry::StateEntry;
use server::state::models::{CreateStreamWithId, CreateUserWithId};
@@ -44,10 +43,10 @@ async fn should_apply_single_entry() {
let user_id = 0;
let command = EntryCommand::CreateUser(CreateUserWithId {
user_id: 1,
- command: CreateUser {
- username: "test".to_string(),
- password: SecretString::from("secret"),
- status: Default::default(),
+ command: CreateUserRequest {
+ username: WireName::new("test").unwrap(),
+ password: "secret".to_string(),
+ status: 1,
permissions: None,
},
});
@@ -70,10 +69,10 @@ async fn should_apply_encrypted_entry() {
let user_id = 0;
let command = EntryCommand::CreateUser(CreateUserWithId {
user_id: 1,
- command: CreateUser {
- username: "test".to_string(),
- password: SecretString::from("secret"),
- status: Default::default(),
+ command: CreateUserRequest {
+ username: WireName::new("test").unwrap(),
+ password: "secret".to_string(),
+ status: 1,
permissions: None,
},
});
@@ -102,10 +101,10 @@ async fn should_apply_multiple_entries() {
let created_user_id = 1; // First created user
let create_user = EntryCommand::CreateUser(CreateUserWithId {
user_id: created_user_id,
- command: CreateUser {
- username: "test".to_string(),
- password: SecretString::from("secret"),
- status: Default::default(),
+ command: CreateUserRequest {
+ username: WireName::new("test").unwrap(),
+ password: "secret".to_string(),
+ status: 1,
permissions: None,
},
});
@@ -120,8 +119,8 @@ async fn should_apply_multiple_entries() {
let stream_id = 1;
let create_stream = EntryCommand::CreateStream(CreateStreamWithId {
stream_id,
- command: CreateStream {
- name: "test".to_string(),
+ command: CreateStreamRequest {
+ name: WireName::new("test").unwrap(),
},
});
let create_stream_bytes = create_stream.to_bytes();
diff --git a/core/integration/tests/state/system.rs b/core/integration/tests/state/system.rs
index ca567de41..0f992312f 100644
--- a/core/integration/tests/state/system.rs
+++ b/core/integration/tests/state/system.rs
@@ -17,15 +17,12 @@
*/
use crate::state::StateSetup;
-use iggy::prelude::IggyExpiry;
-use iggy_common::create_consumer_group::CreateConsumerGroup;
-use iggy_common::create_partitions::CreatePartitions;
-use iggy_common::create_personal_access_token::CreatePersonalAccessToken;
-use iggy_common::create_stream::CreateStream;
-use iggy_common::create_topic::CreateTopic;
-use iggy_common::create_user::CreateUser;
-use iggy_common::delete_stream::DeleteStream;
-use secrecy::{ExposeSecret, SecretString};
+use iggy_binary_protocol::requests::{
+ consumer_groups::CreateConsumerGroupRequest, partitions::CreatePartitionsRequest,
+ personal_access_tokens::CreatePersonalAccessTokenRequest, streams::CreateStreamRequest,
+ streams::DeleteStreamRequest, topics::CreateTopicRequest, users::CreateUserRequest,
+};
+use iggy_binary_protocol::{WireIdentifier, WireName};
use server::state::command::EntryCommand;
use server::state::models::{
CreateConsumerGroupWithId, CreatePersonalAccessTokenWithHash, CreateStreamWithId,
@@ -40,103 +37,70 @@ async fn should_be_initialized_based_on_state_entries() {
state.init().await.unwrap();
let user_id = 0;
- let create_user = CreateUser {
- username: "user".to_string(),
- password: SecretString::from("secret"),
- status: Default::default(),
- permissions: None,
- };
- let create_user_clone = CreateUser {
- username: "user".to_string(),
- password: SecretString::from("secret"),
- status: Default::default(),
+ let create_user = CreateUserRequest {
+ username: WireName::new("user").unwrap(),
+ password: "secret".to_string(),
+ status: 1, // Active
permissions: None,
};
- let stream1_id = 1;
- let create_stream1 = CreateStream {
- name: "stream1".to_string(),
- };
-
- let create_stream1_clone = CreateStream {
- name: "stream1".to_string(),
- };
-
- let topic1_id = 1;
- let create_topic1 = CreateTopic {
- stream_id: stream1_id.try_into().unwrap(),
- partitions_count: 1,
- compression_algorithm: Default::default(),
- message_expiry: Default::default(),
- max_topic_size: Default::default(),
- name: "topic1".to_string(),
- replication_factor: None,
+ let stream1_id = 1u32;
+ let create_stream1 = CreateStreamRequest {
+ name: WireName::new("stream1").unwrap(),
};
- let create_topic1_clone = CreateTopic {
- stream_id: stream1_id.try_into().unwrap(),
+ let topic1_id = 1u32;
+ let create_topic1 = CreateTopicRequest {
+ stream_id: WireIdentifier::numeric(stream1_id),
partitions_count: 1,
- compression_algorithm: Default::default(),
- message_expiry: Default::default(),
- max_topic_size: Default::default(),
- name: "topic1".to_string(),
- replication_factor: None,
+ compression_algorithm: 1, // None compression
+ message_expiry: 0, // NeverExpire
+ max_topic_size: 0, // ServerDefault
+ replication_factor: 0, // None
+ name: WireName::new("topic1").unwrap(),
};
- let stream2_id = 2;
- let create_stream2 = CreateStream {
- name: "stream2".to_string(),
+ let stream2_id = 2u32;
+ let create_stream2 = CreateStreamRequest {
+ name: WireName::new("stream2").unwrap(),
};
- let topic2_id = 2;
- let create_topic2 = CreateTopic {
- stream_id: stream2_id.try_into().unwrap(),
+ let topic2_id = 2u32;
+ let create_topic2 = CreateTopicRequest {
+ stream_id: WireIdentifier::numeric(stream2_id),
partitions_count: 1,
- compression_algorithm: Default::default(),
- message_expiry: Default::default(),
- max_topic_size: Default::default(),
- name: "topic2".to_string(),
- replication_factor: None,
+ compression_algorithm: 1,
+ message_expiry: 0,
+ max_topic_size: 0,
+ replication_factor: 0,
+ name: WireName::new("topic2").unwrap(),
};
- let create_partitions = CreatePartitions {
- stream_id: stream1_id.try_into().unwrap(),
- topic_id: topic1_id.try_into().unwrap(),
+ let create_partitions = CreatePartitionsRequest {
+ stream_id: WireIdentifier::numeric(stream1_id),
+ topic_id: WireIdentifier::numeric(topic1_id),
partitions_count: 2,
};
- let delete_stream = DeleteStream {
- stream_id: stream2_id.try_into().unwrap(),
+ let delete_stream = DeleteStreamRequest {
+ stream_id: WireIdentifier::numeric(stream2_id),
};
let create_personal_access_token = CreatePersonalAccessTokenWithHash {
- command: CreatePersonalAccessToken {
- name: "test".to_string(),
- expiry: IggyExpiry::NeverExpire,
+ command: CreatePersonalAccessTokenRequest {
+ name: WireName::new("test").unwrap(),
+ expiry: 0, // NeverExpire
},
hash: "hash".to_string(),
};
- let create_personal_access_token_clone = CreatePersonalAccessTokenWithHash {
- command: CreatePersonalAccessToken {
- name: "test".to_string(),
- expiry: IggyExpiry::NeverExpire,
- },
- hash: "hash".to_string(),
+ let create_consumer_group = CreateConsumerGroupRequest {
+ stream_id: WireIdentifier::numeric(stream1_id),
+ topic_id: WireIdentifier::numeric(topic1_id),
+ name: WireName::new("test").unwrap(),
};
- let group_id = 1;
- let create_consumer_group = CreateConsumerGroup {
- stream_id: stream1_id.try_into().unwrap(),
- topic_id: topic1_id.try_into().unwrap(),
- name: "test".to_string(),
- };
-
- let create_consumer_group_clone = CreateConsumerGroup {
- stream_id: stream1_id.try_into().unwrap(),
- topic_id: topic1_id.try_into().unwrap(),
- name: "test".to_string(),
- };
+ let group_id = 1u32;
state
.apply(
@@ -222,40 +186,28 @@ async fn should_be_initialized_based_on_state_entries() {
assert_eq!(system.users.len(), 1);
let mut user = system.users.remove(&user_id).unwrap();
assert_eq!(user.id, user_id);
- assert_eq!(user.username, create_user_clone.username);
- assert_eq!(
- user.password_hash,
- create_user_clone.password.expose_secret()
- );
+ assert_eq!(user.username, "user");
+ assert_eq!(user.password_hash, "secret");
assert_eq!(user.personal_access_tokens.len(), 1);
- let personal_access_token = user
- .personal_access_tokens
- .remove(&create_personal_access_token_clone.command.name)
- .unwrap();
- assert_eq!(
- personal_access_token.token_hash,
- create_personal_access_token_clone.hash
- );
- assert_eq!(
- personal_access_token.name,
- create_personal_access_token_clone.command.name
- );
+ let personal_access_token = user.personal_access_tokens.remove("test").unwrap();
+ assert_eq!(personal_access_token.token_hash, "hash");
+ assert_eq!(personal_access_token.name, "test");
assert_eq!(system.streams.len(), 1);
let mut stream = system.streams.remove(&stream1_id).unwrap();
assert_eq!(stream.id, stream1_id);
- assert_eq!(stream.name, create_stream1_clone.name);
+ assert_eq!(stream.name, "stream1");
assert_eq!(stream.topics.len(), 1);
let mut topic = stream.topics.remove(&topic1_id).unwrap();
assert_eq!(topic.id, topic1_id);
- assert_eq!(topic.name, create_topic1_clone.name);
+ assert_eq!(topic.name, "topic1");
assert_eq!(topic.partitions.len(), 3);
assert_eq!(topic.consumer_groups.len(), 1);
let consumer_group = topic.consumer_groups.remove(&group_id).unwrap();
assert_eq!(consumer_group.id, group_id);
- assert_eq!(consumer_group.name, create_consumer_group_clone.name);
+ assert_eq!(consumer_group.name, "test");
}
diff --git a/core/metadata/Cargo.toml b/core/metadata/Cargo.toml
index 97f7ae997..2618b6153 100644
--- a/core/metadata/Cargo.toml
+++ b/core/metadata/Cargo.toml
@@ -38,7 +38,6 @@ left-right = { workspace = true }
message_bus = { workspace = true }
paste = { workspace = true }
rmp-serde = { workspace = true }
-secrecy = { workspace = true }
serde = { workspace = true, features = ["derive"] }
slab = { workspace = true }
tracing = { workspace = true }
diff --git a/core/metadata/src/stm/consumer_group.rs b/core/metadata/src/stm/consumer_group.rs
index 2eddcdfaa..bd8ef96db 100644
--- a/core/metadata/src/stm/consumer_group.rs
+++ b/core/metadata/src/stm/consumer_group.rs
@@ -21,9 +21,10 @@ use crate::{collect_handlers, define_state, impl_fill_restore};
use bytes::Bytes;
use ahash::AHashMap;
-use iggy_common::create_consumer_group::CreateConsumerGroup;
-use iggy_common::delete_consumer_group::DeleteConsumerGroup;
-use iggy_common::{IdKind, Identifier};
+use iggy_binary_protocol::WireIdentifier;
+use iggy_binary_protocol::requests::consumer_groups::{
+ CreateConsumerGroupRequest, DeleteConsumerGroupRequest,
+};
use serde::{Deserialize, Serialize};
use slab::Slab;
use std::sync::Arc;
@@ -111,66 +112,50 @@ collect_handlers! {
}
impl ConsumerGroupsInner {
+ fn resolve_group_in_list(
+ &self,
+ groups_in_topic: &[usize],
+ group_id: &WireIdentifier,
+ ) -> Option<usize> {
+ match group_id {
+ WireIdentifier::Numeric(id) => {
+ let g_id = *id as usize;
+ groups_in_topic.contains(&g_id).then_some(g_id)
+ }
+ WireIdentifier::String(name) => groups_in_topic
+ .iter()
+ .find(|&&id| {
+ self.items
+ .get(id)
+ .is_some_and(|g| g.name.as_ref() == name.as_str())
+ })
+ .copied(),
+ }
+ }
+
fn resolve_consumer_group_id_by_identifiers(
&self,
- stream_id: &Identifier,
- topic_id: &Identifier,
- group_id: &Identifier,
+ stream_id: &WireIdentifier,
+ topic_id: &WireIdentifier,
+ group_id: &WireIdentifier,
) -> Option<usize> {
- if let (Ok(s), Ok(t)) = (stream_id.get_u32_value(), topic_id.get_u32_value()) {
- let groups_in_topic = self.topic_index.get(&(s as usize, t as usize))?;
-
- return match group_id.kind {
- IdKind::Numeric => {
- let g_id = group_id.get_u32_value().ok()? as usize;
- groups_in_topic.contains(&g_id).then_some(g_id)
- }
- IdKind::String => {
- let g_name = group_id.get_string_value().ok()?;
- groups_in_topic
- .iter()
- .find(|&&id| {
- self.items
- .get(id)
- .is_some_and(|g| g.name.as_ref() == g_name)
- })
- .copied()
- }
- };
+ if let (WireIdentifier::Numeric(s), WireIdentifier::Numeric(t)) = (stream_id, topic_id) {
+ let groups_in_topic = self.topic_index.get(&(*s as usize, *t as usize))?;
+ return self.resolve_group_in_list(groups_in_topic, group_id);
}
- if let (Ok(s), Ok(t)) = (stream_id.get_string_value(), topic_id.get_string_value()) {
+ if let (WireIdentifier::String(s), WireIdentifier::String(t)) = (stream_id, topic_id) {
let key = (Arc::from(s.as_str()), Arc::from(t.as_str()));
let groups_in_topic = self.topic_name_index.get(&key)?;
-
- return match group_id.kind {
- IdKind::Numeric => {
- let g_id = group_id.get_u32_value().ok()? as usize;
- groups_in_topic.contains(&g_id).then_some(g_id)
- }
- IdKind::String => {
- let g_name = group_id.get_string_value().ok()?;
- groups_in_topic
- .iter()
- .find(|&&id| {
- self.items
- .get(id)
- .is_some_and(|g| g.name.as_ref() == g_name)
- })
- .copied()
- }
- };
+ return self.resolve_group_in_list(groups_in_topic, group_id);
}
None
}
}
-// TODO: This is all a hack, we need to figure out how to do this in a way where `Identifier`
-// does not reach this stage of execution.
-
// TODO(hubcio): Serialize proper reply (e.g. assigned group ID) instead of empty Bytes.
-impl StateHandler for CreateConsumerGroup {
+impl StateHandler for CreateConsumerGroupRequest {
type State = ConsumerGroupsInner;
fn apply(&self, state: &mut ConsumerGroupsInner) -> Bytes {
let name: Arc<str> = Arc::from(self.name.as_str());
@@ -184,21 +169,19 @@ impl StateHandler for CreateConsumerGroup {
state.name_index.insert(name, id);
- if let (Ok(s), Ok(t)) = (
- self.stream_id.get_u32_value(),
- self.topic_id.get_u32_value(),
- ) {
+ if let (WireIdentifier::Numeric(s), WireIdentifier::Numeric(t)) =
+ (&self.stream_id, &self.topic_id)
+ {
state
.topic_index
- .entry((s as usize, t as usize))
+ .entry((*s as usize, *t as usize))
.or_default()
.push(id);
}
- if let (Ok(s), Ok(t)) = (
- self.stream_id.get_string_value(),
- self.topic_id.get_string_value(),
- ) {
+ if let (WireIdentifier::String(s), WireIdentifier::String(t)) =
+ (&self.stream_id, &self.topic_id)
+ {
let key = (Arc::from(s.as_str()), Arc::from(t.as_str()));
state.topic_name_index.entry(key).or_default().push(id);
}
@@ -206,7 +189,7 @@ impl StateHandler for CreateConsumerGroup {
}
}
-impl StateHandler for DeleteConsumerGroup {
+impl StateHandler for DeleteConsumerGroupRequest {
type State = ConsumerGroupsInner;
fn apply(&self, state: &mut ConsumerGroupsInner) -> Bytes {
let Some(id) = state.resolve_consumer_group_id_by_identifiers(
@@ -220,18 +203,16 @@ impl StateHandler for DeleteConsumerGroup {
let group = state.items.remove(id);
state.name_index.remove(&group.name);
- if let (Ok(s), Ok(t)) = (
- self.stream_id.get_u32_value(),
- self.topic_id.get_u32_value(),
- ) && let Some(vec) = state.topic_index.get_mut(&(s as usize, t as usize))
+ if let (WireIdentifier::Numeric(s), WireIdentifier::Numeric(t)) =
+ (&self.stream_id, &self.topic_id)
+ && let Some(vec) = state.topic_index.get_mut(&(*s as usize, *t as usize))
{
vec.retain(|&x| x != id);
}
- if let (Ok(s), Ok(t)) = (
- self.stream_id.get_string_value(),
- self.topic_id.get_string_value(),
- ) {
+ if let (WireIdentifier::String(s), WireIdentifier::String(t)) =
+ (&self.stream_id, &self.topic_id)
+ {
let key = (Arc::from(s.as_str()), Arc::from(t.as_str()));
if let Some(vec) = state.topic_name_index.get_mut(&key) {
vec.retain(|&x| x != id);
diff --git a/core/metadata/src/stm/mod.rs b/core/metadata/src/stm/mod.rs
index 0e2bb9b4b..e3d8611f4 100644
--- a/core/metadata/src/stm/mod.rs
+++ b/core/metadata/src/stm/mod.rs
@@ -223,7 +223,8 @@ macro_rules! define_state {
/// - `Absorb<{$state}Command>` impl for `{$state}Inner`
///
/// # Requirements
-/// Each listed operation type must implement `StateHandler<{$state}Inner>`.
+/// Each listed operation must have a corresponding `{Operation}Request` wire type
+/// that implements `WireDecode` and `StateHandler<State = {$state}Inner>`.
#[macro_export]
macro_rules! collect_handlers {
(
@@ -235,7 +236,7 @@ macro_rules! collect_handlers {
#[derive(Debug, Clone)]
pub enum [<$state Command>] {
$(
- $operation($operation),
+ $operation([<$operation Request>]),
)*
}
@@ -245,7 +246,7 @@ macro_rules! collect_handlers {
type Error = ::iggy_common::IggyError;
fn parse(input: Self::Input) -> Result<::iggy_common::Either<Self::Cmd, Self::Input>, Self::Error> {
- use ::iggy_common::BytesSerializable;
+ use ::iggy_binary_protocol::WireDecode;
use ::iggy_common::Either;
use ::iggy_binary_protocol::{Operation, PrepareHeader};
match input.header().operation {
@@ -256,7 +257,8 @@ macro_rules! collect_handlers {
let body = ::bytes::Bytes::copy_from_slice(
&input.as_slice()[core::mem::size_of::<PrepareHeader>()..header.size as usize]
);
- let cmd = $operation::from_bytes(body)?;
+ let cmd = [<$operation Request>]::decode_from(&body)
+ .map_err(|_| ::iggy_common::IggyError::InvalidCommand)?;
Ok(Either::Left([<$state Command>]::$operation(cmd)))
},
)*
diff --git a/core/metadata/src/stm/stream.rs b/core/metadata/src/stm/stream.rs
index df610a6a1..dfb7e9e77 100644
--- a/core/metadata/src/stm/stream.rs
+++ b/core/metadata/src/stm/stream.rs
@@ -21,16 +21,16 @@ use crate::stm::snapshot::Snapshotable;
use crate::{collect_handlers, define_state, impl_fill_restore};
use ahash::AHashMap;
use bytes::Bytes;
-use iggy_common::create_partitions::CreatePartitions;
-use iggy_common::create_stream::CreateStream;
-use iggy_common::create_topic::CreateTopic;
-use iggy_common::delete_partitions::DeletePartitions;
-use iggy_common::delete_stream::DeleteStream;
-use iggy_common::delete_topic::DeleteTopic;
-use iggy_common::purge_stream::PurgeStream;
-use iggy_common::purge_topic::PurgeTopic;
-use iggy_common::update_stream::UpdateStream;
-use iggy_common::update_topic::UpdateTopic;
+use iggy_binary_protocol::WireIdentifier;
+use iggy_binary_protocol::requests::partitions::{
+ CreatePartitionsRequest, DeletePartitionsRequest,
+};
+use iggy_binary_protocol::requests::streams::{
+ CreateStreamRequest, DeleteStreamRequest, PurgeStreamRequest, UpdateStreamRequest,
+};
+use iggy_binary_protocol::requests::topics::{
+ CreateTopicRequest, DeleteTopicRequest, PurgeTopicRequest, UpdateTopicRequest,
+};
use iggy_common::{CompressionAlgorithm, IggyExpiry, IggyTimestamp, MaxTopicSize};
use serde::{Deserialize, Serialize};
use slab::Slab;
@@ -233,51 +233,38 @@ collect_handlers! {
}
impl StreamsInner {
- fn resolve_stream_id(&self, identifier: &iggy_common::Identifier) -> Option<usize> {
- use iggy_common::IdKind;
- match identifier.kind {
- IdKind::Numeric => {
- let id = identifier.get_u32_value().ok()? as usize;
+ fn resolve_stream_id(&self, identifier: &WireIdentifier) -> Option<usize> {
+ match identifier {
+ WireIdentifier::Numeric(id) => {
+ let id = *id as usize;
if self.items.contains(id) {
Some(id)
} else {
None
}
}
- IdKind::String => {
- let name = identifier.get_string_value().ok()?;
- self.index.get(name.as_str()).copied()
- }
+ WireIdentifier::String(name) => self.index.get(name.as_str()).copied(),
}
}
- fn resolve_topic_id(
- &self,
- stream_id: usize,
- identifier: &iggy_common::Identifier,
- ) -> Option<usize> {
- use iggy_common::IdKind;
+ fn resolve_topic_id(&self, stream_id: usize, identifier: &WireIdentifier) -> Option<usize> {
let stream = self.items.get(stream_id)?;
-
- match identifier.kind {
- IdKind::Numeric => {
- let id = identifier.get_u32_value().ok()? as usize;
+ match identifier {
+ WireIdentifier::Numeric(id) => {
+ let id = *id as usize;
if stream.topics.contains(id) {
Some(id)
} else {
None
}
}
- IdKind::String => {
- let name = identifier.get_string_value().ok()?;
- stream.topic_index.get(name.as_str()).copied()
- }
+ WireIdentifier::String(name) => stream.topic_index.get(name.as_str()).copied(),
}
}
}
// TODO(hubcio): Serialize proper reply (e.g. assigned stream ID) instead of empty Bytes.
-impl StateHandler for CreateStream {
+impl StateHandler for CreateStreamRequest {
type State = StreamsInner;
fn apply(&self, state: &mut StreamsInner) -> Bytes {
let name_arc: Arc<str> = Arc::from(self.name.as_str());
@@ -288,7 +275,7 @@ impl StateHandler for CreateStream {
let stream = Stream {
id: 0,
name: name_arc.clone(),
- created_at: iggy_common::IggyTimestamp::now(),
+ created_at: IggyTimestamp::now(),
stats: Arc::new(StreamStats::default()),
topics: Slab::new(),
topic_index: AHashMap::default(),
@@ -303,7 +290,7 @@ impl StateHandler for CreateStream {
}
}
-impl StateHandler for UpdateStream {
+impl StateHandler for UpdateStreamRequest {
type State = StreamsInner;
fn apply(&self, state: &mut StreamsInner) -> Bytes {
let Some(stream_id) = state.resolve_stream_id(&self.stream_id) else {
@@ -327,7 +314,7 @@ impl StateHandler for UpdateStream {
}
}
-impl StateHandler for DeleteStream {
+impl StateHandler for DeleteStreamRequest {
type State = StreamsInner;
fn apply(&self, state: &mut StreamsInner) -> Bytes {
let Some(stream_id) = state.resolve_stream_id(&self.stream_id) else {
@@ -344,7 +331,7 @@ impl StateHandler for DeleteStream {
}
}
-impl StateHandler for PurgeStream {
+impl StateHandler for PurgeStreamRequest {
type State = StreamsInner;
fn apply(&self, _state: &mut StreamsInner) -> Bytes {
// TODO
@@ -353,7 +340,7 @@ impl StateHandler for PurgeStream {
}
// TODO(hubcio): Serialize proper reply (e.g. assigned topic ID) instead of empty Bytes.
-impl StateHandler for CreateTopic {
+impl StateHandler for CreateTopicRequest {
type State = StreamsInner;
fn apply(&self, state: &mut StreamsInner) -> Bytes {
let Some(stream_id) = state.resolve_stream_id(&self.stream_id) else {
@@ -368,14 +355,21 @@ impl StateHandler for CreateTopic {
return Bytes::new();
}
+ let replication_factor = if self.replication_factor == 0 {
+ 1
+ } else {
+ self.replication_factor
+ };
+
let topic = Topic {
id: 0,
name: name_arc.clone(),
- created_at: iggy_common::IggyTimestamp::now(),
- replication_factor: self.replication_factor.unwrap_or(1),
- message_expiry: self.message_expiry,
- compression_algorithm: self.compression_algorithm,
- max_topic_size: self.max_topic_size,
+ created_at: IggyTimestamp::now(),
+ replication_factor,
+ message_expiry: IggyExpiry::from(self.message_expiry),
+ compression_algorithm: CompressionAlgorithm::from_code(self.compression_algorithm)
+ .unwrap_or_default(),
+ max_topic_size: MaxTopicSize::from(self.max_topic_size),
stats: Arc::new(TopicStats::new(stream.stats.clone())),
partitions: Vec::new(),
round_robin_counter: Arc::new(AtomicUsize::new(0)),
@@ -388,7 +382,7 @@ impl StateHandler for CreateTopic {
for partition_id in 0..self.partitions_count as usize {
let partition = Partition {
id: partition_id,
- created_at: iggy_common::IggyTimestamp::now(),
+ created_at: IggyTimestamp::now(),
};
topic.partitions.push(partition);
}
@@ -399,7 +393,7 @@ impl StateHandler for CreateTopic {
}
}
-impl StateHandler for UpdateTopic {
+impl StateHandler for UpdateTopicRequest {
type State = StreamsInner;
fn apply(&self, state: &mut StreamsInner) -> Bytes {
let Some(stream_id) = state.resolve_stream_id(&self.stream_id) else {
@@ -425,18 +419,19 @@ impl StateHandler for UpdateTopic {
stream.topic_index.remove(&topic.name);
topic.name = new_name_arc.clone();
- topic.compression_algorithm = self.compression_algorithm;
- topic.message_expiry = self.message_expiry;
- topic.max_topic_size = self.max_topic_size;
- if let Some(rf) = self.replication_factor {
- topic.replication_factor = rf;
+ topic.compression_algorithm =
+ CompressionAlgorithm::from_code(self.compression_algorithm).unwrap_or_default();
+ topic.message_expiry = IggyExpiry::from(self.message_expiry);
+ topic.max_topic_size = MaxTopicSize::from(self.max_topic_size);
+ if self.replication_factor != 0 {
+ topic.replication_factor = self.replication_factor;
}
stream.topic_index.insert(new_name_arc, topic_id);
Bytes::new()
}
}
-impl StateHandler for DeleteTopic {
+impl StateHandler for DeleteTopicRequest {
type State = StreamsInner;
fn apply(&self, state: &mut StreamsInner) -> Bytes {
let Some(stream_id) = state.resolve_stream_id(&self.stream_id) else {
@@ -458,7 +453,7 @@ impl StateHandler for DeleteTopic {
}
}
-impl StateHandler for PurgeTopic {
+impl StateHandler for PurgeTopicRequest {
type State = StreamsInner;
fn apply(&self, _state: &mut StreamsInner) -> Bytes {
// TODO
@@ -467,7 +462,7 @@ impl StateHandler for PurgeTopic {
}
// TODO(hubcio): Serialize proper reply (e.g. assigned partition IDs) instead of empty Bytes.
-impl StateHandler for CreatePartitions {
+impl StateHandler for CreatePartitionsRequest {
type State = StreamsInner;
fn apply(&self, state: &mut StreamsInner) -> Bytes {
let Some(stream_id) = state.resolve_stream_id(&self.stream_id) else {
@@ -489,7 +484,7 @@ impl StateHandler for CreatePartitions {
let partition_id = current_partition_count + i;
let partition = Partition {
id: partition_id,
- created_at: iggy_common::IggyTimestamp::now(),
+ created_at: IggyTimestamp::now(),
};
topic.partitions.push(partition);
}
@@ -497,7 +492,7 @@ impl StateHandler for CreatePartitions {
}
}
-impl StateHandler for DeletePartitions {
+impl StateHandler for DeletePartitionsRequest {
type State = StreamsInner;
fn apply(&self, state: &mut StreamsInner) -> Bytes {
let Some(stream_id) = state.resolve_stream_id(&self.stream_id) else {
diff --git a/core/metadata/src/stm/user.rs b/core/metadata/src/stm/user.rs
index 5ebf2ee5c..adde8a848 100644
--- a/core/metadata/src/stm/user.rs
+++ b/core/metadata/src/stm/user.rs
@@ -21,18 +21,18 @@ use crate::stm::snapshot::Snapshotable;
use crate::{collect_handlers, define_state, impl_fill_restore};
use ahash::AHashMap;
use bytes::Bytes;
-use iggy_common::change_password::ChangePassword;
-use iggy_common::create_personal_access_token::CreatePersonalAccessToken;
-use iggy_common::create_user::CreateUser;
-use iggy_common::delete_personal_access_token::DeletePersonalAccessToken;
-use iggy_common::delete_user::DeleteUser;
-use iggy_common::update_permissions::UpdatePermissions;
-use iggy_common::update_user::UpdateUser;
+use iggy_binary_protocol::WireIdentifier;
+use iggy_binary_protocol::requests::personal_access_tokens::{
+ CreatePersonalAccessTokenRequest, DeletePersonalAccessTokenRequest,
+};
+use iggy_binary_protocol::requests::users::{
+ ChangePasswordRequest, CreateUserRequest, DeleteUserRequest, UpdatePermissionsRequest,
+ UpdateUserRequest,
+};
use iggy_common::{
- GlobalPermissions, IggyTimestamp, Permissions, PersonalAccessToken, StreamPermissions, UserId,
- UserStatus,
+ GlobalPermissions, IggyExpiry, IggyTimestamp, Permissions, PersonalAccessToken,
+ StreamPermissions, UserId, UserStatus,
};
-use secrecy::ExposeSecret;
use serde::{Deserialize, Serialize};
use slab::Slab;
use std::sync::Arc;
@@ -106,27 +106,23 @@ collect_handlers! {
}
impl UsersInner {
- fn resolve_user_id(&self, identifier: &iggy_common::Identifier) -> Option<usize> {
- use iggy_common::IdKind;
- match identifier.kind {
- IdKind::Numeric => {
- let id = identifier.get_u32_value().ok()? as usize;
+ fn resolve_user_id(&self, identifier: &WireIdentifier) -> Option<usize> {
+ match identifier {
+ WireIdentifier::Numeric(id) => {
+ let id = *id as usize;
if self.items.contains(id) {
Some(id)
} else {
None
}
}
- IdKind::String => {
- let username = identifier.get_string_value().ok()?;
- self.index.get(username.as_str()).map(|&id| id as usize)
- }
+ WireIdentifier::String(name) => self.index.get(name.as_str()).map(|&id| id as usize),
}
}
}
// TODO(hubcio): Serialize proper reply (e.g. assigned user ID) instead of empty Bytes.
-impl StateHandler for CreateUser {
+impl StateHandler for CreateUserRequest {
type State = UsersInner;
#[allow(clippy::cast_possible_truncation)]
fn apply(&self, state: &mut UsersInner) -> Bytes {
@@ -135,13 +131,19 @@ impl StateHandler for CreateUser {
return Bytes::new();
}
+ let status = UserStatus::from_code(self.status).unwrap_or_default();
+ let permissions = self
+ .permissions
+ .as_ref()
+ .map(|p| Arc::new(Permissions::from(p.clone())));
+
let user = User {
id: 0,
username: username_arc.clone(),
- password_hash: Arc::from(self.password.expose_secret()),
- status: self.status,
- created_at: iggy_common::IggyTimestamp::now(),
- permissions: self.permissions.as_ref().map(|p| Arc::new(p.clone())),
+ password_hash: Arc::from(self.password.as_str()),
+ status,
+ created_at: IggyTimestamp::now(),
+ permissions,
};
let id = state.items.insert(user);
@@ -157,7 +159,7 @@ impl StateHandler for CreateUser {
}
}
-impl StateHandler for UpdateUser {
+impl StateHandler for UpdateUserRequest {
type State = UsersInner;
#[allow(clippy::cast_possible_truncation)]
fn apply(&self, state: &mut UsersInner) -> Bytes {
@@ -182,14 +184,16 @@ impl StateHandler for UpdateUser {
state.index.insert(new_username_arc, user_id as UserId);
}
- if let Some(new_status) = self.status {
+ if let Some(status_code) = self.status
+ && let Ok(new_status) = UserStatus::from_code(status_code)
+ {
user.status = new_status;
}
Bytes::new()
}
}
-impl StateHandler for DeleteUser {
+impl StateHandler for DeleteUserRequest {
type State = UsersInner;
#[allow(clippy::cast_possible_truncation)]
fn apply(&self, state: &mut UsersInner) -> Bytes {
@@ -207,7 +211,7 @@ impl StateHandler for DeleteUser {
}
}
-impl StateHandler for ChangePassword {
+impl StateHandler for ChangePasswordRequest {
type State = UsersInner;
fn apply(&self, state: &mut UsersInner) -> Bytes {
let Some(user_id) = state.resolve_user_id(&self.user_id) else {
@@ -215,13 +219,13 @@ impl StateHandler for ChangePassword {
};
if let Some(user) = state.items.get_mut(user_id) {
- user.password_hash = Arc::from(self.new_password.expose_secret());
+ user.password_hash = Arc::from(self.new_password.as_str());
}
Bytes::new()
}
}
-impl StateHandler for UpdatePermissions {
+impl StateHandler for UpdatePermissionsRequest {
type State = UsersInner;
fn apply(&self, state: &mut UsersInner) -> Bytes {
let Some(user_id) = state.resolve_user_id(&self.user_id) else {
@@ -229,43 +233,43 @@ impl StateHandler for UpdatePermissions {
};
if let Some(user) = state.items.get_mut(user_id) {
- user.permissions = self.permissions.as_ref().map(|p| Arc::new(p.clone()));
+ user.permissions = self
+ .permissions
+ .as_ref()
+ .map(|p| Arc::new(Permissions::from(p.clone())));
}
Bytes::new()
}
}
// TODO(hubcio): Serialize proper reply (e.g. generated token) instead of empty Bytes.
-impl StateHandler for CreatePersonalAccessToken {
+impl StateHandler for CreatePersonalAccessTokenRequest {
type State = UsersInner;
fn apply(&self, state: &mut UsersInner) -> Bytes {
// TODO: Stub until protocol gets adjusted.
let user_id = 0;
+ let expiry = IggyExpiry::from(self.expiry);
let user_tokens = state.personal_access_tokens.entry(user_id).or_default();
let name_arc: Arc<str> = Arc::from(self.name.as_str());
if user_tokens.contains_key(&name_arc) {
return Bytes::new();
}
- let expiry_at = PersonalAccessToken::calculate_expiry_at(IggyTimestamp::now(), self.expiry);
+ let expiry_at = PersonalAccessToken::calculate_expiry_at(IggyTimestamp::now(), expiry);
if let Some(expiry_at) = expiry_at
&& expiry_at.as_micros() <= IggyTimestamp::now().as_micros()
{
return Bytes::new();
}
- let (pat, _) = PersonalAccessToken::new(
- user_id,
- self.name.as_ref(),
- IggyTimestamp::now(),
- self.expiry,
- );
+ let (pat, _) =
+ PersonalAccessToken::new(user_id, self.name.as_ref(), IggyTimestamp::now(), expiry);
user_tokens.insert(name_arc, pat);
Bytes::new()
}
}
-impl StateHandler for DeletePersonalAccessToken {
+impl StateHandler for DeletePersonalAccessTokenRequest {
type State = UsersInner;
fn apply(&self, state: &mut UsersInner) -> Bytes {
// TODO: Stub until protocol gets adjusted.
diff --git a/core/server/src/http/segments.rs b/core/server/src/http/segments.rs
index dcc4551eb..b2b8f9b52 100644
--- a/core/server/src/http/segments.rs
+++ b/core/server/src/http/segments.rs
@@ -16,6 +16,7 @@
* under the License.
*/
+use crate::binary::dispatch::identifier_to_wire_id;
use crate::http::COMPONENT;
use crate::http::error::CustomError;
use crate::http::jwt::json_web_token::Identity;
@@ -27,6 +28,7 @@ use axum::http::StatusCode;
use axum::routing::delete;
use axum::{Extension, Router, debug_handler};
use err_trail::ErrContext;
+use iggy_binary_protocol::requests::segments::DeleteSegmentsRequest;
use iggy_common::Identifier;
use iggy_common::Validatable;
use iggy_common::delete_segments::DeleteSegments;
@@ -96,13 +98,13 @@ async fn delete_segments(
_ => unreachable!("Expected DeleteSegments"),
}
- let command = DeleteSegments {
- stream_id: query.stream_id.clone(),
- topic_id: query.topic_id.clone(),
+ let wire_command = DeleteSegmentsRequest {
+ stream_id: identifier_to_wire_id(&query.stream_id)?,
+ topic_id: identifier_to_wire_id(&query.topic_id)?,
partition_id: query.partition_id,
segments_count,
};
- let entry_command = crate::state::command::EntryCommand::DeleteSegments(command);
+ let entry_command = crate::state::command::EntryCommand::DeleteSegments(wire_command);
let state_future = SendWrapper::new(
state
.shard
diff --git a/core/server/src/quic/listener.rs b/core/server/src/quic/listener.rs
index a39abae56..91287f198 100644
--- a/core/server/src/quic/listener.rs
+++ b/core/server/src/quic/listener.rs
@@ -26,8 +26,8 @@ use compio::io::AsyncReadExt;
use compio::quic::{Connection, Endpoint, RecvStream, SendStream};
use futures::FutureExt;
use iggy_binary_protocol::RequestFrame;
-use iggy_binary_protocol::codes::{SEND_MESSAGES_CODE, command_name};
-use iggy_common::{GET_CLUSTER_METADATA_CODE, IggyError, SenderKind, TransportProtocol};
+use iggy_binary_protocol::codes::{GET_CLUSTER_METADATA_CODE, SEND_MESSAGES_CODE, command_name};
+use iggy_common::{IggyError, SenderKind, TransportProtocol};
use std::rc::Rc;
use tracing::{debug, error, info, trace, warn};
diff --git a/core/server/src/shard/execution.rs b/core/server/src/shard/execution.rs
index ea2d90862..26c73cfc2 100644
--- a/core/server/src/shard/execution.rs
+++ b/core/server/src/shard/execution.rs
@@ -41,14 +41,7 @@ use iggy_binary_protocol::requests::{
};
use iggy_common::{
CompressionAlgorithm, Identifier, IggyError, IggyExpiry, MaxTopicSize, PersonalAccessToken,
- UserStatus, change_password::ChangePassword, create_consumer_group::CreateConsumerGroup,
- create_partitions::CreatePartitions, create_personal_access_token::CreatePersonalAccessToken,
- create_stream::CreateStream, create_topic::CreateTopic, create_user::CreateUser,
- delete_consumer_group::DeleteConsumerGroup, delete_partitions::DeletePartitions,
- delete_personal_access_token::DeletePersonalAccessToken, delete_stream::DeleteStream,
- delete_topic::DeleteTopic, delete_user::DeleteUser, purge_stream::PurgeStream,
- purge_topic::PurgeTopic, update_permissions::UpdatePermissions, update_stream::UpdateStream,
- update_topic::UpdateTopic, update_user::UpdateUser,
+ UserStatus,
};
use secrecy::{ExposeSecret, SecretString};
@@ -59,12 +52,8 @@ pub async fn execute_create_stream(
) -> Result<StreamResponseData, IggyError> {
shard.metadata.perm_create_stream(user_id)?;
- let command = CreateStream {
- name: wire.name.to_string(),
- };
- let stream_id = shard.create_stream(command.name.clone()).await?;
+ let stream_id = shard.create_stream(wire.name.to_string()).await?;
- // Capture response data from metadata before state apply
let response_data = shard.metadata.with_metadata(|m| {
let stream = m
.streams
@@ -83,7 +72,7 @@ pub async fn execute_create_stream(
user_id,
&EntryCommand::CreateStream(CreateStreamWithId {
stream_id: stream_id as u32,
- command,
+ command: wire,
}),
)
.await?;
@@ -96,18 +85,15 @@ pub async fn execute_update_stream(
user_id: u32,
wire: UpdateStreamRequest,
) -> Result<(), IggyError> {
- let command = UpdateStream {
- stream_id: wire_id_to_identifier(&wire.stream_id)?,
- name: wire.name.to_string(),
- };
- let stream = shard.resolve_stream(&command.stream_id)?;
+ let stream_id = wire_id_to_identifier(&wire.stream_id)?;
+ let stream = shard.resolve_stream(&stream_id)?;
shard.metadata.perm_update_stream(user_id, stream.id())?;
- shard.update_stream(stream, command.name.clone())?;
+ shard.update_stream(stream, wire.name.to_string())?;
shard
.state
- .apply(user_id, &EntryCommand::UpdateStream(command))
+ .apply(user_id, &EntryCommand::UpdateStream(wire))
.await?;
Ok(())
@@ -118,10 +104,8 @@ pub async fn execute_delete_stream(
user_id: u32,
wire: DeleteStreamRequest,
) -> Result<(), IggyError> {
- let command = DeleteStream {
- stream_id: wire_id_to_identifier(&wire.stream_id)?,
- };
- let stream = shard.resolve_stream(&command.stream_id)?;
+ let stream_id = wire_id_to_identifier(&wire.stream_id)?;
+ let stream = shard.resolve_stream(&stream_id)?;
shard.metadata.perm_delete_stream(user_id, stream.id())?;
// Capture all topic/partition info BEFORE deletion for broadcast
@@ -139,7 +123,7 @@ pub async fn execute_delete_stream(
shard
.state
- .apply(user_id, &EntryCommand::DeleteStream(command))
+ .apply(user_id, &EntryCommand::DeleteStream(wire))
.await?;
// Broadcast DeletedPartitions to all shards for each topic's partitions (best-effort)
@@ -168,10 +152,8 @@ pub async fn execute_purge_stream(
user_id: u32,
wire: PurgeStreamRequest,
) -> Result<(), IggyError> {
- let command = PurgeStream {
- stream_id: wire_id_to_identifier(&wire.stream_id)?,
- };
- let stream = shard.resolve_stream(&command.stream_id)?;
+ let stream_id = wire_id_to_identifier(&wire.stream_id)?;
+ let stream = shard.resolve_stream(&stream_id)?;
shard.metadata.perm_purge_stream(user_id, stream.id())?;
shard.purge_stream(stream).await?;
@@ -179,7 +161,7 @@ pub async fn execute_purge_stream(
shard
.state
- .apply(user_id, &EntryCommand::PurgeStream(command))
+ .apply(user_id, &EntryCommand::PurgeStream(wire))
.await?;
let event = ShardEvent::PurgedStream {
@@ -198,30 +180,27 @@ pub async fn execute_create_topic(
user_id: u32,
wire: CreateTopicRequest,
) -> Result<TopicResponseData, IggyError> {
- let command = CreateTopic {
- stream_id: wire_id_to_identifier(&wire.stream_id)?,
- partitions_count: wire.partitions_count,
- compression_algorithm: CompressionAlgorithm::from_code(wire.compression_algorithm)?,
- message_expiry: IggyExpiry::from(wire.message_expiry),
- max_topic_size: MaxTopicSize::from(wire.max_topic_size),
- replication_factor: if wire.replication_factor == 0 {
- None
- } else {
- Some(wire.replication_factor)
- },
- name: wire.name.to_string(),
+ let stream_id = wire_id_to_identifier(&wire.stream_id)?;
+ let compression = CompressionAlgorithm::from_code(wire.compression_algorithm)?;
+ let message_expiry = IggyExpiry::from(wire.message_expiry);
+ let max_topic_size = MaxTopicSize::from(wire.max_topic_size);
+ let replication_factor = if wire.replication_factor == 0 {
+ None
+ } else {
+ Some(wire.replication_factor)
};
- let stream = shard.resolve_stream(&command.stream_id)?;
+
+ let stream = shard.resolve_stream(&stream_id)?;
shard.metadata.perm_create_topic(user_id, stream.id())?;
let topic_id = shard
.create_topic(
stream,
- command.name.clone(),
- command.message_expiry,
- command.compression_algorithm,
- command.max_topic_size,
- command.replication_factor,
+ wire.name.to_string(),
+ message_expiry,
+ compression,
+ max_topic_size,
+ replication_factor,
)
.await?;
@@ -230,7 +209,7 @@ pub async fn execute_create_topic(
topic_id,
};
let partition_infos = shard
- .create_partitions(resolved_topic, command.partitions_count)
+ .create_partitions(resolved_topic, wire.partitions_count)
.await?;
let response_data = shard.metadata.with_metadata(|m| {
@@ -257,7 +236,7 @@ pub async fn execute_create_topic(
user_id,
&EntryCommand::CreateTopic(CreateTopicWithId {
topic_id: topic_id as u32,
- command,
+ command: wire,
}),
)
.await?;
@@ -280,36 +259,34 @@ pub async fn execute_update_topic(
user_id: u32,
wire: UpdateTopicRequest,
) -> Result<(), IggyError> {
- let command = UpdateTopic {
- stream_id: wire_id_to_identifier(&wire.stream_id)?,
- topic_id: wire_id_to_identifier(&wire.topic_id)?,
- compression_algorithm: CompressionAlgorithm::from_code(wire.compression_algorithm)?,
- message_expiry: IggyExpiry::from(wire.message_expiry),
- max_topic_size: MaxTopicSize::from(wire.max_topic_size),
- replication_factor: if wire.replication_factor == 0 {
- None
- } else {
- Some(wire.replication_factor)
- },
- name: wire.name.to_string(),
+ let stream_id = wire_id_to_identifier(&wire.stream_id)?;
+ let topic_id = wire_id_to_identifier(&wire.topic_id)?;
+ let compression = CompressionAlgorithm::from_code(wire.compression_algorithm)?;
+ let message_expiry = IggyExpiry::from(wire.message_expiry);
+ let max_topic_size = MaxTopicSize::from(wire.max_topic_size);
+ let replication_factor = if wire.replication_factor == 0 {
+ None
+ } else {
+ Some(wire.replication_factor)
};
- let topic = shard.resolve_topic(&command.stream_id, &command.topic_id)?;
+
+ let topic = shard.resolve_topic(&stream_id, &topic_id)?;
shard
.metadata
.perm_update_topic(user_id, topic.stream_id, topic.topic_id)?;
shard.update_topic(
topic,
- command.name.clone(),
- command.message_expiry,
- command.compression_algorithm,
- command.max_topic_size,
- command.replication_factor,
+ wire.name.to_string(),
+ message_expiry,
+ compression,
+ max_topic_size,
+ replication_factor,
)?;
shard
.state
- .apply(user_id, &EntryCommand::UpdateTopic(command))
+ .apply(user_id, &EntryCommand::UpdateTopic(wire))
.await?;
Ok(())
@@ -320,11 +297,9 @@ pub async fn execute_delete_topic(
user_id: u32,
wire: DeleteTopicRequest,
) -> Result<(), IggyError> {
- let command = DeleteTopic {
- stream_id: wire_id_to_identifier(&wire.stream_id)?,
- topic_id: wire_id_to_identifier(&wire.topic_id)?,
- };
- let topic = shard.resolve_topic(&command.stream_id, &command.topic_id)?;
+ let stream_id = wire_id_to_identifier(&wire.stream_id)?;
+ let topic_id = wire_id_to_identifier(&wire.topic_id)?;
+ let topic = shard.resolve_topic(&stream_id, &topic_id)?;
shard
.metadata
.perm_delete_topic(user_id, topic.stream_id, topic.topic_id)?;
@@ -338,7 +313,7 @@ pub async fn execute_delete_topic(
shard
.state
- .apply(user_id, &EntryCommand::DeleteTopic(command))
+ .apply(user_id, &EntryCommand::DeleteTopic(wire))
.await?;
// Broadcast to all shards to clean up their local_partitions entries (best-effort)
@@ -362,11 +337,9 @@ pub async fn execute_purge_topic(
user_id: u32,
wire: PurgeTopicRequest,
) -> Result<(), IggyError> {
- let command = PurgeTopic {
- stream_id: wire_id_to_identifier(&wire.stream_id)?,
- topic_id: wire_id_to_identifier(&wire.topic_id)?,
- };
- let topic = shard.resolve_topic(&command.stream_id, &command.topic_id)?;
+ let stream_id = wire_id_to_identifier(&wire.stream_id)?;
+ let topic_id = wire_id_to_identifier(&wire.topic_id)?;
+ let topic = shard.resolve_topic(&stream_id, &topic_id)?;
shard
.metadata
.perm_purge_topic(user_id, topic.stream_id, topic.topic_id)?;
@@ -376,7 +349,7 @@ pub async fn execute_purge_topic(
shard
.state
- .apply(user_id, &EntryCommand::PurgeTopic(command))
+ .apply(user_id, &EntryCommand::PurgeTopic(wire))
.await?;
let event = ShardEvent::PurgedTopic {
@@ -397,18 +370,15 @@ pub async fn execute_create_partitions(
user_id: u32,
wire: CreatePartitionsRequest,
) -> Result<(), IggyError> {
- let command = CreatePartitions {
- stream_id: wire_id_to_identifier(&wire.stream_id)?,
- topic_id: wire_id_to_identifier(&wire.topic_id)?,
- partitions_count: wire.partitions_count,
- };
- let topic = shard.resolve_topic(&command.stream_id, &command.topic_id)?;
+ let stream_id = wire_id_to_identifier(&wire.stream_id)?;
+ let topic_id = wire_id_to_identifier(&wire.topic_id)?;
+ let topic = shard.resolve_topic(&stream_id, &topic_id)?;
shard
.metadata
.perm_create_partitions(user_id, topic.stream_id, topic.topic_id)?;
let partition_infos = shard
- .create_partitions(topic, command.partitions_count)
+ .create_partitions(topic, wire.partitions_count)
.await?;
let total_partition_count = shard
.metadata
@@ -421,7 +391,7 @@ pub async fn execute_create_partitions(
shard
.state
- .apply(user_id, &EntryCommand::CreatePartitions(command))
+ .apply(user_id, &EntryCommand::CreatePartitions(wire))
.await?;
let event = ShardEvent::CreatedPartitions {
@@ -443,18 +413,15 @@ pub async fn execute_delete_partitions(
user_id: u32,
wire: DeletePartitionsRequest,
) -> Result<(), IggyError> {
- let command = DeletePartitions {
- stream_id: wire_id_to_identifier(&wire.stream_id)?,
- topic_id: wire_id_to_identifier(&wire.topic_id)?,
- partitions_count: wire.partitions_count,
- };
- let topic = shard.resolve_topic(&command.stream_id, &command.topic_id)?;
+ let stream_id = wire_id_to_identifier(&wire.stream_id)?;
+ let topic_id = wire_id_to_identifier(&wire.topic_id)?;
+ let topic = shard.resolve_topic(&stream_id, &topic_id)?;
shard
.metadata
.perm_delete_partitions(user_id, topic.stream_id, topic.topic_id)?;
let deleted_partition_ids = shard
- .delete_partitions(topic, command.partitions_count)
+ .delete_partitions(topic, wire.partitions_count)
.await?;
let remaining_partition_count = shard
@@ -469,7 +436,7 @@ pub async fn execute_delete_partitions(
shard
.state
- .apply(user_id, &EntryCommand::DeletePartitions(command))
+ .apply(user_id, &EntryCommand::DeletePartitions(wire))
.await?;
let event = ShardEvent::DeletedPartitions {
@@ -492,17 +459,14 @@ pub async fn execute_create_consumer_group(
user_id: u32,
wire: CreateConsumerGroupRequest,
) -> Result<ConsumerGroupResponseData, IggyError> {
- let command = CreateConsumerGroup {
- stream_id: wire_id_to_identifier(&wire.stream_id)?,
- topic_id: wire_id_to_identifier(&wire.topic_id)?,
- name: wire.name.to_string(),
- };
- let topic = shard.resolve_topic(&command.stream_id, &command.topic_id)?;
+ let stream_id = wire_id_to_identifier(&wire.stream_id)?;
+ let topic_id = wire_id_to_identifier(&wire.topic_id)?;
+ let topic = shard.resolve_topic(&stream_id, &topic_id)?;
shard
.metadata
.perm_create_consumer_group(user_id, topic.stream_id, topic.topic_id)?;
- let group_id = shard.create_consumer_group(topic, command.name.clone())?;
+ let group_id = shard.create_consumer_group(topic, wire.name.to_string())?;
let response_data = shard
.metadata
@@ -520,7 +484,7 @@ pub async fn execute_create_consumer_group(
user_id,
&EntryCommand::CreateConsumerGroup(CreateConsumerGroupWithId {
group_id: group_id as u32,
- command,
+ command: wire,
}),
)
.await?;
@@ -533,13 +497,10 @@ pub async fn execute_delete_consumer_group(
user_id: u32,
wire: DeleteConsumerGroupRequest,
) -> Result<(), IggyError> {
- let command = DeleteConsumerGroup {
- stream_id: wire_id_to_identifier(&wire.stream_id)?,
- topic_id: wire_id_to_identifier(&wire.topic_id)?,
- group_id: wire_id_to_identifier(&wire.group_id)?,
- };
- let group =
- shard.resolve_consumer_group(&command.stream_id, &command.topic_id, &command.group_id)?;
+ let stream_id = wire_id_to_identifier(&wire.stream_id)?;
+ let topic_id = wire_id_to_identifier(&wire.topic_id)?;
+ let group_id = wire_id_to_identifier(&wire.group_id)?;
+ let group = shard.resolve_consumer_group(&stream_id, &topic_id, &group_id)?;
shard
.metadata
.perm_delete_consumer_group(user_id, group.stream_id, group.topic_id)?;
@@ -558,7 +519,7 @@ pub async fn execute_delete_consumer_group(
shard
.state
- .apply(user_id, &EntryCommand::DeleteConsumerGroup(command))
+ .apply(user_id, &EntryCommand::DeleteConsumerGroup(wire))
.await?;
Ok(())
@@ -609,22 +570,19 @@ pub async fn execute_create_user(
) -> Result<User, IggyError> {
shard.metadata.perm_create_user(user_id)?;
- let command = CreateUser {
- username: wire.username.to_string(),
- password: SecretString::from(wire.password),
- status: UserStatus::from_code(wire.status)?,
- permissions: wire
- .permissions
- .as_ref()
- .map(wire_permissions_to_permissions),
- };
+ let username = wire.username.to_string();
+ let password = SecretString::from(wire.password.clone());
+ let status = UserStatus::from_code(wire.status)?;
+ let permissions = wire
+ .permissions
+ .as_ref()
+ .map(wire_permissions_to_permissions);
- let user = shard.create_user(
- &command.username,
- command.password.expose_secret(),
- command.status,
- command.permissions.clone(),
- )?;
+ let user = shard.create_user(&username, password.expose_secret(), status, permissions)?;
+
+ // Hash the password before persisting to WAL
+ let mut wal_wire = wire;
+ wal_wire.password = crypto::hash_password(password.expose_secret());
shard
.state
@@ -632,12 +590,7 @@ pub async fn execute_create_user(
user_id,
&EntryCommand::CreateUser(CreateUserWithId {
user_id: user.id,
- command: CreateUser {
- password: SecretString::from(crypto::hash_password(
- command.password.expose_secret(),
- )),
- ..command
- },
+ command: wal_wire,
}),
)
.await?;
@@ -652,14 +605,12 @@ pub async fn execute_delete_user(
) -> Result<User, IggyError> {
shard.metadata.perm_delete_user(user_id)?;
- let command = DeleteUser {
- user_id: wire_id_to_identifier(&wire.user_id)?,
- };
- let user = shard.delete_user(&command.user_id)?;
+ let target_id = wire_id_to_identifier(&wire.user_id)?;
+ let user = shard.delete_user(&target_id)?;
shard
.state
- .apply(user_id, &EntryCommand::DeleteUser(command))
+ .apply(user_id, &EntryCommand::DeleteUser(wire))
.await?;
Ok(user)
@@ -672,16 +623,14 @@ pub async fn execute_update_user(
) -> Result<User, IggyError> {
shard.metadata.perm_update_user(user_id)?;
- let command = UpdateUser {
- user_id: wire_id_to_identifier(&wire.user_id)?,
- username: wire.username.map(|n| n.to_string()),
- status: wire.status.map(UserStatus::from_code).transpose()?,
- };
- let user = shard.update_user(&command.user_id, command.username.clone(), command.status)?;
+ let target_id = wire_id_to_identifier(&wire.user_id)?;
+ let username = wire.username.as_ref().map(|n| n.to_string());
+ let status = wire.status.map(UserStatus::from_code).transpose()?;
+ let user = shard.update_user(&target_id, username, status)?;
shard
.state
- .apply(user_id, &EntryCommand::UpdateUser(command))
+ .apply(user_id, &EntryCommand::UpdateUser(wire))
.await?;
Ok(user)
@@ -692,34 +641,24 @@ pub async fn execute_change_password(
user_id: u32,
wire: ChangePasswordRequest,
) -> Result<(), IggyError> {
- let command = ChangePassword {
- user_id: wire_id_to_identifier(&wire.user_id)?,
- current_password: SecretString::from(wire.current_password),
- new_password: SecretString::from(wire.new_password),
- };
- let target_user = shard.get_user(&command.user_id)?;
+ let target_id = wire_id_to_identifier(&wire.user_id)?;
+ let target_user = shard.get_user(&target_id)?;
if target_user.id != user_id {
shard.metadata.perm_change_password(user_id)?;
}
- shard.change_password(
- &command.user_id,
- command.current_password.expose_secret(),
- command.new_password.expose_secret(),
- )?;
+ shard.change_password(&target_id, &wire.current_password, &wire.new_password)?;
+
+ // Clear current password and hash new password before persisting to WAL
+ let wal_wire = ChangePasswordRequest {
+ user_id: wire.user_id,
+ current_password: String::new(),
+ new_password: crypto::hash_password(&wire.new_password),
+ };
shard
.state
- .apply(
- user_id,
- &EntryCommand::ChangePassword(ChangePassword {
- current_password: SecretString::from(String::new()),
- new_password: SecretString::from(crypto::hash_password(
- command.new_password.expose_secret(),
- )),
- ..command
- }),
- )
+ .apply(user_id, &EntryCommand::ChangePassword(wal_wire))
.await?;
Ok(())
@@ -732,23 +671,21 @@ pub async fn execute_update_permissions(
) -> Result<(), IggyError> {
shard.metadata.perm_update_permissions(user_id)?;
- let command = UpdatePermissions {
- user_id: wire_id_to_identifier(&wire.user_id)?,
- permissions: wire
- .permissions
- .as_ref()
- .map(wire_permissions_to_permissions),
- };
- let target_user = shard.get_user(&command.user_id)?;
+ let target_id = wire_id_to_identifier(&wire.user_id)?;
+ let target_user = shard.get_user(&target_id)?;
if target_user.is_root() {
return Err(IggyError::CannotChangePermissions(target_user.id));
}
- shard.update_permissions(&command.user_id, command.permissions.clone())?;
+ let permissions = wire
+ .permissions
+ .as_ref()
+ .map(wire_permissions_to_permissions);
+ shard.update_permissions(&target_id, permissions)?;
shard
.state
- .apply(user_id, &EntryCommand::UpdatePermissions(command))
+ .apply(user_id, &EntryCommand::UpdatePermissions(wire))
.await?;
Ok(())
@@ -759,12 +696,10 @@ pub async fn execute_create_personal_access_token(
user_id: u32,
wire: CreatePersonalAccessTokenRequest,
) -> Result<(PersonalAccessToken, String), IggyError> {
- let command = CreatePersonalAccessToken {
- name: wire.name.to_string(),
- expiry: IggyExpiry::from(wire.expiry),
- };
+ let name = wire.name.to_string();
+ let expiry = IggyExpiry::from(wire.expiry);
let (personal_access_token, token) =
- shard.create_personal_access_token(user_id, &command.name, command.expiry)?;
+ shard.create_personal_access_token(user_id, &name, expiry)?;
shard
.state
@@ -772,7 +707,7 @@ pub async fn execute_create_personal_access_token(
user_id,
&EntryCommand::CreatePersonalAccessToken(CreatePersonalAccessTokenWithHash {
hash: personal_access_token.token.to_string(),
- command,
+ command: wire,
}),
)
.await?;
@@ -785,14 +720,11 @@ pub async fn execute_delete_personal_access_token(
user_id: u32,
wire: DeletePersonalAccessTokenRequest,
) -> Result<(), IggyError> {
- let command = DeletePersonalAccessToken {
- name: wire.name.to_string(),
- };
- shard.delete_personal_access_token(user_id, &command.name)?;
+ shard.delete_personal_access_token(user_id, wire.name.as_str())?;
shard
.state
- .apply(user_id, &EntryCommand::DeletePersonalAccessToken(command))
+ .apply(user_id, &EntryCommand::DeletePersonalAccessToken(wire))
.await?;
Ok(())
diff --git a/core/server/src/state/command.rs b/core/server/src/state/command.rs
index b9783d2a6..ccb19c05f 100644
--- a/core/server/src/state/command.rs
+++ b/core/server/src/state/command.rs
@@ -21,82 +21,85 @@ use crate::state::models::{
CreateTopicWithId, CreateUserWithId,
};
use bytes::{Buf, BufMut, Bytes, BytesMut};
-use iggy_common::BytesSerializable;
-use iggy_common::IggyError;
-use iggy_common::change_password::ChangePassword;
-use iggy_common::create_partitions::CreatePartitions;
-use iggy_common::delete_consumer_group::DeleteConsumerGroup;
-use iggy_common::delete_partitions::DeletePartitions;
-use iggy_common::delete_personal_access_token::DeletePersonalAccessToken;
-use iggy_common::delete_segments::DeleteSegments;
-use iggy_common::delete_stream::DeleteStream;
-use iggy_common::delete_topic::DeleteTopic;
-use iggy_common::delete_user::DeleteUser;
-use iggy_common::purge_stream::PurgeStream;
-use iggy_common::purge_topic::PurgeTopic;
-use iggy_common::update_permissions::UpdatePermissions;
-use iggy_common::update_stream::UpdateStream;
-use iggy_common::update_topic::UpdateTopic;
-use iggy_common::update_user::UpdateUser;
-use iggy_common::{
+use iggy_binary_protocol::codes::{
CHANGE_PASSWORD_CODE, CREATE_CONSUMER_GROUP_CODE, CREATE_PARTITIONS_CODE,
CREATE_PERSONAL_ACCESS_TOKEN_CODE, CREATE_STREAM_CODE, CREATE_TOPIC_CODE, CREATE_USER_CODE,
- Command, DELETE_CONSUMER_GROUP_CODE, DELETE_PARTITIONS_CODE, DELETE_PERSONAL_ACCESS_TOKEN_CODE,
- DELETE_STREAM_CODE, DELETE_TOPIC_CODE, DELETE_USER_CODE, PURGE_STREAM_CODE, PURGE_TOPIC_CODE,
- UPDATE_PERMISSIONS_CODE, UPDATE_STREAM_CODE, UPDATE_TOPIC_CODE, UPDATE_USER_CODE,
+ DELETE_CONSUMER_GROUP_CODE, DELETE_PARTITIONS_CODE, DELETE_PERSONAL_ACCESS_TOKEN_CODE,
+ DELETE_SEGMENTS_CODE, DELETE_STREAM_CODE, DELETE_TOPIC_CODE, DELETE_USER_CODE,
+ PURGE_STREAM_CODE, PURGE_TOPIC_CODE, UPDATE_PERMISSIONS_CODE, UPDATE_STREAM_CODE,
+ UPDATE_TOPIC_CODE, UPDATE_USER_CODE,
+};
+use iggy_binary_protocol::requests::{
+ consumer_groups::DeleteConsumerGroupRequest,
+ partitions::{CreatePartitionsRequest, DeletePartitionsRequest},
+ personal_access_tokens::DeletePersonalAccessTokenRequest,
+ segments::DeleteSegmentsRequest,
+ streams::{DeleteStreamRequest, PurgeStreamRequest, UpdateStreamRequest},
+ topics::{DeleteTopicRequest, PurgeTopicRequest, UpdateTopicRequest},
+ users::{
+ ChangePasswordRequest, DeleteUserRequest, UpdatePermissionsRequest, UpdateUserRequest,
+ },
};
+use iggy_binary_protocol::{WireDecode, WireEncode};
+use iggy_common::BytesSerializable;
+use iggy_common::IggyError;
use std::fmt::{Display, Formatter};
#[derive(Debug)]
pub enum EntryCommand {
CreateStream(CreateStreamWithId),
- UpdateStream(UpdateStream),
- DeleteStream(DeleteStream),
- PurgeStream(PurgeStream),
+ UpdateStream(UpdateStreamRequest),
+ DeleteStream(DeleteStreamRequest),
+ PurgeStream(PurgeStreamRequest),
CreateTopic(CreateTopicWithId),
- UpdateTopic(UpdateTopic),
- DeleteTopic(DeleteTopic),
- PurgeTopic(PurgeTopic),
- CreatePartitions(CreatePartitions),
- DeletePartitions(DeletePartitions),
- DeleteSegments(DeleteSegments),
+ UpdateTopic(UpdateTopicRequest),
+ DeleteTopic(DeleteTopicRequest),
+ PurgeTopic(PurgeTopicRequest),
+ CreatePartitions(CreatePartitionsRequest),
+ DeletePartitions(DeletePartitionsRequest),
+ DeleteSegments(DeleteSegmentsRequest),
CreateConsumerGroup(CreateConsumerGroupWithId),
- DeleteConsumerGroup(DeleteConsumerGroup),
+ DeleteConsumerGroup(DeleteConsumerGroupRequest),
CreateUser(CreateUserWithId),
- UpdateUser(UpdateUser),
- DeleteUser(DeleteUser),
- ChangePassword(ChangePassword),
- UpdatePermissions(UpdatePermissions),
+ UpdateUser(UpdateUserRequest),
+ DeleteUser(DeleteUserRequest),
+ ChangePassword(ChangePasswordRequest),
+ UpdatePermissions(UpdatePermissionsRequest),
CreatePersonalAccessToken(CreatePersonalAccessTokenWithHash),
- DeletePersonalAccessToken(DeletePersonalAccessToken),
+ DeletePersonalAccessToken(DeletePersonalAccessTokenRequest),
+}
+
+fn wire_error_to_iggy(e: iggy_binary_protocol::WireError) -> IggyError {
+ tracing::warn!("wire decode error during WAL replay: {e}");
+ IggyError::InvalidCommand
}
impl BytesSerializable for EntryCommand {
fn to_bytes(&self) -> Bytes {
let (code, command) = match self {
- EntryCommand::CreateStream(command) => (command.code(), command.to_bytes()),
- EntryCommand::UpdateStream(command) => (command.code(), command.to_bytes()),
- EntryCommand::DeleteStream(command) => (command.code(), command.to_bytes()),
- EntryCommand::PurgeStream(command) => (command.code(), command.to_bytes()),
- EntryCommand::CreateTopic(command) => (command.code(), command.to_bytes()),
- EntryCommand::UpdateTopic(command) => (command.code(), command.to_bytes()),
- EntryCommand::DeleteTopic(command) => (command.code(), command.to_bytes()),
- EntryCommand::PurgeTopic(command) => (command.code(), command.to_bytes()),
- EntryCommand::CreatePartitions(command) => (command.code(), command.to_bytes()),
- EntryCommand::DeletePartitions(command) => (command.code(), command.to_bytes()),
- EntryCommand::DeleteSegments(command) => (command.code(), command.to_bytes()),
- EntryCommand::CreateConsumerGroup(command) => (command.code(), command.to_bytes()),
- EntryCommand::DeleteConsumerGroup(command) => (command.code(), command.to_bytes()),
- EntryCommand::CreateUser(command) => (command.code(), command.to_bytes()),
- EntryCommand::UpdateUser(command) => (command.code(), command.to_bytes()),
- EntryCommand::DeleteUser(command) => (command.code(), command.to_bytes()),
- EntryCommand::ChangePassword(command) => (command.code(), command.to_bytes()),
- EntryCommand::UpdatePermissions(command) => (command.code(), command.to_bytes()),
- EntryCommand::CreatePersonalAccessToken(command) => {
- (command.code(), command.to_bytes())
+ EntryCommand::CreateStream(cmd) => (CREATE_STREAM_CODE, cmd.to_bytes()),
+ EntryCommand::UpdateStream(cmd) => (UPDATE_STREAM_CODE, cmd.to_bytes()),
+ EntryCommand::DeleteStream(cmd) => (DELETE_STREAM_CODE, cmd.to_bytes()),
+ EntryCommand::PurgeStream(cmd) => (PURGE_STREAM_CODE, cmd.to_bytes()),
+ EntryCommand::CreateTopic(cmd) => (CREATE_TOPIC_CODE, cmd.to_bytes()),
+ EntryCommand::UpdateTopic(cmd) => (UPDATE_TOPIC_CODE, cmd.to_bytes()),
+ EntryCommand::DeleteTopic(cmd) => (DELETE_TOPIC_CODE, cmd.to_bytes()),
+ EntryCommand::PurgeTopic(cmd) => (PURGE_TOPIC_CODE, cmd.to_bytes()),
+ EntryCommand::CreatePartitions(cmd) => (CREATE_PARTITIONS_CODE, cmd.to_bytes()),
+ EntryCommand::DeletePartitions(cmd) => (DELETE_PARTITIONS_CODE, cmd.to_bytes()),
+ EntryCommand::DeleteSegments(cmd) => (DELETE_SEGMENTS_CODE, cmd.to_bytes()),
+ EntryCommand::CreateConsumerGroup(cmd) => (CREATE_CONSUMER_GROUP_CODE, cmd.to_bytes()),
+ EntryCommand::DeleteConsumerGroup(cmd) => (DELETE_CONSUMER_GROUP_CODE, cmd.to_bytes()),
+ EntryCommand::CreateUser(cmd) => (CREATE_USER_CODE, cmd.to_bytes()),
+ EntryCommand::UpdateUser(cmd) => (UPDATE_USER_CODE, cmd.to_bytes()),
+ EntryCommand::DeleteUser(cmd) => (DELETE_USER_CODE, cmd.to_bytes()),
+ EntryCommand::ChangePassword(cmd) => (CHANGE_PASSWORD_CODE, cmd.to_bytes()),
+ EntryCommand::UpdatePermissions(cmd) => (UPDATE_PERMISSIONS_CODE, cmd.to_bytes()),
+ EntryCommand::CreatePersonalAccessToken(cmd) => {
+ (CREATE_PERSONAL_ACCESS_TOKEN_CODE, cmd.to_bytes())
}
- EntryCommand::DeletePersonalAccessToken(command) => {
- (command.code(), command.to_bytes())
+ EntryCommand::DeletePersonalAccessToken(cmd) => {
+ (DELETE_PERSONAL_ACCESS_TOKEN_CODE, cmd.to_bytes())
}
};
@@ -113,52 +116,69 @@ impl BytesSerializable for EntryCommand {
{
let code = bytes.slice(0..4).get_u32_le();
let length = bytes.slice(4..8).get_u32_le();
- let payload = bytes.slice(8..8 + length as usize);
+ let payload = &bytes[8..8 + length as usize];
match code {
- CREATE_STREAM_CODE => Ok(EntryCommand::CreateStream(CreateStreamWithId::from_bytes(
- payload,
- )?)),
- UPDATE_STREAM_CODE => Ok(EntryCommand::UpdateStream(UpdateStream::from_bytes(
- payload,
- )?)),
- DELETE_STREAM_CODE => Ok(EntryCommand::DeleteStream(DeleteStream::from_bytes(
- payload,
- )?)),
- PURGE_STREAM_CODE => Ok(EntryCommand::PurgeStream(PurgeStream::from_bytes(payload)?)),
- CREATE_TOPIC_CODE => Ok(EntryCommand::CreateTopic(CreateTopicWithId::from_bytes(
- payload,
- )?)),
- UPDATE_TOPIC_CODE => Ok(EntryCommand::UpdateTopic(UpdateTopic::from_bytes(payload)?)),
- DELETE_TOPIC_CODE => Ok(EntryCommand::DeleteTopic(DeleteTopic::from_bytes(payload)?)),
- PURGE_TOPIC_CODE => Ok(EntryCommand::PurgeTopic(PurgeTopic::from_bytes(payload)?)),
+ CREATE_STREAM_CODE => Ok(EntryCommand::CreateStream(
+ CreateStreamWithId::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
+ UPDATE_STREAM_CODE => Ok(EntryCommand::UpdateStream(
+ UpdateStreamRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
+ DELETE_STREAM_CODE => Ok(EntryCommand::DeleteStream(
+ DeleteStreamRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
+ PURGE_STREAM_CODE => Ok(EntryCommand::PurgeStream(
+ PurgeStreamRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
+ CREATE_TOPIC_CODE => Ok(EntryCommand::CreateTopic(
+ CreateTopicWithId::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
+ UPDATE_TOPIC_CODE => Ok(EntryCommand::UpdateTopic(
+ UpdateTopicRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
+ DELETE_TOPIC_CODE => Ok(EntryCommand::DeleteTopic(
+ DeleteTopicRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
+ PURGE_TOPIC_CODE => Ok(EntryCommand::PurgeTopic(
+ PurgeTopicRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
CREATE_PARTITIONS_CODE => Ok(EntryCommand::CreatePartitions(
- CreatePartitions::from_bytes(payload)?,
+ CreatePartitionsRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
)),
DELETE_PARTITIONS_CODE => Ok(EntryCommand::DeletePartitions(
- DeletePartitions::from_bytes(payload)?,
+ DeletePartitionsRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
+ DELETE_SEGMENTS_CODE => Ok(EntryCommand::DeleteSegments(
+ DeleteSegmentsRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
)),
CREATE_CONSUMER_GROUP_CODE => Ok(EntryCommand::CreateConsumerGroup(
- CreateConsumerGroupWithId::from_bytes(payload)?,
+ CreateConsumerGroupWithId::decode_from(payload).map_err(wire_error_to_iggy)?,
)),
DELETE_CONSUMER_GROUP_CODE => Ok(EntryCommand::DeleteConsumerGroup(
- DeleteConsumerGroup::from_bytes(payload)?,
- )),
- CREATE_USER_CODE => Ok(EntryCommand::CreateUser(CreateUserWithId::from_bytes(
- payload,
- )?)),
- UPDATE_USER_CODE => Ok(EntryCommand::UpdateUser(UpdateUser::from_bytes(payload)?)),
- DELETE_USER_CODE => Ok(EntryCommand::DeleteUser(DeleteUser::from_bytes(payload)?)),
- CHANGE_PASSWORD_CODE => Ok(EntryCommand::ChangePassword(ChangePassword::from_bytes(
- payload,
- )?)),
+ DeleteConsumerGroupRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
+ CREATE_USER_CODE => Ok(EntryCommand::CreateUser(
+ CreateUserWithId::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
+ UPDATE_USER_CODE => Ok(EntryCommand::UpdateUser(
+ UpdateUserRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
+ DELETE_USER_CODE => Ok(EntryCommand::DeleteUser(
+ DeleteUserRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
+ CHANGE_PASSWORD_CODE => Ok(EntryCommand::ChangePassword(
+ ChangePasswordRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
+ )),
UPDATE_PERMISSIONS_CODE => Ok(EntryCommand::UpdatePermissions(
- UpdatePermissions::from_bytes(payload)?,
+ UpdatePermissionsRequest::decode_from(payload).map_err(wire_error_to_iggy)?,
)),
CREATE_PERSONAL_ACCESS_TOKEN_CODE => Ok(EntryCommand::CreatePersonalAccessToken(
- CreatePersonalAccessTokenWithHash::from_bytes(payload)?,
+ CreatePersonalAccessTokenWithHash::decode_from(payload)
+ .map_err(wire_error_to_iggy)?,
)),
DELETE_PERSONAL_ACCESS_TOKEN_CODE => Ok(EntryCommand::DeletePersonalAccessToken(
- DeletePersonalAccessToken::from_bytes(payload)?,
+ DeletePersonalAccessTokenRequest::decode_from(payload)
+ .map_err(wire_error_to_iggy)?,
)),
_ => Err(IggyError::InvalidCommand),
}
@@ -169,32 +189,34 @@ impl Display for EntryCommand {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
EntryCommand::CreateStream(command) => write!(f, "CreateStream({command})"),
- EntryCommand::UpdateStream(command) => write!(f, "UpdateStream({command})"),
- EntryCommand::DeleteStream(command) => write!(f, "DeleteStream({command})"),
- EntryCommand::PurgeStream(command) => write!(f, "PurgeStream({command})"),
+ EntryCommand::UpdateStream(command) => write!(f, "UpdateStream({command:?})"),
+ EntryCommand::DeleteStream(command) => write!(f, "DeleteStream({command:?})"),
+ EntryCommand::PurgeStream(command) => write!(f, "PurgeStream({command:?})"),
EntryCommand::CreateTopic(command) => write!(f, "CreateTopic({command})"),
- EntryCommand::UpdateTopic(command) => write!(f, "UpdateTopic({command})"),
- EntryCommand::DeleteTopic(command) => write!(f, "DeleteTopic({command})"),
- EntryCommand::PurgeTopic(command) => write!(f, "PurgeTopic({command})"),
- EntryCommand::CreatePartitions(command) => write!(f, "CreatePartitions({command})"),
- EntryCommand::DeletePartitions(command) => write!(f, "DeletePartitions({command})"),
- EntryCommand::DeleteSegments(command) => write!(f, "DeleteSegments({command})"),
+ EntryCommand::UpdateTopic(command) => write!(f, "UpdateTopic({command:?})"),
+ EntryCommand::DeleteTopic(command) => write!(f, "DeleteTopic({command:?})"),
+ EntryCommand::PurgeTopic(command) => write!(f, "PurgeTopic({command:?})"),
+ EntryCommand::CreatePartitions(command) => write!(f, "CreatePartitions({command:?})"),
+ EntryCommand::DeletePartitions(command) => write!(f, "DeletePartitions({command:?})"),
+ EntryCommand::DeleteSegments(command) => write!(f, "DeleteSegments({command:?})"),
EntryCommand::CreateConsumerGroup(command) => {
write!(f, "CreateConsumerGroup({command})")
}
EntryCommand::DeleteConsumerGroup(command) => {
- write!(f, "DeleteConsumerGroup({command})")
+ write!(f, "DeleteConsumerGroup({command:?})")
}
EntryCommand::CreateUser(command) => write!(f, "CreateUser({command})"),
- EntryCommand::UpdateUser(command) => write!(f, "UpdateUser({command})"),
- EntryCommand::DeleteUser(command) => write!(f, "DeleteUser({command})"),
- EntryCommand::ChangePassword(command) => write!(f, "ChangePassword({command})"),
- EntryCommand::UpdatePermissions(command) => write!(f, "UpdatePermissions({command})"),
+ EntryCommand::UpdateUser(command) => write!(f, "UpdateUser({command:?})"),
+ EntryCommand::DeleteUser(command) => write!(f, "DeleteUser({command:?})"),
+ EntryCommand::ChangePassword(command) => write!(f, "ChangePassword({command:?})"),
+ EntryCommand::UpdatePermissions(command) => {
+ write!(f, "UpdatePermissions({command:?})")
+ }
EntryCommand::CreatePersonalAccessToken(command) => {
write!(f, "CreatePersonalAccessToken({command})")
}
EntryCommand::DeletePersonalAccessToken(command) => {
- write!(f, "DeletePersonalAccessToken({command})")
+ write!(f, "DeletePersonalAccessToken({command:?})")
}
}
}
diff --git a/core/server/src/state/models.rs b/core/server/src/state/models.rs
index e0b97106f..01a9309df 100644
--- a/core/server/src/state/models.rs
+++ b/core/server/src/state/models.rs
@@ -16,119 +16,52 @@
* under the License.
*/
-use crate::state::COMPONENT;
-use bytes::{BufMut, Bytes, BytesMut};
-use err_trail::ErrContext;
-use iggy_common::BytesSerializable;
-use iggy_common::Command;
-use iggy_common::IggyError;
-use iggy_common::Validatable;
-use iggy_common::create_consumer_group::CreateConsumerGroup;
-use iggy_common::create_personal_access_token::CreatePersonalAccessToken;
-use iggy_common::create_stream::CreateStream;
-use iggy_common::create_topic::CreateTopic;
-use iggy_common::create_user::CreateUser;
-use serde::{Deserialize, Serialize};
+use bytes::{BufMut, BytesMut};
+use iggy_binary_protocol::requests::{
+ consumer_groups::CreateConsumerGroupRequest,
+ personal_access_tokens::CreatePersonalAccessTokenRequest, streams::CreateStreamRequest,
+ topics::CreateTopicRequest, users::CreateUserRequest,
+};
+use iggy_binary_protocol::{WireDecode, WireEncode};
use std::fmt;
use std::fmt::{Display, Formatter};
-use std::str::from_utf8;
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateStreamWithId {
pub stream_id: u32,
- pub command: CreateStream,
+ pub command: CreateStreamRequest,
}
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateTopicWithId {
pub topic_id: u32,
- pub command: CreateTopic,
+ pub command: CreateTopicRequest,
}
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateConsumerGroupWithId {
pub group_id: u32,
- pub command: CreateConsumerGroup,
+ pub command: CreateConsumerGroupRequest,
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateUserWithId {
pub user_id: u32,
- pub command: CreateUser,
+ pub command: CreateUserRequest,
}
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreatePersonalAccessTokenWithHash {
pub hash: String,
- pub command: CreatePersonalAccessToken,
-}
-
-impl Validatable<IggyError> for CreateStreamWithId {
- fn validate(&self) -> Result<(), IggyError> {
- self.command.validate()
- }
-}
-
-impl Command for CreateStreamWithId {
- fn code(&self) -> u32 {
- self.command.code()
- }
-}
-
-impl Validatable<IggyError> for CreateTopicWithId {
- fn validate(&self) -> Result<(), IggyError> {
- self.command.validate()
- }
-}
-
-impl Command for CreateTopicWithId {
- fn code(&self) -> u32 {
- self.command.code()
- }
-}
-
-impl Validatable<IggyError> for CreateConsumerGroupWithId {
- fn validate(&self) -> Result<(), IggyError> {
- self.command.validate()
- }
-}
-
-impl Command for CreateConsumerGroupWithId {
- fn code(&self) -> u32 {
- self.command.code()
- }
-}
-
-impl Validatable<IggyError> for CreateUserWithId {
- fn validate(&self) -> Result<(), IggyError> {
- self.command.validate()
- }
-}
-
-impl Command for CreateUserWithId {
- fn code(&self) -> u32 {
- self.command.code()
- }
-}
-
-impl Validatable<IggyError> for CreatePersonalAccessTokenWithHash {
- fn validate(&self) -> Result<(), IggyError> {
- self.command.validate()
- }
-}
-
-impl Command for CreatePersonalAccessTokenWithHash {
- fn code(&self) -> u32 {
- self.command.code()
- }
+ pub command: CreatePersonalAccessTokenRequest,
}
impl Display for CreateStreamWithId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
- "CreateStreamWithId {{ command: {}, stream ID: {} }}",
- self.command, self.stream_id
+ "CreateStreamWithId {{ name: {}, stream_id: {} }}",
+ self.command.name, self.stream_id
)
}
}
@@ -137,8 +70,8 @@ impl Display for CreateTopicWithId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
- "CreateTopicWithId {{ command: {}, topic ID: {} }}",
- self.command, self.topic_id
+ "CreateTopicWithId {{ name: {}, topic_id: {} }}",
+ self.command.name, self.topic_id
)
}
}
@@ -147,8 +80,8 @@ impl Display for CreateConsumerGroupWithId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
- "CreateConsumerGroupWithId {{ command: {}, group_id: {} }}",
- self.command, self.group_id
+ "CreateConsumerGroupWithId {{ name: {}, group_id: {} }}",
+ self.command.name, self.group_id
)
}
}
@@ -157,8 +90,8 @@ impl Display for CreateUserWithId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
- "CreateUserWithId {{ command: {}, user_id: {} }}",
- self.command, self.user_id
+ "CreateUserWithId {{ username: {}, user_id: {} }}",
+ self.command.username, self.user_id
)
}
}
@@ -167,222 +100,160 @@ impl Display for CreatePersonalAccessTokenWithHash {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
- "CreatePersonalAccessTokenWithHash {{ command: {}, hash: {} }}",
- self.command, self.hash
+ "CreatePersonalAccessTokenWithHash {{ name: {}, hash: [REDACTED] }}",
+ self.command.name,
)
}
}
-impl BytesSerializable for CreateStreamWithId {
- fn to_bytes(&self) -> Bytes {
- let mut bytes = BytesMut::new();
- bytes.put_u32_le(self.stream_id);
- let command_bytes = self.command.to_bytes();
- bytes.put_u32_le(command_bytes.len() as u32);
- bytes.put_slice(&command_bytes);
- bytes.freeze()
+// Wire format for WithId wrappers: id:u32_le | inner_length:u32_le | inner_bytes
+// This is identical to the previous BytesSerializable format.
+
+impl WireEncode for CreateStreamWithId {
+ fn encoded_size(&self) -> usize {
+ 4 + 4 + self.command.encoded_size()
+ }
+
+ fn encode(&self, buf: &mut BytesMut) {
+ buf.put_u32_le(self.stream_id);
+ buf.put_u32_le(self.command.encoded_size() as u32);
+ self.command.encode(buf);
}
+}
- fn from_bytes(bytes: Bytes) -> Result<Self, IggyError>
- where
- Self: Sized,
- {
- let mut position = 0;
- let stream_id = u32::from_le_bytes(
- bytes[position..4]
- .try_into()
- .error(|e: &std::array::TryFromSliceError| {
- format!("{COMPONENT} (error: {e}) - failed to parse stream ID")
- })
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- position += 4;
- let command_length = u32::from_le_bytes(
- bytes[position..position + 4]
- .try_into()
- .error(|e: &std::array::TryFromSliceError| {
- format!("{COMPONENT} (error: {e}) - failed to parse stream command length")
- })
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- position += 4;
- let command_bytes = bytes.slice(position..position + command_length as usize);
- let command = CreateStream::from_bytes(command_bytes).error(|e: &IggyError| {
- format!("{COMPONENT} (error: {e}) - failed to parse stream command")
- })?;
- Ok(Self { stream_id, command })
+impl WireDecode for CreateStreamWithId {
+ fn decode(buf: &[u8]) -> Result<(Self, usize), iggy_binary_protocol::WireError> {
+ if buf.len() < 8 {
+ return Err(iggy_binary_protocol::WireError::UnexpectedEof {
+ offset: 0,
+ need: 8,
+ have: buf.len(),
+ });
+ }
+ let stream_id = u32::from_le_bytes(buf[0..4].try_into().unwrap());
+ let command_length = u32::from_le_bytes(buf[4..8].try_into().unwrap()) as usize;
+ let (command, _) = CreateStreamRequest::decode(&buf[8..8 + command_length])?;
+ Ok((Self { stream_id, command }, 8 + command_length))
}
}
-impl BytesSerializable for CreateTopicWithId {
- fn to_bytes(&self) -> Bytes {
- let mut bytes = BytesMut::new();
- bytes.put_u32_le(self.topic_id);
- let command_bytes = self.command.to_bytes();
- bytes.put_u32_le(command_bytes.len() as u32);
- bytes.put_slice(&command_bytes);
- bytes.freeze()
+impl WireEncode for CreateTopicWithId {
+ fn encoded_size(&self) -> usize {
+ 4 + 4 + self.command.encoded_size()
}
- fn from_bytes(bytes: Bytes) -> Result<Self, IggyError>
- where
- Self: Sized,
- {
- let mut position = 0;
- let topic_id = u32::from_le_bytes(
- bytes[position..4]
- .try_into()
- .error(|e: &std::array::TryFromSliceError| {
- format!("{COMPONENT} (error: {e}) - failed to parse topic ID")
- })
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- position += 4;
- let command_length = u32::from_le_bytes(
- bytes[position..position + 4]
- .try_into()
- .error(|e: &std::array::TryFromSliceError| {
- format!("{COMPONENT} (error: {e}) - failed to parse topic command length")
- })
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- position += 4;
- let command_bytes = bytes.slice(position..position + command_length as usize);
- let command = CreateTopic::from_bytes(command_bytes).error(|e: &IggyError| {
- format!("{COMPONENT} (error: {e}) - failed to parse topic command")
- })?;
- Ok(Self { topic_id, command })
+ fn encode(&self, buf: &mut BytesMut) {
+ buf.put_u32_le(self.topic_id);
+ buf.put_u32_le(self.command.encoded_size() as u32);
+ self.command.encode(buf);
}
}
-impl BytesSerializable for CreateConsumerGroupWithId {
- fn to_bytes(&self) -> Bytes {
- let mut bytes = BytesMut::new();
- bytes.put_u32_le(self.group_id);
- let command_bytes = self.command.to_bytes();
- bytes.put_u32_le(command_bytes.len() as u32);
- bytes.put_slice(&command_bytes);
- bytes.freeze()
+impl WireDecode for CreateTopicWithId {
+ fn decode(buf: &[u8]) -> Result<(Self, usize), iggy_binary_protocol::WireError> {
+ if buf.len() < 8 {
+ return Err(iggy_binary_protocol::WireError::UnexpectedEof {
+ offset: 0,
+ need: 8,
+ have: buf.len(),
+ });
+ }
+ let topic_id = u32::from_le_bytes(buf[0..4].try_into().unwrap());
+ let command_length = u32::from_le_bytes(buf[4..8].try_into().unwrap()) as usize;
+ let (command, _) = CreateTopicRequest::decode(&buf[8..8 + command_length])?;
+ Ok((Self { topic_id, command }, 8 + command_length))
}
+}
- fn from_bytes(bytes: Bytes) -> Result<Self, IggyError>
- where
- Self: Sized,
- {
- let mut position = 0;
- let group_id = u32::from_le_bytes(
- bytes[position..4]
- .try_into()
- .error(|e: &std::array::TryFromSliceError| {
- format!("{COMPONENT} (error: {e}) - failed to parse consumer group ID")
- })
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- position += 4;
- let command_length = u32::from_le_bytes(
- bytes[position..position + 4]
- .try_into()
- .error(|e: &std::array::TryFromSliceError| {
- format!(
- "{COMPONENT} (error: {e}) - failed to parse consumer group command length"
- )
- })
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- position += 4;
- let command_bytes = bytes.slice(position..position + command_length as usize);
- let command = CreateConsumerGroup::from_bytes(command_bytes).error(|e: &IggyError| {
- format!("{COMPONENT} (error: {e}) - failed to parse consumer group command")
- })?;
- Ok(Self { group_id, command })
+impl WireEncode for CreateConsumerGroupWithId {
+ fn encoded_size(&self) -> usize {
+ 4 + 4 + self.command.encoded_size()
+ }
+
+ fn encode(&self, buf: &mut BytesMut) {
+ buf.put_u32_le(self.group_id);
+ buf.put_u32_le(self.command.encoded_size() as u32);
+ self.command.encode(buf);
+ }
+}
+
+impl WireDecode for CreateConsumerGroupWithId {
+ fn decode(buf: &[u8]) -> Result<(Self, usize), iggy_binary_protocol::WireError> {
+ if buf.len() < 8 {
+ return Err(iggy_binary_protocol::WireError::UnexpectedEof {
+ offset: 0,
+ need: 8,
+ have: buf.len(),
+ });
+ }
+ let group_id = u32::from_le_bytes(buf[0..4].try_into().unwrap());
+ let command_length = u32::from_le_bytes(buf[4..8].try_into().unwrap()) as usize;
+ let (command, _) = CreateConsumerGroupRequest::decode(&buf[8..8 + command_length])?;
+ Ok((Self { group_id, command }, 8 + command_length))
}
}
-impl BytesSerializable for CreateUserWithId {
- fn to_bytes(&self) -> Bytes {
- let mut bytes = BytesMut::new();
- bytes.put_u32_le(self.user_id);
- let command_bytes = self.command.to_bytes();
- bytes.put_u32_le(command_bytes.len() as u32);
- bytes.put_slice(&command_bytes);
- bytes.freeze()
+impl WireEncode for CreateUserWithId {
+ fn encoded_size(&self) -> usize {
+ 4 + 4 + self.command.encoded_size()
}
- fn from_bytes(bytes: Bytes) -> Result<Self, IggyError>
- where
- Self: Sized,
- {
- let mut position = 0;
- let user_id = u32::from_le_bytes(
- bytes[position..4]
- .try_into()
- .error(|e: &std::array::TryFromSliceError| {
- format!("{COMPONENT} (error: {e}) - failed to parse user ID")
- })
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- position += 4;
- let command_length = u32::from_le_bytes(
- bytes[position..position + 4]
- .try_into()
- .error(|e: &std::array::TryFromSliceError| {
- format!("{COMPONENT} (error: {e}) - failed to parse user command length")
- })
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- position += 4;
- let command_bytes = bytes.slice(position..position + command_length as usize);
- let command = CreateUser::from_bytes(command_bytes).error(|e: &IggyError| {
- format!("{COMPONENT} (error: {e}) - failed to parse user command")
- })?;
- Ok(Self { user_id, command })
+ fn encode(&self, buf: &mut BytesMut) {
+ buf.put_u32_le(self.user_id);
+ buf.put_u32_le(self.command.encoded_size() as u32);
+ self.command.encode(buf);
}
}
-impl BytesSerializable for CreatePersonalAccessTokenWithHash {
- fn to_bytes(&self) -> Bytes {
- let mut bytes = BytesMut::new();
- bytes.put_u32_le(self.hash.len() as u32);
- bytes.put_slice(self.hash.as_bytes());
- let command_bytes = self.command.to_bytes();
- bytes.put_u32_le(command_bytes.len() as u32);
- bytes.put_slice(&command_bytes);
- bytes.freeze()
+impl WireDecode for CreateUserWithId {
+ fn decode(buf: &[u8]) -> Result<(Self, usize), iggy_binary_protocol::WireError> {
+ if buf.len() < 8 {
+ return Err(iggy_binary_protocol::WireError::UnexpectedEof {
+ offset: 0,
+ need: 8,
+ have: buf.len(),
+ });
+ }
+ let user_id = u32::from_le_bytes(buf[0..4].try_into().unwrap());
+ let command_length = u32::from_le_bytes(buf[4..8].try_into().unwrap()) as usize;
+ let (command, _) = CreateUserRequest::decode(&buf[8..8 + command_length])?;
+ Ok((Self { user_id, command }, 8 + command_length))
}
+}
- fn from_bytes(bytes: Bytes) -> Result<Self, IggyError>
- where
- Self: Sized,
- {
- let mut position = 0;
- let hash_length = u32::from_le_bytes(
- bytes[position..4]
- .try_into()
- .error(|e: &std::array::TryFromSliceError| {
- format!("{COMPONENT} (error: {e}) - failed to parse hash length")
- })
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- position += 4;
- let hash = from_utf8(&bytes[position..position + hash_length as usize])
- .map_err(|_| IggyError::InvalidUtf8)?
- .to_string();
+impl WireEncode for CreatePersonalAccessTokenWithHash {
+ fn encoded_size(&self) -> usize {
+ 4 + self.hash.len() + 4 + self.command.encoded_size()
+ }
- position += hash_length as usize;
- let command_length = u32::from_le_bytes(
- bytes[position..position + 4]
- .try_into()
- .error(|e: &std::array::TryFromSliceError| {
- format!("{COMPONENT} (error: {e}) - failed to parse personal access token command length")
- })
- .map_err(|_| IggyError::InvalidNumberEncoding)?,
- );
- position += 4;
- let command_bytes = bytes.slice(position..position + command_length as usize);
- let command =
- CreatePersonalAccessToken::from_bytes(command_bytes).error(|e: &IggyError| {
- format!("{COMPONENT} (error: {e}) - failed to parse personal access token command")
- })?;
- Ok(Self { hash, command })
+ fn encode(&self, buf: &mut BytesMut) {
+ buf.put_u32_le(self.hash.len() as u32);
+ buf.put_slice(self.hash.as_bytes());
+ buf.put_u32_le(self.command.encoded_size() as u32);
+ self.command.encode(buf);
+ }
+}
+
+impl WireDecode for CreatePersonalAccessTokenWithHash {
+ fn decode(buf: &[u8]) -> Result<(Self, usize), iggy_binary_protocol::WireError> {
+ if buf.len() < 4 {
+ return Err(iggy_binary_protocol::WireError::UnexpectedEof {
+ offset: 0,
+ need: 4,
+ have: buf.len(),
+ });
+ }
+ let hash_length = u32::from_le_bytes(buf[0..4].try_into().unwrap()) as usize;
+ let mut pos = 4;
+ let hash = std::str::from_utf8(&buf[pos..pos + hash_length])
+ .map_err(|_| iggy_binary_protocol::WireError::InvalidUtf8 { offset: pos })?
+ .to_string();
+ pos += hash_length;
+ let command_length = u32::from_le_bytes(buf[pos..pos + 4].try_into().unwrap()) as usize;
+ pos += 4;
+ let (command, _) =
+ CreatePersonalAccessTokenRequest::decode(&buf[pos..pos + command_length])?;
+ pos += command_length;
+ Ok((Self { hash, command }, pos))
}
}
diff --git a/core/server/src/state/system.rs b/core/server/src/state/system.rs
index 666d62475..784f6df7a 100644
--- a/core/server/src/state/system.rs
+++ b/core/server/src/state/system.rs
@@ -16,22 +16,23 @@
* under the License.
*/
+use crate::binary::dispatch::{domain_permissions_to_wire, wire_permissions_to_permissions};
use crate::bootstrap::create_root_user;
use crate::state::file::FileState;
use crate::state::models::CreateUserWithId;
use crate::state::{COMPONENT, EntryCommand, StateEntry};
use ahash::AHashMap;
use err_trail::ErrContext;
+use iggy_binary_protocol::requests::users::CreateUserRequest;
+use iggy_binary_protocol::{WireIdentifier, WireName};
use iggy_common::CompressionAlgorithm;
use iggy_common::IggyError;
use iggy_common::IggyExpiry;
use iggy_common::IggyTimestamp;
use iggy_common::MaxTopicSize;
use iggy_common::PersonalAccessToken;
-use iggy_common::create_user::CreateUser;
use iggy_common::defaults::DEFAULT_ROOT_USER_ID;
-use iggy_common::{IdKind, Identifier, Permissions, UserStatus};
-use secrecy::{ExposeSecret, SecretString};
+use iggy_common::{Permissions, UserStatus};
use std::collections::BTreeMap;
use std::fmt::Display;
use tracing::{debug, error, info};
@@ -147,11 +148,12 @@ impl SystemState {
if !root_exists {
info!("No users found, creating the root user...");
let root = create_root_user();
- let command = CreateUser {
- username: root.username.clone(),
- password: SecretString::from(root.password.clone()),
- status: root.status,
- permissions: root.permissions.clone(),
+ let command = CreateUserRequest {
+ username: WireName::new(root.username.clone())
+ .expect("root username must be valid"),
+ password: root.password.clone(),
+ status: root.status.as_code(),
+ permissions: root.permissions.as_ref().map(domain_permissions_to_wire),
};
state
.apply(0, &EntryCommand::CreateUser(CreateUserWithId {
@@ -189,10 +191,9 @@ impl SystemState {
EntryCommand::CreateStream(command) => {
info!("Creating stream: {command:?}");
let stream_id = command.stream_id;
- let command = command.command;
let stream = StreamState {
id: stream_id,
- name: command.name.clone(),
+ name: command.command.name.to_string(),
topics: BTreeMap::new(),
created_at: entry.timestamp,
};
@@ -203,7 +204,7 @@ impl SystemState {
let stream = streams
.get_mut(&stream_id)
.unwrap_or_else(|| panic!("{}", format!("Stream: {stream_id} not found")));
- stream.name = command.name;
+ stream.name = command.name.to_string();
}
EntryCommand::DeleteStream(command) => {
let stream_id = find_stream_id(&streams, &command.stream_id);
@@ -214,7 +215,6 @@ impl SystemState {
streams
.get(&stream_id)
.unwrap_or_else(|| panic!("{}", format!("Stream: {stream_id} not found")));
- // It only affects the segments which are not part of the state
}
EntryCommand::CreateTopic(command) => {
let stream_id = find_stream_id(&streams, &command.command.stream_id);
@@ -222,19 +222,25 @@ impl SystemState {
.get_mut(&stream_id)
.unwrap_or_else(|| panic!("{}", format!("Stream: {stream_id} not found")));
let topic_id = command.topic_id;
- let command = command.command;
+ let wire = command.command;
let topic = TopicState {
id: topic_id,
- name: command.name,
+ name: wire.name.to_string(),
consumer_groups: BTreeMap::new(),
- compression_algorithm: command.compression_algorithm,
- message_expiry: command.message_expiry,
- max_topic_size: command.max_topic_size,
- replication_factor: command.replication_factor,
+ compression_algorithm: CompressionAlgorithm::from_code(
+ wire.compression_algorithm,
+ )?,
+ message_expiry: IggyExpiry::from(wire.message_expiry),
+ max_topic_size: MaxTopicSize::from(wire.max_topic_size),
+ replication_factor: if wire.replication_factor == 0 {
+ None
+ } else {
+ Some(wire.replication_factor)
+ },
created_at: entry.timestamp,
- partitions: if command.partitions_count > 0 {
+ partitions: if wire.partitions_count > 0 {
let mut partitions = BTreeMap::new();
- for i in 0..command.partitions_count {
+ for i in 0..wire.partitions_count {
partitions.insert(
i,
PartitionState {
@@ -260,11 +266,16 @@ impl SystemState {
.topics
.get_mut(&topic_id)
.unwrap_or_else(|| panic!("{}", format!("Topic: {topic_id} not found")));
- topic.name = command.name;
- topic.compression_algorithm = command.compression_algorithm;
- topic.message_expiry = command.message_expiry;
- topic.max_topic_size = command.max_topic_size;
- topic.replication_factor = command.replication_factor;
+ topic.name = command.name.to_string();
+ topic.compression_algorithm =
+ CompressionAlgorithm::from_code(command.compression_algorithm)?;
+ topic.message_expiry = IggyExpiry::from(command.message_expiry);
+ topic.max_topic_size = MaxTopicSize::from(command.max_topic_size);
+ topic.replication_factor = if command.replication_factor == 0 {
+ None
+ } else {
+ Some(command.replication_factor)
+ };
}
EntryCommand::DeleteTopic(command) => {
let stream_id = find_stream_id(&streams, &command.stream_id);
@@ -284,7 +295,6 @@ impl SystemState {
.topics
.get(&topic_id)
.unwrap_or_else(|| panic!("{}", format!("Topic: {topic_id} not found")));
- // It only affects the segments which are not part of the state
}
EntryCommand::CreatePartitions(command) => {
let stream_id = find_stream_id(&streams, &command.stream_id);
@@ -363,24 +373,22 @@ impl SystemState {
.unwrap_or_else(|| {
panic!("{}", format!("Partition {partition_id} not found."))
});
-
- // State is not affected by the delete segments
}
EntryCommand::CreateConsumerGroup(command) => {
let consumer_group_id = command.group_id;
- let command = command.command;
- let stream_id = find_stream_id(&streams, &command.stream_id);
+ let wire = command.command;
+ let stream_id = find_stream_id(&streams, &wire.stream_id);
let stream = streams
.get_mut(&stream_id)
.unwrap_or_else(|| panic!("{}", format!("Stream: {stream_id} not found")));
- let topic_id = find_topic_id(&stream.topics, &command.topic_id);
+ let topic_id = find_topic_id(&stream.topics, &wire.topic_id);
let topic = stream
.topics
.get_mut(&topic_id)
.unwrap_or_else(|| panic!("{}", format!("Topic: {topic_id} not found")));
let consumer_group = ConsumerGroupState {
id: consumer_group_id,
- name: command.name,
+ name: wire.name.to_string(),
};
topic
.consumer_groups
@@ -402,14 +410,17 @@ impl SystemState {
}
EntryCommand::CreateUser(command) => {
let user_id = command.user_id;
- let command = command.command;
+ let wire = command.command;
let user = UserState {
id: user_id,
- username: command.username,
- password_hash: command.password.expose_secret().to_owned(), // This is already hashed
- status: command.status,
+ username: wire.username.to_string(),
+ password_hash: wire.password, // already hashed at write time
+ status: UserStatus::from_code(wire.status)?,
created_at: entry.timestamp,
- permissions: command.permissions,
+ permissions: wire
+ .permissions
+ .as_ref()
+ .map(wire_permissions_to_permissions),
personal_access_tokens: AHashMap::new(),
};
users.insert(user.id, user);
@@ -420,10 +431,10 @@ impl SystemState {
.get_mut(&user_id)
.unwrap_or_else(|| panic!("{}", format!("User: {user_id} not found")));
if let Some(username) = &command.username {
- user.username.clone_from(username);
+ user.username = username.to_string();
}
- if let Some(status) = &command.status {
- user.status = *status;
+ if let Some(status) = command.status {
+ user.status = UserStatus::from_code(status)?;
}
}
EntryCommand::DeleteUser(command) => {
@@ -435,32 +446,27 @@ impl SystemState {
let user = users
.get_mut(&user_id)
.unwrap_or_else(|| panic!("{}", format!("User: {user_id} not found")));
- user.password_hash = command.new_password.expose_secret().to_owned() // This is already hashed
+ user.password_hash = command.new_password; // already hashed at write time
}
EntryCommand::UpdatePermissions(command) => {
let user_id = find_user_id(&users, &command.user_id);
let user = users
.get_mut(&user_id)
.unwrap_or_else(|| panic!("{}", format!("User: {user_id} not found")));
- user.permissions = command.permissions;
+ user.permissions = command
+ .permissions
+ .as_ref()
+ .map(wire_permissions_to_permissions);
}
EntryCommand::CreatePersonalAccessToken(command) => {
let token_hash = command.hash;
- let user_id = find_user_id(
- &users,
- &entry.user_id.try_into().error(|e: &IggyError| {
- format!(
- "{COMPONENT} (error: {e}) - failed to find user, user ID: {}",
- entry.user_id
- )
- })?,
- );
+ let user_id = find_user_id(&users, &WireIdentifier::numeric(entry.user_id));
let user = users
.get_mut(&user_id)
.unwrap_or_else(|| panic!("{}", format!("User: {user_id} not found")));
let expiry_at = PersonalAccessToken::calculate_expiry_at(
entry.timestamp,
- command.command.expiry,
+ IggyExpiry::from(command.command.expiry),
);
if let Some(expiry_at) = expiry_at
&& expiry_at.as_micros() <= IggyTimestamp::now().as_micros()
@@ -469,29 +475,22 @@ impl SystemState {
continue;
}
+ let name = command.command.name.to_string();
user.personal_access_tokens.insert(
- command.command.name.clone(),
+ name.clone(),
PersonalAccessTokenState {
- name: command.command.name,
+ name,
token_hash,
expiry_at,
},
);
}
EntryCommand::DeletePersonalAccessToken(command) => {
- let user_id = find_user_id(
- &users,
- &entry.user_id.try_into().error(|e: &IggyError| {
- format!(
- "{COMPONENT} (error: {e}) - failed to find user, user ID: {}",
- entry.user_id
- )
- })?,
- );
+ let user_id = find_user_id(&users, &WireIdentifier::numeric(entry.user_id));
let user = users
.get_mut(&user_id)
.unwrap_or_else(|| panic!("{}", format!("User: {user_id} not found")));
- user.personal_access_tokens.remove(&command.name);
+ user.personal_access_tokens.remove(command.name.as_str());
}
}
}
@@ -504,37 +503,29 @@ impl SystemState {
}
}
-fn find_stream_id(streams: &BTreeMap<u32, StreamState>, stream_id: &Identifier) -> u32 {
- match stream_id.kind {
- IdKind::Numeric => stream_id
- .get_u32_value()
- .unwrap_or_else(|_| panic!("{}", format!("Invalid stream ID: {stream_id}"))),
- IdKind::String => {
- let name = stream_id
- .get_cow_str_value()
- .unwrap_or_else(|_| panic!("{}", format!("Invalid stream name: {stream_id}")));
+fn find_stream_id(streams: &BTreeMap<u32, StreamState>, stream_id: &WireIdentifier) -> u32 {
+ match stream_id {
+ WireIdentifier::Numeric(id) => *id,
+ WireIdentifier::String(name) => {
+ let name = name.as_str();
let stream = streams
.values()
.find(|s| s.name == name)
- .unwrap_or_else(|| panic!("{}", format!("Stream: {name} not found")));
+ .unwrap_or_else(|| panic!("Stream: {name} not found"));
stream.id
}
}
}
-fn find_topic_id(topics: &BTreeMap<u32, TopicState>, topic_id: &Identifier) -> u32 {
- match topic_id.kind {
- IdKind::Numeric => topic_id
- .get_u32_value()
- .unwrap_or_else(|_| panic!("{}", format!("Invalid topic ID: {topic_id}"))),
- IdKind::String => {
- let name = topic_id
- .get_cow_str_value()
- .unwrap_or_else(|_| panic!("{}", format!("Invalid topic name: {topic_id}")));
+fn find_topic_id(topics: &BTreeMap<u32, TopicState>, topic_id: &WireIdentifier) -> u32 {
+ match topic_id {
+ WireIdentifier::Numeric(id) => *id,
+ WireIdentifier::String(name) => {
+ let name = name.as_str();
let topic = topics
.values()
.find(|s| s.name == name)
- .unwrap_or_else(|| panic!("{}", format!("Topic: {name} not found")));
+ .unwrap_or_else(|| panic!("Topic: {name} not found"));
topic.id
}
}
@@ -542,38 +533,30 @@ fn find_topic_id(topics: &BTreeMap<u32, TopicState>, topic_id: &Identifier) -> u
fn find_consumer_group_id(
groups: &BTreeMap<u32, ConsumerGroupState>,
- group_id: &Identifier,
+ group_id: &WireIdentifier,
) -> u32 {
- match group_id.kind {
- IdKind::Numeric => group_id
- .get_u32_value()
- .unwrap_or_else(|_| panic!("{}", format!("Invalid group ID: {group_id}"))),
- IdKind::String => {
- let name = group_id
- .get_cow_str_value()
- .unwrap_or_else(|_| panic!("{}", format!("Invalid group name: {group_id}")));
+ match group_id {
+ WireIdentifier::Numeric(id) => *id,
+ WireIdentifier::String(name) => {
+ let name = name.as_str();
let group = groups
.values()
.find(|s| s.name == name)
- .unwrap_or_else(|| panic!("{}", format!("Consumer group: {name} not found")));
+ .unwrap_or_else(|| panic!("Consumer group: {name} not found"));
group.id
}
}
}
-fn find_user_id(users: &AHashMap<u32, UserState>, user_id: &Identifier) -> u32 {
- match user_id.kind {
- IdKind::Numeric => user_id
- .get_u32_value()
- .unwrap_or_else(|_| panic!("{}", format!("Invalid user ID: {user_id}"))),
- IdKind::String => {
- let username = user_id
- .get_cow_str_value()
- .unwrap_or_else(|_| panic!("{}", format!("Invalid username: {user_id}")));
+fn find_user_id(users: &AHashMap<u32, UserState>, user_id: &WireIdentifier) -> u32 {
+ match user_id {
+ WireIdentifier::Numeric(id) => *id,
+ WireIdentifier::String(name) => {
+ let name = name.as_str();
let user = users
.values()
- .find(|s| s.username == username)
- .unwrap_or_else(|| panic!("{}", format!("User: {username} not found")));
+ .find(|s| s.username == name)
+ .unwrap_or_else(|| panic!("User: {name} not found"));
user.id
}
}
diff --git a/core/simulator/src/client.rs b/core/simulator/src/client.rs
index 2d64d0f40..4d23affff 100644
--- a/core/simulator/src/client.rs
+++ b/core/simulator/src/client.rs
@@ -16,14 +16,14 @@
// under the License.
use bytes::Bytes;
-use iggy_binary_protocol::{Message, Operation, RequestHeader};
+use iggy_binary_protocol::requests::streams::{CreateStreamRequest, DeleteStreamRequest};
+use iggy_binary_protocol::{
+ Message, Operation, RequestHeader, WireEncode, WireIdentifier, WireName,
+};
use iggy_common::send_messages2::{
IggyMessage2, IggyMessage2Header, IggyMessages2, SendMessages2Owned,
};
-use iggy_common::{
- BytesSerializable, Identifier, create_stream::CreateStream, delete_stream::DeleteStream,
- sharding::IggyNamespace,
-};
+use iggy_common::sharding::IggyNamespace;
use iobuf::Owned;
use std::cell::Cell;
@@ -48,22 +48,24 @@ impl SimClient {
current
}
+ /// # Panics
+ /// Panics if the stream name is not a valid wire name.
pub fn create_stream(&self, name: &str) -> Message<RequestHeader> {
- let create_stream = CreateStream {
- name: name.to_string(),
+ let wire = CreateStreamRequest {
+ name: WireName::new(name).expect("stream name must be valid"),
};
- let payload = create_stream.to_bytes();
+ let payload = wire.to_bytes();
self.build_request(Operation::CreateStream, &payload)
}
/// # Panics
- /// Panics if the stream name cannot be converted to an `Identifier`.
+ /// Panics if the stream name cannot be converted to a `WireIdentifier`.
pub fn delete_stream(&self, name: &str) -> Message<RequestHeader> {
- let delete_stream = DeleteStream {
- stream_id: Identifier::named(name).unwrap(),
+ let wire = DeleteStreamRequest {
+ stream_id: WireIdentifier::named(name).expect("stream name must be valid"),
};
- let payload = delete_stream.to_bytes();
+ let payload = wire.to_bytes();
self.build_request(Operation::DeleteStream, &payload)
}