| // Licensed to the Apache Software Foundation (ASF) under one | |
| // or more contributor license agreements. See the NOTICE file | |
| // distributed with this work for additional information | |
| // regarding copyright ownership. The ASF licenses this file | |
| // to you under the Apache License, Version 2.0 (the | |
| // "License"); you may not use this file except in compliance | |
| // with the License. You may obtain a copy of the License at | |
| // | |
| // http://www.apache.org/licenses/LICENSE-2.0 | |
| // | |
| // Unless required by applicable law or agreed to in writing, | |
| // software distributed under the License is distributed on an | |
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| // KIND, either express or implied. See the License for the | |
| // specific language governing permissions and limitations | |
| // under the License. | |
| use bytes::{Bytes, BytesMut}; | |
| use iggy_binary_protocol::batch::BatchProducer; | |
| use iggy_binary_protocol::codes::{ | |
| CANCEL_DEFERRED_REQUEST_CODE, FETCH_MESSAGES_CODE, GET_STREAM_CODE, POLL_MESSAGES_CODE, | |
| POLL_MESSAGES_DEFERRED_CODE, | |
| }; | |
| use iggy_binary_protocol::primitives::consumer::WireConsumer; | |
| use iggy_binary_protocol::primitives::partition_history::PartitionContext; | |
| use iggy_binary_protocol::requests::consumer_groups::{ | |
| CreateConsumerGroupRequest, DeleteConsumerGroupRequest, JoinConsumerGroupRequest, | |
| LeaveConsumerGroupRequest, | |
| }; | |
| use iggy_binary_protocol::requests::consumer_offsets::{ | |
| DeleteConsumerOffsetRequest, StoreConsumerOffsetRequest, | |
| }; | |
| use iggy_binary_protocol::requests::messages::{ | |
| DeferredPollMessagesRequest, FetchMessagesRequest, FetchMessagesTarget, PollMessagesRequest, | |
| RawMessage, SendMessagesEncoder, | |
| }; | |
| use iggy_binary_protocol::requests::partitions::{ | |
| CreatePartitionsRequest, DeletePartitionsRequest, | |
| }; | |
| use iggy_binary_protocol::requests::personal_access_tokens::{ | |
| CreatePersonalAccessTokenRequest as WireCreatePersonalAccessTokenRequest, | |
| DeletePersonalAccessTokenRequest as WireDeletePersonalAccessTokenRequest, | |
| }; | |
| use iggy_binary_protocol::requests::segments::DeleteSegmentsRequest; | |
| use iggy_binary_protocol::requests::streams::{ | |
| CreateStreamRequest, DeleteStreamRequest, GetStreamRequest, WRAPPED_STREAM_KEY_LENGTH, | |
| }; | |
| use iggy_binary_protocol::requests::system::{ | |
| BindSessionRequest, ResourceTarget, SessionIdentity, UpdateResourceRequest, | |
| }; | |
| use iggy_binary_protocol::requests::topics::{CreateTopicRequest, DeleteTopicRequest}; | |
| use iggy_binary_protocol::requests::users::login_register::BindSecret; | |
| use iggy_binary_protocol::requests::users::login_register::{CredentialProof, RegisterRequest}; | |
| use iggy_binary_protocol::requests::users::{ | |
| ChangePasswordRequest, CreateUserRequest, DeleteUserRequest, LoginRegisterRequest, | |
| UpdatePermissionsRequest, | |
| }; | |
| use iggy_binary_protocol::{ | |
| AckLevel, ClientVersionInfo, IGGY_PROTOCOL_VERSION, Operation, RoutedRequestHeader, WireEncode, | |
| WireIdentifier, WireName, WireOptions, WirePartitioning, WirePermissions, WirePollingStrategy, | |
| }; | |
| use iggy_common::DEFAULT_POLL_MAX_BYTES; | |
| use iggy_common::wire_conversions::resource_options_to_wire; | |
| use iggy_common::{ | |
| HeaderKey, HeaderValue, OptionKey, OptionValue, OptionsPatch, OptionsProvenance, | |
| ResourceOptions, StreamUpdateOptions, TopicUpdateOptions, UserStatus, UserUpdateOptions, | |
| critical_keys_marker, | |
| }; | |
| use metadata::stm::user::{ | |
| ChangePasswordRequest as ResolvedChangePasswordRequest, CreatePersonalAccessTokenRequest, | |
| DeletePersonalAccessTokenRequest, ROOT_USER_ACCESS_REVISION, ROOT_USER_CREATED_AT_MICROS, User, | |
| }; | |
| use secrecy::SecretString; | |
| use server_common::sharding::{IggyNamespace, METADATA_GROUP}; | |
| use server_common::{Message, iobuf::Owned}; | |
| use std::cell::{Cell, RefCell}; | |
| use std::collections::BTreeMap; | |
| /// Key-encryption key [`SIM_STREAM_WRAP_SET`] is sealed under. | |
| pub const SIM_STREAM_KEK: &str = "c2ltdWxhdG9yLXN0cmVhbS1rZXktZW5jcnlwdGlvbi0="; | |
| /// Key-encryption key [`SIM_ROTATED_WRAP_SET`] is sealed under. | |
| pub const SIM_ROTATED_KEK: &str = "c2ltdWxhdG9yLXJvdGF0ZWQta2V5LWVuY3J5cHRpb24="; | |
| /// Client stream key both fixed wrap sets hold. | |
| pub const SIM_STREAM_KEY: [u8; 32] = [0x51; 32]; | |
| /// [`SIM_STREAM_KEY`] wrapped under [`SIM_STREAM_KEK`]. Precomputed, since a | |
| /// fresh wrap draws its nonce from the OS generator and breaks seeded replay. | |
| pub const SIM_STREAM_WRAP_SET: [u8; WRAPPED_STREAM_KEY_LENGTH] = [ | |
| 0x01, 0x01, 0xd5, 0x40, 0xc9, 0x77, 0x57, 0xd4, 0x39, 0x46, 0xec, 0x07, 0x1d, 0xb1, 0x3d, 0xfb, | |
| 0x78, 0x80, 0x18, 0xfc, 0xae, 0x2b, 0xb8, 0x25, 0x96, 0x8a, 0xd7, 0x9d, 0x65, 0xbc, 0x41, 0x08, | |
| 0xd6, 0x1d, 0xed, 0x5e, 0x85, 0x01, 0x54, 0xcd, 0x8d, 0x17, 0x34, 0x16, 0x9f, 0x19, 0x6e, 0xc6, | |
| 0xf7, 0xdc, 0x23, 0xcb, 0x1d, 0x9e, 0x04, 0x7a, 0xc7, 0xa6, 0xbf, 0x8b, 0xf2, 0x81, 0x42, 0x32, | |
| 0xa9, 0x58, 0xd0, 0x29, 0x44, 0x35, 0x31, 0x19, 0x21, 0x47, 0x46, 0xe2, 0x94, 0xc5, | |
| ]; | |
| /// [`SIM_STREAM_KEY`] wrapped under [`SIM_ROTATED_KEK`], the set a rewrap stores. | |
| pub const SIM_ROTATED_WRAP_SET: [u8; WRAPPED_STREAM_KEY_LENGTH] = [ | |
| 0x01, 0x01, 0x28, 0x05, 0x68, 0xfc, 0x9e, 0xaa, 0x81, 0x5f, 0x96, 0x5f, 0x30, 0x69, 0xfd, 0x3f, | |
| 0x3c, 0x50, 0xd8, 0xf5, 0x48, 0xdb, 0x49, 0xb4, 0x0e, 0x11, 0xbb, 0xd0, 0x66, 0x1e, 0xb3, 0xff, | |
| 0x95, 0xe5, 0x24, 0x1e, 0x4a, 0xb0, 0x69, 0x04, 0xee, 0x40, 0x43, 0xe5, 0x36, 0x81, 0x09, 0xf1, | |
| 0x16, 0x43, 0xa3, 0x11, 0xf3, 0x53, 0xcd, 0x76, 0x8d, 0x4a, 0xff, 0x95, 0xc4, 0xbd, 0xc8, 0x84, | |
| 0x41, 0x84, 0xf2, 0x31, 0x01, 0x37, 0x31, 0x19, 0x21, 0x47, 0x46, 0xe2, 0x94, 0xc5, | |
| ]; | |
| // TODO: Proper client which implements the full client SDK API | |
| pub struct SimClient { | |
| client_id: u128, | |
| /// Monotonic `1, 2, 3, …` request ids shared by every replicated op, | |
| /// metadata and partition alike, which is what the SDKs send. One sequence | |
| /// also issues each id exactly once per client, so a delayed or duplicated | |
| /// partition reply can never carry the `(client, request)` key of a live | |
| /// metadata entry in the auditor's map. See [`SimClient::next_request_id`]. | |
| request_counter: Cell<u64>, | |
| /// Deterministic per-message id source for produced messages. The real SDK | |
| /// mints a random UUID for a zero message id before encoding; that mint is | |
| /// unseeded, so under the deterministic executor a produce's replicated | |
| /// body bytes (and their checksums) would differ run to run, silently | |
| /// breaking seeded replay. Stamping a deterministic id here keeps the body | |
| /// a pure function of the seed. See [`SimClient::next_message_id`]. | |
| message_counter: Cell<u64>, | |
| session: Cell<u64>, | |
| partition_contexts: RefCell<BTreeMap<IggyNamespace, PartitionContext>>, | |
| /// Whether this client talks to the server's real dispatch layer, which | |
| /// changes what a PAT request must contain. | |
| /// | |
| /// A real client sends `[name][expiry]` and the server mints the token and its | |
| /// hash in `maybe_rewrite_pat_request`, rewriting the request into the | |
| /// replicated form before consensus sees it. The raw path has no dispatch layer | |
| /// and so no rewrite, so a request submitted there must arrive already | |
| /// replicated. Sessions split the same way (`register` raw, `login` shell); | |
| /// this is the one op family whose BODY differs rather than its envelope. Set | |
| /// by `Simulator::shell_login_via`, so it follows the path the client took. | |
| shell_wire: Cell<bool>, | |
| } | |
| impl SimClient { | |
| #[must_use] | |
| pub const fn new(client_id: u128) -> Self { | |
| Self { | |
| client_id, | |
| request_counter: Cell::new(0), | |
| message_counter: Cell::new(0), | |
| session: Cell::new(0), | |
| partition_contexts: RefCell::new(BTreeMap::new()), | |
| shell_wire: Cell::new(false), | |
| } | |
| } | |
| /// Mark this client as talking to the real dispatch layer, so PAT requests | |
| /// carry the client wire shape rather than the replicated one. See | |
| /// [`SimClient::shell_wire`]. | |
| pub fn set_shell_wire(&self) { | |
| self.shell_wire.set(true); | |
| } | |
| /// Put this client back on the replicated wire shape. | |
| /// | |
| /// The inverse exists because the flip is otherwise permanent and silent: a | |
| /// client moved to the client wire shape by mistake stops covering the | |
| /// replicated PAT path for the rest of the run, with nothing failing. | |
| pub fn clear_shell_wire(&self) { | |
| self.shell_wire.set(false); | |
| } | |
| /// Whether this client talks the client wire shape (see | |
| /// [`SimClient::set_shell_wire`]). | |
| #[must_use] | |
| pub const fn shell_wire(&self) -> bool { | |
| self.shell_wire.get() | |
| } | |
| #[must_use] | |
| pub const fn client_id(&self) -> u128 { | |
| self.client_id | |
| } | |
| /// Discovery updates affect new requests; retained messages keep their captured context. | |
| pub fn set_partition_context(&self, namespace: IggyNamespace, context: PartitionContext) { | |
| self.partition_contexts | |
| .borrow_mut() | |
| .insert(namespace, context); | |
| } | |
| fn stamp_partition_context(&self, header: &mut RoutedRequestHeader) { | |
| if let Some(context) = self | |
| .partition_contexts | |
| .borrow() | |
| .get(&IggyNamespace::from_raw(header.group)) | |
| { | |
| header.partition_incarnation = context.incarnation; | |
| header.owner_generation = context.owner_generation; | |
| header.minimum_metadata_op = context.metadata_op; | |
| } | |
| } | |
| /// Next deterministic, non-zero, cross-client-unique message id, standing | |
| /// in for the SDK's `id: 0` / server-side random UUID mint so a produce's | |
| /// replicated bytes are a pure function of the seed. The `client_id` fills | |
| /// the high 64 bits (ids stay disjoint across clients, whose ids are minted | |
| /// small) and a monotonic counter fills the low 64 bits (starts at 1, so | |
| /// the id is never 0 and never re-triggers the server's random mint). See | |
| /// [`SimClient::message_counter`]. | |
| fn next_message_id(&self) -> u128 { | |
| let seq = self.message_counter.get() + 1; | |
| self.message_counter.set(seq); | |
| (self.client_id << 64) | u128::from(seq) | |
| } | |
| /// Bind the session assigned by the consensus layer after registration. | |
| /// | |
| /// # Panics | |
| /// Panics if `session` is 0. | |
| pub fn bind_session(&self, session: u64) { | |
| assert!(session > 0, "bind_session: session must be > 0"); | |
| self.session.set(session); | |
| } | |
| /// Assign the wire request id for the next replicated op. | |
| /// | |
| /// Every replicated op advances one counter, metadata and partition alike, | |
| /// which is what the SDKs send: a partition op needs its own number for a | |
| /// retry to be recognisable, and the ids it spends cost the metadata plane | |
| /// nothing, because `ClientTable` admits anything above the watermark | |
| /// (`client_table.rs`: "There is no `RequestGap`"). | |
| /// | |
| /// The server ignores the id of a `NonReplicated` read. The SDK still spends | |
| /// one per bound read, so a link can match each reply to its request, and | |
| /// [`Self::poll_messages_at`] does the same. | |
| fn next_request_id(&self) -> u64 { | |
| let next = self.request_counter.get() + 1; | |
| self.request_counter.set(next); | |
| next | |
| } | |
| pub(crate) fn session_id(&self) -> u64 { | |
| let s = self.session.get(); | |
| assert!( | |
| s > 0, | |
| "session not bound — call register() + bind_session() first" | |
| ); | |
| s | |
| } | |
| fn bind_secret(&self) -> [u8; consensus::client_table::BIND_SECRET_BYTES] { | |
| let mut secret = [0; consensus::client_table::BIND_SECRET_BYTES]; | |
| secret[..16].copy_from_slice(&self.client_id.to_le_bytes()); | |
| secret[16..].copy_from_slice(&self.client_id.to_le_bytes()); | |
| secret | |
| } | |
| /// # Panics | |
| /// | |
| /// Panics if the fixed simulator SDK name or version is invalid. | |
| pub fn bind_session_request(&self, metadata_watermark: u64) -> Message<RoutedRequestHeader> { | |
| let request = BindSessionRequest { | |
| version_info: ClientVersionInfo { | |
| protocol_version: IGGY_PROTOCOL_VERSION, | |
| sdk_name: WireName::new("simulator").expect("valid SDK name"), | |
| sdk_version: WireName::new("1.0.0").expect("valid SDK version"), | |
| }, | |
| identity: SessionIdentity { | |
| client_id: self.client_id, | |
| session: self.session_id(), | |
| metadata_watermark, | |
| }, | |
| bind_secret: BindSecret::new(Box::new(self.bind_secret())), | |
| }; | |
| self.non_replicated_request( | |
| iggy_binary_protocol::codes::BIND_SESSION_CODE, | |
| METADATA_GROUP, | |
| &request.to_bytes(), | |
| self.request_counter.get(), | |
| ) | |
| } | |
| /// Build a `Register` request for this client. | |
| /// | |
| /// Register uses `session=0, request=0` per the protocol spec. | |
| /// The consensus layer assigns a session on commit. | |
| /// | |
| /// # Panics | |
| /// Panics if the register request buffer is invalid. | |
| #[allow(clippy::cast_possible_truncation)] | |
| pub fn register(&self) -> Message<RoutedRequestHeader> { | |
| let header_size = std::mem::size_of::<RoutedRequestHeader>(); | |
| let registration = RegisterRequest { | |
| credential: CredentialProof::account( | |
| ROOT_USER_CREATED_AT_MICROS, | |
| ROOT_USER_ACCESS_REVISION, | |
| ), | |
| bind_verifier: consensus::client_table::bind_verifier( | |
| self.client_id, | |
| 0, | |
| &self.bind_secret(), | |
| ), | |
| } | |
| .to_bytes(); | |
| let header = RoutedRequestHeader { | |
| command: iggy_binary_protocol::Command::Request, | |
| operation: Operation::Register, | |
| size: (header_size + registration.len()) as u32, | |
| client: self.client_id, | |
| session: 0, | |
| request: 0, | |
| // Register is a vsr-reserved op: the shard router picks its | |
| // target by comparing this against the metadata consensus | |
| // group, not by op class. | |
| group: METADATA_GROUP, | |
| ..Default::default() | |
| }; | |
| let header_bytes = bytemuck::bytes_of(&header); | |
| let mut buffer = header_bytes.to_vec(); | |
| buffer.extend_from_slice(®istration); | |
| Message::try_from(Owned::<4096>::copy_from_slice(&buffer)) | |
| .expect("register request must be valid") | |
| } | |
| /// Build a credentialed login-register request: the shell-mode | |
| /// counterpart of [`SimClient::register`]. | |
| /// | |
| /// Same `Register` / `session=0` / `request=0` envelope, but the body | |
| /// carries the `ClientVersionInfo` prefix plus username/password that | |
| /// `handle_login_register_request` verifies against the seeded root | |
| /// user before the consensus layer assigns the session on commit. Used | |
| /// only on the dispatch-shell path (the raw fast path uses `register`). | |
| /// | |
| /// # Panics | |
| /// Panics if a credential exceeds the wire name/secret bounds or the | |
| /// request buffer is invalid. | |
| #[allow(clippy::cast_possible_truncation)] | |
| pub fn login(&self, username: &str, password: &str) -> Message<RoutedRequestHeader> { | |
| let body = LoginRegisterRequest { | |
| version_info: ClientVersionInfo { | |
| protocol_version: IGGY_PROTOCOL_VERSION, | |
| sdk_name: WireName::new("sim-sdk").expect("sim sdk name is valid"), | |
| sdk_version: WireName::new("1.0.0").expect("sim sdk version is valid"), | |
| }, | |
| username: WireName::new(username).expect("login username is a valid wire name"), | |
| bind_secret: BindSecret::new(Box::new(self.bind_secret())), | |
| password: SecretString::from(password.to_owned()), | |
| client_context: None, | |
| } | |
| .to_bytes(); | |
| let header_size = std::mem::size_of::<RoutedRequestHeader>(); | |
| let total_size = header_size + body.len(); | |
| let header = RoutedRequestHeader { | |
| command: iggy_binary_protocol::Command::Request, | |
| operation: Operation::Register, | |
| size: total_size as u32, | |
| client: self.client_id, | |
| session: 0, | |
| request: 0, | |
| group: METADATA_GROUP, | |
| ..Default::default() | |
| }; | |
| let mut buffer = Vec::with_capacity(total_size); | |
| buffer.extend_from_slice(bytemuck::bytes_of(&header)); | |
| buffer.extend_from_slice(&body); | |
| Message::try_from(Owned::<4096>::copy_from_slice(&buffer)) | |
| .expect("login request must be valid") | |
| } | |
| /// Tear down this client's bound session. | |
| /// | |
| /// Replicates through the metadata plane like any other session op, so it | |
| /// carries the bound session and a metadata request id and needs no body. A | |
| /// logout to a BACKUP is what produces `ForwardLogout`: the backup owns the | |
| /// connection but not the log, so it asks the primary to commit the teardown | |
| /// and answers once `ForwardLogoutResult` returns. | |
| #[must_use] | |
| pub fn logout(&self) -> Message<RoutedRequestHeader> { | |
| self.build_request(Operation::Logout, &[]) | |
| } | |
| /// # Panics | |
| /// Panics if the stream name is not a valid wire name. | |
| pub fn create_stream(&self, name: &str) -> Message<RoutedRequestHeader> { | |
| let wire = CreateStreamRequest { | |
| name: WireName::new(name).expect("stream name must be valid"), | |
| options: WireOptions::empty(), | |
| }; | |
| let payload = wire.to_bytes(); | |
| self.build_request(Operation::CreateStream, &payload) | |
| } | |
| /// A `CreateStream` already in the replicated form an edge produces: the | |
| /// fixed [`SIM_STREAM_WRAP_SET`] and the critical marker naming it. The | |
| /// dispatch shell refuses a client-sent wrap set, so only the raw path | |
| /// commits one. | |
| /// | |
| /// # Panics | |
| /// Panics if the stream name is not a valid wire name. | |
| pub fn create_keyed_stream(&self, name: &str) -> Message<RoutedRequestHeader> { | |
| let options = ResourceOptions::from([ | |
| ( | |
| HeaderKey::from(OptionKey::EncryptionKeyWrapped), | |
| OptionValue::explicit( | |
| HeaderValue::try_from(SIM_STREAM_WRAP_SET.as_slice()) | |
| .expect("a wrap set fits a header value"), | |
| ), | |
| ), | |
| ( | |
| HeaderKey::from(OptionKey::CriticalKeys), | |
| OptionValue::explicit( | |
| critical_keys_marker(&[OptionKey::EncryptionKeyWrapped]) | |
| .expect("the wrapped key is a critical option"), | |
| ), | |
| ), | |
| ]); | |
| let wire = CreateStreamRequest { | |
| name: WireName::new(name).expect("stream name must be valid"), | |
| options: resource_options_to_wire(&options, OptionsProvenance::All) | |
| .expect("the keyed options fit a block"), | |
| }; | |
| self.build_request(Operation::CreateStream, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if the stream name cannot be converted to a `WireIdentifier`. | |
| pub fn delete_stream(&self, name: &str) -> Message<RoutedRequestHeader> { | |
| let wire = DeleteStreamRequest { | |
| stream_id: WireIdentifier::named(name).expect("stream name must be valid"), | |
| }; | |
| let payload = wire.to_bytes(); | |
| self.build_request(Operation::DeleteStream, &payload) | |
| } | |
| /// # Panics | |
| /// Panics if the new name or the existing stream name is not a valid | |
| /// `WireName`. | |
| pub fn update_stream(&self, stream: &str, new_name: &str) -> Message<RoutedRequestHeader> { | |
| let patch = StreamUpdateOptions { | |
| name: Some(new_name.to_owned()), | |
| ..StreamUpdateOptions::default() | |
| } | |
| .to_patch() | |
| .expect("stream name must be valid"); | |
| self.update_resource( | |
| ResourceTarget::Stream { | |
| stream_id: WireIdentifier::named(stream).expect("stream name must be valid"), | |
| }, | |
| patch, | |
| ) | |
| } | |
| /// # Panics | |
| /// Panics if `stream` or `name` is not a valid `WireName`. | |
| pub fn create_topic( | |
| &self, | |
| stream: &str, | |
| name: &str, | |
| partitions_count: u32, | |
| ) -> Message<RoutedRequestHeader> { | |
| self.create_topic_with_factor(stream, name, partitions_count, None) | |
| } | |
| /// [`Self::create_topic`] with an explicit replication factor; `None` | |
| /// leaves it to the server default. | |
| /// | |
| /// # Panics | |
| /// As [`Self::create_topic`]. | |
| pub fn create_topic_with_factor( | |
| &self, | |
| stream: &str, | |
| name: &str, | |
| partitions_count: u32, | |
| replication_factor: Option<u32>, | |
| ) -> Message<RoutedRequestHeader> { | |
| let wire = CreateTopicRequest { | |
| stream_id: WireIdentifier::named(stream).expect("stream name must be valid"), | |
| partitions_count, | |
| name: WireName::new(name).expect("topic name must be valid"), | |
| options: iggy_common::TopicCreateOptions { | |
| durability: iggy_common::Durability::Persisted, | |
| consumer_offset_durability: iggy_common::Durability::Persisted, | |
| replication_factor, | |
| ..Default::default() | |
| } | |
| .to_wire() | |
| .expect("valid simulator durability options"), | |
| }; | |
| self.build_request(Operation::CreateTopic, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if `stream` or `topic` is not a valid `WireName`, or `options` | |
| /// fail the client-side patch checks. | |
| pub fn update_topic( | |
| &self, | |
| stream: &str, | |
| topic: &str, | |
| options: &TopicUpdateOptions, | |
| ) -> Message<RoutedRequestHeader> { | |
| let patch = options.to_patch().expect("topic patch must be valid"); | |
| self.update_resource( | |
| ResourceTarget::Topic { | |
| stream_id: WireIdentifier::named(stream).expect("stream name must be valid"), | |
| topic_id: WireIdentifier::named(topic).expect("topic name must be valid"), | |
| }, | |
| patch, | |
| ) | |
| } | |
| /// # Panics | |
| /// Panics if `stream` or `topic` is not a valid `WireName`. | |
| pub fn delete_topic(&self, stream: &str, topic: &str) -> Message<RoutedRequestHeader> { | |
| let wire = DeleteTopicRequest { | |
| stream_id: WireIdentifier::named(stream).expect("stream name must be valid"), | |
| topic_id: WireIdentifier::named(topic).expect("topic name must be valid"), | |
| }; | |
| self.build_request(Operation::DeleteTopic, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if `stream` or `topic` is not a valid `WireName`. | |
| pub fn create_partitions( | |
| &self, | |
| stream: &str, | |
| topic: &str, | |
| partitions_count: u32, | |
| ) -> Message<RoutedRequestHeader> { | |
| let wire = CreatePartitionsRequest { | |
| stream_id: WireIdentifier::named(stream).expect("stream name must be valid"), | |
| topic_id: WireIdentifier::named(topic).expect("topic name must be valid"), | |
| partitions_count, | |
| }; | |
| self.build_request(Operation::CreatePartitions, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if `stream` or `topic` is not a valid `WireName`. | |
| pub fn delete_partitions( | |
| &self, | |
| stream: &str, | |
| topic: &str, | |
| partitions_count: u32, | |
| ) -> Message<RoutedRequestHeader> { | |
| let wire = DeletePartitionsRequest { | |
| stream_id: WireIdentifier::named(stream).expect("stream name must be valid"), | |
| topic_id: WireIdentifier::named(topic).expect("topic name must be valid"), | |
| partitions_count, | |
| }; | |
| self.build_request(Operation::DeletePartitions, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if `stream` or `topic` is not a valid `WireName`. | |
| pub fn delete_segments( | |
| &self, | |
| stream: &str, | |
| topic: &str, | |
| partition_id: u32, | |
| segments_count: u32, | |
| ) -> Message<RoutedRequestHeader> { | |
| let wire = DeleteSegmentsRequest { | |
| stream_id: WireIdentifier::named(stream).expect("stream name must be valid"), | |
| topic_id: WireIdentifier::named(topic).expect("topic name must be valid"), | |
| partition_id, | |
| segments_count, | |
| }; | |
| self.build_request(Operation::DeleteSegments, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if `stream`, `topic`, or `name` is not a valid `WireName`. | |
| pub fn create_consumer_group( | |
| &self, | |
| stream: &str, | |
| topic: &str, | |
| name: &str, | |
| ) -> Message<RoutedRequestHeader> { | |
| let wire = CreateConsumerGroupRequest { | |
| stream_id: WireIdentifier::named(stream).expect("stream name must be valid"), | |
| topic_id: WireIdentifier::named(topic).expect("topic name must be valid"), | |
| name: WireName::new(name).expect("consumer group name must be valid"), | |
| }; | |
| self.build_request(Operation::CreateConsumerGroup, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if any identifier is not a valid name. | |
| pub fn join_consumer_group( | |
| &self, | |
| stream: &str, | |
| topic: &str, | |
| group: &str, | |
| ) -> Message<RoutedRequestHeader> { | |
| let wire = JoinConsumerGroupRequest { | |
| stream_id: WireIdentifier::named(stream).expect("stream name must be valid"), | |
| topic_id: WireIdentifier::named(topic).expect("topic name must be valid"), | |
| group_id: WireIdentifier::named(group).expect("group name must be valid"), | |
| }; | |
| self.build_request(Operation::JoinConsumerGroup, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if any identifier is not a valid name. | |
| pub fn leave_consumer_group( | |
| &self, | |
| stream: &str, | |
| topic: &str, | |
| group: &str, | |
| ) -> Message<RoutedRequestHeader> { | |
| let wire = LeaveConsumerGroupRequest { | |
| stream_id: WireIdentifier::named(stream).expect("stream name must be valid"), | |
| topic_id: WireIdentifier::named(topic).expect("topic name must be valid"), | |
| group_id: WireIdentifier::named(group).expect("group name must be valid"), | |
| }; | |
| self.build_request(Operation::LeaveConsumerGroup, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if `stream`, `topic`, or `group` is not a valid `WireName`. | |
| pub fn delete_consumer_group( | |
| &self, | |
| stream: &str, | |
| topic: &str, | |
| group: &str, | |
| ) -> Message<RoutedRequestHeader> { | |
| let wire = DeleteConsumerGroupRequest { | |
| stream_id: WireIdentifier::named(stream).expect("stream name must be valid"), | |
| topic_id: WireIdentifier::named(topic).expect("topic name must be valid"), | |
| group_id: WireIdentifier::named(group).expect("group name must be valid"), | |
| }; | |
| self.build_request(Operation::DeleteConsumerGroup, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if `username` is not a valid `WireName`. | |
| pub fn create_user( | |
| &self, | |
| username: &str, | |
| password: &str, | |
| status: u8, | |
| ) -> Message<RoutedRequestHeader> { | |
| self.create_user_with_permissions(username, password, status, None) | |
| } | |
| /// # Panics | |
| /// Panics if `username` is not a valid `WireName`. | |
| pub fn create_user_with_permissions( | |
| &self, | |
| username: &str, | |
| password: &str, | |
| status: u8, | |
| permissions: Option<WirePermissions>, | |
| ) -> Message<RoutedRequestHeader> { | |
| let wire = CreateUserRequest { | |
| username: WireName::new(username).expect("username must be valid"), | |
| password: password.to_string(), | |
| status, | |
| permissions, | |
| options: WireOptions::empty(), | |
| }; | |
| self.build_request(Operation::CreateUser, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if `user` (existing username) or `new_username` (when | |
| /// provided) is not a valid `WireName`. | |
| pub fn update_user( | |
| &self, | |
| user: &str, | |
| new_username: Option<&str>, | |
| status: Option<UserStatus>, | |
| ) -> Message<RoutedRequestHeader> { | |
| let patch = UserUpdateOptions { | |
| username: new_username.map(ToOwned::to_owned), | |
| status, | |
| ..UserUpdateOptions::default() | |
| } | |
| .to_patch() | |
| .expect("username must be valid"); | |
| self.update_resource( | |
| ResourceTarget::User { | |
| user_id: WireIdentifier::named(user).expect("username must be valid"), | |
| }, | |
| patch, | |
| ) | |
| } | |
| fn update_resource( | |
| &self, | |
| target: ResourceTarget, | |
| patch: OptionsPatch, | |
| ) -> Message<RoutedRequestHeader> { | |
| let wire = UpdateResourceRequest { | |
| target, | |
| reset: patch.reset, | |
| options: patch.set, | |
| }; | |
| self.build_request(Operation::UpdateResource, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if `user` is not a valid `WireName`. | |
| pub fn delete_user(&self, user: &str) -> Message<RoutedRequestHeader> { | |
| let wire = DeleteUserRequest { | |
| user_id: WireIdentifier::named(user).expect("username must be valid"), | |
| }; | |
| self.build_request(Operation::DeleteUser, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if `user` is not a valid `WireName`. | |
| pub fn change_password( | |
| &self, | |
| user: &str, | |
| current_password: &str, | |
| new_password: &str, | |
| ) -> Message<RoutedRequestHeader> { | |
| let user_id = WireIdentifier::named(user).expect("username must be valid"); | |
| // See `create_personal_access_token` for why the shape depends on the path. | |
| if self.shell_wire.get() { | |
| let wire = ChangePasswordRequest { | |
| user_id, | |
| current_password: current_password.to_string(), | |
| new_password: new_password.to_string(), | |
| }; | |
| return self.build_request(Operation::ChangePassword, &wire.to_bytes()); | |
| } | |
| self.raw_change_password(user_id, None, current_password, new_password) | |
| } | |
| pub(crate) fn raw_change_password( | |
| &self, | |
| user_id: WireIdentifier, | |
| account: Option<&User>, | |
| current_password: &str, | |
| new_password: &str, | |
| ) -> Message<RoutedRequestHeader> { | |
| // Raw fixtures store their deterministic password value directly. | |
| let (user_id, access_revision, password_hash) = account.map_or_else( | |
| || (user_id, 0, String::new()), | |
| |account| { | |
| ( | |
| WireIdentifier::numeric(account.id), | |
| account.access_revision, | |
| if account.password_hash.as_ref() == current_password { | |
| new_password.to_owned() | |
| } else { | |
| String::new() | |
| }, | |
| ) | |
| }, | |
| ); | |
| let wire = ResolvedChangePasswordRequest { | |
| user_id, | |
| access_revision, | |
| password_hash, | |
| keep_session: true, | |
| }; | |
| self.build_request(Operation::ChangePassword, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if `user` is not a valid `WireName`. | |
| pub fn update_permissions(&self, user: &str) -> Message<RoutedRequestHeader> { | |
| let wire = UpdatePermissionsRequest { | |
| user_id: WireIdentifier::named(user).expect("username must be valid"), | |
| permissions: None, | |
| }; | |
| self.build_request(Operation::UpdatePermissions, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if `name` is not a valid `WireName`. | |
| pub fn create_personal_access_token( | |
| &self, | |
| name: &str, | |
| expiry: u64, | |
| ) -> Message<RoutedRequestHeader> { | |
| let name = WireName::new(name).expect("PAT name must be valid"); | |
| // Through dispatch, send what a real client sends: the server resolves the | |
| // acting user from the session and mints the token and its hash in | |
| // `maybe_rewrite_pat_request`, rewriting this into the replicated form | |
| // before consensus sees it. A client cannot produce that form, not knowing | |
| // the hash, so sending it here made every PAT request fail to decode. | |
| if self.shell_wire.get() { | |
| let wire = WireCreatePersonalAccessTokenRequest { name, expiry }; | |
| return self.build_request(Operation::CreatePersonalAccessToken, &wire.to_bytes()); | |
| } | |
| // Raw path: no dispatch layer, so no rewrite ever happens and the request | |
| // has to arrive already replicated. | |
| let wire = CreatePersonalAccessTokenRequest { | |
| user_id: 0, | |
| name, | |
| expiry, | |
| token_hash: [b'a'; 64], | |
| }; | |
| self.build_request(Operation::CreatePersonalAccessToken, &wire.to_bytes()) | |
| } | |
| /// # Panics | |
| /// Panics if `name` is not a valid `WireName`. | |
| pub fn delete_personal_access_token(&self, name: &str) -> Message<RoutedRequestHeader> { | |
| let name = WireName::new(name).expect("PAT name must be valid"); | |
| // See `create_personal_access_token` for why the shape depends on the path. | |
| if self.shell_wire.get() { | |
| let wire = WireDeletePersonalAccessTokenRequest { name }; | |
| return self.build_request(Operation::DeletePersonalAccessToken, &wire.to_bytes()); | |
| } | |
| let wire = DeletePersonalAccessTokenRequest { | |
| user_id: 0, | |
| name, | |
| only_if_expired: false, | |
| }; | |
| self.build_request(Operation::DeletePersonalAccessToken, &wire.to_bytes()) | |
| } | |
| /// Build a `SendMessages` request in the `SendMessagesEncoder` wire shape, | |
| /// byte-compatible with what the real SDK sends (`common` binary client). | |
| /// VSR clients resolve to an explicit partition before sending, so the sim | |
| /// always emits `WirePartitioning::PartitionId`: that is the shape the | |
| /// shell's `resolve_partition_request_namespace` decodes before admission | |
| /// strips the metadata and stamps the batch. | |
| /// | |
| /// # Panics | |
| /// Panics if a group id exceeds `u32` or the request buffer is invalid. | |
| pub fn send_messages( | |
| &self, | |
| group: IggyNamespace, | |
| messages: &[Bytes], | |
| ) -> Message<RoutedRequestHeader> { | |
| self.send_batch(group, None, messages) | |
| } | |
| /// [`Self::send_messages`] as one batch of an idempotent producer. | |
| /// | |
| /// # Panics | |
| /// Panics if a group id exceeds `u32` or the request buffer is invalid. | |
| pub fn send_producer_messages( | |
| &self, | |
| group: IggyNamespace, | |
| producer: BatchProducer, | |
| messages: &[Bytes], | |
| ) -> Message<RoutedRequestHeader> { | |
| self.send_batch(group, Some(producer), messages) | |
| } | |
| fn send_batch( | |
| &self, | |
| group: IggyNamespace, | |
| producer: Option<BatchProducer>, | |
| messages: &[Bytes], | |
| ) -> Message<RoutedRequestHeader> { | |
| let to_u32 = |v: usize| u32::try_from(v).expect("group id fits u32"); | |
| let stream_id = WireIdentifier::Numeric(to_u32(group.stream_id())); | |
| let topic_id = WireIdentifier::Numeric(to_u32(group.topic_id())); | |
| let partitioning = WirePartitioning::PartitionId(to_u32(group.partition_id())); | |
| // Stamp a deterministic, non-zero id per message. `id: 0` (the real | |
| // SDK's server-assigned path) would make the server mint an unseeded | |
| // random UUID into the replicated body, breaking seeded replay of any | |
| // produce; see `next_message_id`. `origin_timestamp: 0` keeps the batch | |
| // bytes seed-independent. | |
| let raw: Vec<RawMessage<'_>> = messages | |
| .iter() | |
| .map(|message| RawMessage { | |
| id: self.next_message_id(), | |
| origin_timestamp: 0, | |
| headers: None, | |
| payload: message.as_ref(), | |
| }) | |
| .collect(); | |
| let size = SendMessagesEncoder::encoded_size(&stream_id, &topic_id, &partitioning, &raw); | |
| let mut buf = BytesMut::with_capacity(size); | |
| SendMessagesEncoder::encode_with_producer( | |
| &mut buf, | |
| &stream_id, | |
| &topic_id, | |
| &partitioning, | |
| producer, | |
| &raw, | |
| ) | |
| .expect("simulator send batch encodes"); | |
| self.build_request_with_namespace(Operation::SendMessages, &buf, group) | |
| } | |
| /// Build a `NonReplicated` request: `code` in the header's `reserved` | |
| /// prefix, `group` as the routing namespace, `body` already encoded. | |
| /// | |
| /// The server ignores `request` for ops its `ClientTable` never sees. The | |
| /// setup and fixture reads echo the current counter without advancing it, so | |
| /// the request ids their hand-written scenarios pin stay put. | |
| /// | |
| /// # Panics | |
| /// Panics if the request buffer is invalid. | |
| #[allow(clippy::cast_possible_truncation)] | |
| fn non_replicated_request( | |
| &self, | |
| code: u32, | |
| group: u64, | |
| body: &[u8], | |
| request: u64, | |
| ) -> Message<RoutedRequestHeader> { | |
| let header_size = std::mem::size_of::<RoutedRequestHeader>(); | |
| let total_size = header_size + body.len(); | |
| let reserved = code.to_le_bytes(); | |
| let mut header = RoutedRequestHeader { | |
| command: iggy_binary_protocol::Command::Request, | |
| operation: Operation::NonReplicated, | |
| size: total_size as u32, | |
| client: self.client_id, | |
| session: self.session_id(), | |
| request, | |
| reserved, | |
| group, | |
| ..Default::default() | |
| }; | |
| self.stamp_partition_context(&mut header); | |
| let mut buffer = Vec::with_capacity(total_size); | |
| buffer.extend_from_slice(bytemuck::bytes_of(&header)); | |
| buffer.extend_from_slice(body); | |
| Message::try_from(Owned::<4096>::copy_from_slice(&buffer)) | |
| .expect("non-replicated request must be valid") | |
| } | |
| /// Build a `POLL_MESSAGES` request for an individual consumer, reading | |
| /// `count` messages from offset 0 of `group`'s partition. | |
| /// | |
| /// Requires a bound session (polls are auth-gated). | |
| /// | |
| /// # Panics | |
| /// Panics if the session is unbound or the request buffer is invalid. | |
| #[allow(clippy::cast_possible_truncation)] | |
| pub fn poll_messages(&self, group: IggyNamespace, count: u32) -> Message<RoutedRequestHeader> { | |
| let (stream_id, topic_id, partition_id) = namespace_ids(group); | |
| let body = PollMessagesRequest { | |
| consumer: WireConsumer::consumer(WireIdentifier::Numeric(self.client_id as u32)), | |
| stream_id, | |
| topic_id, | |
| partition_id, | |
| strategy: WirePollingStrategy::first(), | |
| count, | |
| auto_commit: false, | |
| } | |
| .to_bytes(); | |
| self.non_replicated_request( | |
| POLL_MESSAGES_CODE, | |
| group.inner(), | |
| &body, | |
| self.request_counter.get(), | |
| ) | |
| } | |
| /// Build a `POLL_MESSAGES_DEFERRED` request for an individual consumer of | |
| /// `group`'s partition. Spends a request id, as every bound read does, so | |
| /// the reply and a cancellation can name it. | |
| /// | |
| /// # Panics | |
| /// Panics if the session is unbound or the request buffer is invalid. | |
| #[allow(clippy::cast_possible_truncation)] | |
| pub fn deferred_poll_messages( | |
| &self, | |
| group: IggyNamespace, | |
| strategy: WirePollingStrategy, | |
| (count, min_count): (u32, u32), | |
| auto_commit: bool, | |
| (wait_us, request_timeout_us): (u64, u64), | |
| ) -> Message<RoutedRequestHeader> { | |
| self.deferred_poll_messages_for_consumer( | |
| group, | |
| strategy, | |
| (count, min_count), | |
| auto_commit, | |
| (wait_us, request_timeout_us), | |
| self.client_id as u32, | |
| ) | |
| } | |
| /// Build a deferred read of another session's standalone consumer. | |
| pub fn deferred_poll_messages_for_consumer( | |
| &self, | |
| group: IggyNamespace, | |
| strategy: WirePollingStrategy, | |
| (count, min_count): (u32, u32), | |
| auto_commit: bool, | |
| (wait_us, request_timeout_us): (u64, u64), | |
| consumer_id: u32, | |
| ) -> Message<RoutedRequestHeader> { | |
| let (stream_id, topic_id, partition_id) = namespace_ids(group); | |
| let body = DeferredPollMessagesRequest { | |
| poll: PollMessagesRequest { | |
| consumer: WireConsumer::consumer(WireIdentifier::Numeric(consumer_id)), | |
| stream_id, | |
| topic_id, | |
| partition_id, | |
| strategy, | |
| count, | |
| auto_commit, | |
| }, | |
| wait_us, | |
| min_count, | |
| max_bytes: DEFAULT_POLL_MAX_BYTES, | |
| request_timeout_us, | |
| } | |
| .to_bytes(); | |
| self.non_replicated_request( | |
| POLL_MESSAGES_DEFERRED_CODE, | |
| group.inner(), | |
| &body, | |
| self.next_request_id(), | |
| ) | |
| } | |
| /// Build a `FETCH_MESSAGES` request of the client's own consumer for | |
| /// `partitions` of one stream and topic, each read from `strategy` with | |
| /// the partition context the client discovered. Spends a request id, so | |
| /// the reply and a cancellation can name it. | |
| /// | |
| /// # Panics | |
| /// Panics if `partitions` is empty, the session is unbound or the request | |
| /// buffer is invalid. | |
| #[allow(clippy::cast_possible_truncation)] | |
| pub fn fetch_messages( | |
| &self, | |
| partitions: &[IggyNamespace], | |
| strategy: &WirePollingStrategy, | |
| (count, min_count): (u32, u32), | |
| auto_commit: bool, | |
| (wait_us, request_timeout_us): (u64, u64), | |
| ) -> Message<RoutedRequestHeader> { | |
| let first = *partitions.first().expect("a fetch names a partition"); | |
| let (stream_id, topic_id, _) = namespace_ids(first); | |
| let contexts = self.partition_contexts.borrow(); | |
| let targets = partitions | |
| .iter() | |
| .map(|namespace| { | |
| let context = contexts.get(namespace).copied().unwrap_or_default(); | |
| FetchMessagesTarget { | |
| partition_id: namespace.partition_id() as u32, | |
| strategy: strategy.clone(), | |
| max_bytes: DEFAULT_POLL_MAX_BYTES, | |
| incarnation: context.incarnation, | |
| owner_generation: context.owner_generation, | |
| } | |
| }) | |
| .collect(); | |
| drop(contexts); | |
| let body = FetchMessagesRequest { | |
| consumer: WireConsumer::consumer(WireIdentifier::Numeric(self.client_id as u32)), | |
| stream_id, | |
| topic_id, | |
| wait_us, | |
| request_timeout_us, | |
| min_count, | |
| count, | |
| max_bytes: DEFAULT_POLL_MAX_BYTES, | |
| auto_commit, | |
| targets, | |
| } | |
| .to_bytes(); | |
| self.non_replicated_request( | |
| FETCH_MESSAGES_CODE, | |
| first.inner(), | |
| &body, | |
| self.next_request_id(), | |
| ) | |
| } | |
| /// Build a `CANCEL_DEFERRED_REQUEST` for the deferred request this client | |
| /// sent with `request`, as the SDK sends it: same connection, empty body. | |
| /// | |
| /// # Panics | |
| /// Panics if the session is unbound or the request buffer is invalid. | |
| pub fn cancel_deferred_request( | |
| &self, | |
| group: IggyNamespace, | |
| request: u64, | |
| ) -> Message<RoutedRequestHeader> { | |
| self.non_replicated_request(CANCEL_DEFERRED_REQUEST_CODE, group.inner(), &[], request) | |
| } | |
| /// Build a `POLL_MESSAGES` request reading `count` messages from `offset` of | |
| /// `group`'s partition as `consumer_kind`/`consumer_id`, without auto-commit. | |
| /// | |
| /// Spends a request id, as the SDK does for every bound read, so a late copy | |
| /// of the previous request's reply cannot answer this one. | |
| /// | |
| /// # Panics | |
| /// Panics if the session is unbound or the request buffer is invalid. | |
| pub fn poll_messages_at( | |
| &self, | |
| group: IggyNamespace, | |
| consumer_kind: u8, | |
| consumer_id: u32, | |
| offset: u64, | |
| count: u32, | |
| ) -> Message<RoutedRequestHeader> { | |
| let (stream_id, topic_id, partition_id) = namespace_ids(group); | |
| let body = PollMessagesRequest { | |
| consumer: namespace_consumer(consumer_kind, consumer_id), | |
| stream_id, | |
| topic_id, | |
| partition_id, | |
| strategy: WirePollingStrategy::offset(offset), | |
| count, | |
| auto_commit: false, | |
| } | |
| .to_bytes(); | |
| self.non_replicated_request( | |
| POLL_MESSAGES_CODE, | |
| group.inner(), | |
| &body, | |
| self.next_request_id(), | |
| ) | |
| } | |
| /// Build a `GET_STREAM` read for `name`. | |
| /// | |
| /// A metadata read, so it is answered from whichever replica's state | |
| /// machine the request lands on rather than routed to the primary; the | |
| /// group is the metadata sentinel. Requires a bound session, since the read | |
| /// is auth-gated. | |
| /// | |
| /// # Panics | |
| /// Panics if `name` is not a valid wire name or the request buffer is | |
| /// invalid. | |
| pub fn get_stream(&self, name: &str) -> Message<RoutedRequestHeader> { | |
| let body = GetStreamRequest { | |
| stream_id: WireIdentifier::named(name).expect("stream name must be valid"), | |
| } | |
| .to_bytes(); | |
| self.non_replicated_request( | |
| GET_STREAM_CODE, | |
| METADATA_GROUP, | |
| &body, | |
| self.request_counter.get(), | |
| ) | |
| } | |
| /// Store offset with explicit `AckLevel`. A multi-replica partition routes | |
| /// both values through VSR. A single replica retains the `NoAck` fast path. | |
| /// | |
| /// # Panics | |
| /// Panics on payload too large for `Owned::<4096>` or invalid | |
| /// `Message<RoutedRequestHeader>` parse; both are simulator misconfig. | |
| pub fn store_consumer_offset( | |
| &self, | |
| group: IggyNamespace, | |
| consumer_kind: u8, | |
| consumer_id: u32, | |
| offset: u64, | |
| ack: AckLevel, | |
| ) -> Message<RoutedRequestHeader> { | |
| let (stream_id, topic_id, partition_id) = namespace_ids(group); | |
| let request = StoreConsumerOffsetRequest { | |
| consumer: namespace_consumer(consumer_kind, consumer_id), | |
| stream_id, | |
| topic_id, | |
| partition_id, | |
| offset, | |
| ack, | |
| }; | |
| self.build_request_with_namespace( | |
| Operation::StoreConsumerOffset, | |
| &request.to_bytes(), | |
| group, | |
| ) | |
| } | |
| /// Delete offset with explicit `AckLevel`. | |
| /// | |
| /// # Panics | |
| /// Panics on payload too large for `Owned::<4096>` or invalid | |
| /// `Message<RoutedRequestHeader>` parse; both are simulator misconfig. | |
| pub fn delete_consumer_offset( | |
| &self, | |
| group: IggyNamespace, | |
| consumer_kind: u8, | |
| consumer_id: u32, | |
| ack: AckLevel, | |
| ) -> Message<RoutedRequestHeader> { | |
| let (stream_id, topic_id, partition_id) = namespace_ids(group); | |
| let request = DeleteConsumerOffsetRequest { | |
| consumer: namespace_consumer(consumer_kind, consumer_id), | |
| stream_id, | |
| topic_id, | |
| partition_id, | |
| ack, | |
| }; | |
| self.build_request_with_namespace( | |
| Operation::DeleteConsumerOffset, | |
| &request.to_bytes(), | |
| group, | |
| ) | |
| } | |
| fn build_request_with_namespace( | |
| &self, | |
| operation: Operation, | |
| payload: &[u8], | |
| group: IggyNamespace, | |
| ) -> Message<RoutedRequestHeader> { | |
| let header_size = std::mem::size_of::<RoutedRequestHeader>(); | |
| let total_size = header_size + payload.len(); | |
| let mut header = self.header(operation, group.inner(), total_size); | |
| self.stamp_partition_context(&mut header); | |
| header.request_checksum = 0; | |
| let header_bytes = bytemuck::bytes_of(&header); | |
| let mut buffer = Vec::with_capacity(total_size); | |
| buffer.extend_from_slice(header_bytes); | |
| buffer.extend_from_slice(payload); | |
| Message::try_from(Owned::<4096>::copy_from_slice(&buffer)) | |
| .expect("request buffer must contain a valid request message") | |
| } | |
| fn build_request(&self, operation: Operation, payload: &[u8]) -> Message<RoutedRequestHeader> { | |
| let header_size = std::mem::size_of::<RoutedRequestHeader>(); | |
| let total_size = header_size + payload.len(); | |
| // Every `build_request` caller is a metadata-plane op (partition | |
| // ops go through `build_request_with_namespace`), and metadata | |
| // requests carry the metadata consensus group on the wire. | |
| let mut header = self.header(operation, METADATA_GROUP, total_size); | |
| // The simulator keeps request bytes deterministic for seeded replay. | |
| // Sequence identity must never expose a hash of a secret-bearing body. | |
| header.request_checksum = u128::from(header.request) + 1; | |
| let header_bytes = bytemuck::bytes_of(&header); | |
| let mut buffer = Vec::with_capacity(total_size); | |
| buffer.extend_from_slice(header_bytes); | |
| buffer.extend_from_slice(payload); | |
| Message::try_from(Owned::<4096>::copy_from_slice(&buffer)) | |
| .expect("request buffer must contain a valid request message") | |
| } | |
| #[allow(clippy::cast_possible_truncation)] | |
| fn header(&self, operation: Operation, group: u64, total_size: usize) -> RoutedRequestHeader { | |
| RoutedRequestHeader { | |
| command: iggy_binary_protocol::Command::Request, | |
| operation, | |
| size: total_size as u32, | |
| cluster: 0, // TODO: Get from config | |
| checksum: 0, | |
| checksum_body: 0, | |
| view: 0, | |
| release: 0, | |
| replica: 0, | |
| reserved_frame: [0; 66], | |
| client: self.client_id, | |
| request_checksum: 0, | |
| timestamp: 0, // TODO: Use actual timestamp | |
| session: self.session_id(), | |
| request: self.next_request_id(), | |
| group, | |
| ..Default::default() | |
| } | |
| } | |
| } | |
| /// Build a numeric-id `WireConsumer` for the offset-store/delete requests. | |
| /// The partition plane resolves numeric consumer ids verbatim, so this | |
| /// mirrors the real SDK wire shape (`[kind][WireIdentifier]`) rather than | |
| /// the old fixed `[kind][u32]` prefix. | |
| const fn namespace_consumer(kind: u8, consumer_id: u32) -> WireConsumer { | |
| WireConsumer { | |
| kind, | |
| id: WireIdentifier::Numeric(consumer_id), | |
| } | |
| } | |
| /// Decompose a group into the `(stream_id, topic_id, partition_id)` wire | |
| /// identifiers the consumer-offset requests carry. Namespace ids are small | |
| /// test values that always fit `u32`. | |
| fn namespace_ids(ns: IggyNamespace) -> (WireIdentifier, WireIdentifier, Option<u32>) { | |
| let to_u32 = |v: usize| u32::try_from(v).expect("group id fits u32"); | |
| ( | |
| WireIdentifier::Numeric(to_u32(ns.stream_id())), | |
| WireIdentifier::Numeric(to_u32(ns.topic_id())), | |
| Some(to_u32(ns.partition_id())), | |
| ) | |
| } | |
| #[cfg(test)] | |
| mod tests { | |
| use super::*; | |
| use iggy_common::{ServerKeyContext, StreamEncryptionKey, StreamKeyOrigin, WrapSet}; | |
| #[test] | |
| fn given_fixed_wrap_sets_when_opened_under_their_keks_should_hold_the_same_client_key() { | |
| let key = StreamEncryptionKey::try_from(SIM_STREAM_KEY.as_slice()).expect("32 bytes"); | |
| for (kek, bytes) in [ | |
| (SIM_STREAM_KEK, SIM_STREAM_WRAP_SET), | |
| (SIM_ROTATED_KEK, SIM_ROTATED_WRAP_SET), | |
| ] { | |
| let context = ServerKeyContext::from_config(kek, &[], false).expect("valid kek"); | |
| let set = WrapSet::try_from(bytes.as_slice()).expect("a valid wrap set"); | |
| assert_eq!(set.origin(), StreamKeyOrigin::Client); | |
| assert_eq!(context.open(&set).expect("opens under its kek"), key); | |
| } | |
| } | |
| // A partition send consumes a request id like any other replicated op, so | |
| // an interleaved run numbers both planes from one sequence and the metadata | |
| // ids arrive with gaps under them. That is the pattern the SDKs produce, and | |
| // the server admits it: `ClientTable` compares against a watermark rather | |
| // than requiring contiguity (`client_table.rs`: "There is no `RequestGap`"), | |
| // so a metadata op landing above the watermark executes and moves it. | |
| #[test] | |
| fn every_replicated_op_advances_the_one_request_sequence() { | |
| let client = SimClient::new(7); | |
| client.bind_session(1); | |
| let interleaved = [ | |
| Operation::CreateStream, | |
| Operation::SendMessages, | |
| Operation::CreateStream, | |
| Operation::SendMessages, | |
| Operation::CreateStream, | |
| ]; | |
| let ids: Vec<u64> = interleaved | |
| .into_iter() | |
| .map(|operation| client.header(operation, METADATA_GROUP, 0).request) | |
| .collect(); | |
| assert_eq!(ids, vec![1, 2, 3, 4, 5], "plane must not fork the sequence"); | |
| } | |
| } |