Skip to main content

confluent_kafka/admin/
mock_admin_client.rs

1// Copyright 2025 Confluent Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! An in-memory [`Admin`] implementation for tests.
16//!
17//! Corresponds to `org.apache.kafka.clients.admin.MockAdminClient` (restricted
18//! to the topic, cluster, and config methods that are in scope through Tier 1
19//! Phase 3).
20
21use crate::common::requests::DescribeLogDirsResponse;
22use crate::consumer::internals::ConsumerProtocol;
23use std::collections::{BTreeMap, HashMap};
24use std::sync::Mutex;
25use std::time::Duration;
26
27use async_trait::async_trait;
28
29use crate::DescribeUserScramCredentialsResponseData;
30use crate::admin::FilterResults;
31use crate::admin::{
32    AbortTransactionOptions, AbortTransactionResult, AbortTransactionSpec, DescribeProducersOptions,
33    DescribeProducersResult, DescribeTransactionsOptions, DescribeTransactionsResult, FenceProducersOptions,
34    FenceProducersResult, ListTransactionsOptions, ListTransactionsResult, PartitionProducerState,
35    TerminateTransactionOptions, TerminateTransactionResult, TransactionDescription, TransactionListing,
36};
37use crate::admin::{
38    Admin, AlterClientQuotasOptions, AlterClientQuotasResult, AlterConfigOp, AlterConfigsOptions, AlterConfigsResult,
39    AlterConsumerGroupOffsetsOptions, AlterConsumerGroupOffsetsResult, AlterPartitionReassignmentsOptions,
40    AlterPartitionReassignmentsResult, AlterReplicaLogDirsOptions, AlterReplicaLogDirsResult, ClassicGroupDescription,
41    Config, ConfigEntry, ConsumerGroupDescription, CreateAclsOptions, CreateAclsResult, CreateDelegationTokenOptions,
42    CreateDelegationTokenResult, CreatePartitionsOptions, CreatePartitionsResult, CreateTopicsOptions,
43    CreateTopicsResult, DeleteAclsOptions, DeleteAclsResult, DeleteConsumerGroupOffsetsOptions,
44    DeleteConsumerGroupOffsetsResult, DeleteConsumerGroupsOptions, DeleteConsumerGroupsResult, DeleteRecordsOptions,
45    DeleteRecordsResult, DeleteTopicsOptions, DeleteTopicsResult, DeletedRecords, DescribeAclsOptions,
46    DescribeAclsResult, DescribeClassicGroupsOptions, DescribeClassicGroupsResult, DescribeClientQuotasOptions,
47    DescribeClientQuotasResult, DescribeClusterOptions, DescribeClusterResult, DescribeConfigsOptions,
48    DescribeConfigsResult, DescribeConsumerGroupsOptions, DescribeConsumerGroupsResult, DescribeDelegationTokenOptions,
49    DescribeDelegationTokenResult, DescribeFeaturesOptions, DescribeFeaturesResult, DescribeLogDirsOptions,
50    DescribeLogDirsResult, DescribeReplicaLogDirsOptions, DescribeReplicaLogDirsResult, DescribeTopicsOptions,
51    DescribeTopicsResult, ElectLeadersOptions, ElectLeadersResult, ExpireDelegationTokenOptions,
52    ExpireDelegationTokenResult, FeatureMetadata, FeatureUpdate, FinalizedVersionRange, GroupListing, GroupOffsets,
53    ListConfigResourcesOptions, ListConfigResourcesResult, ListConsumerGroupOffsetsOptions,
54    ListConsumerGroupOffsetsResult, ListConsumerGroupOffsetsSpec, ListGroupsOptions, ListGroupsResult,
55    ListOffsetsOptions, ListOffsetsResult, ListOffsetsResultInfo, ListPartitionReassignmentsOptions,
56    ListPartitionReassignmentsResult, ListTopicsOptions, ListTopicsResult, LogDirDescription, NewPartitionReassignment,
57    NewPartitions, NewTopic, OffsetSpec, OpType, PartitionReassignment, RecordsToDelete,
58    RemoveMembersFromConsumerGroupOptions, RemoveMembersFromConsumerGroupResult, RenewDelegationTokenOptions,
59    RenewDelegationTokenResult, ReplicaInfo, ReplicaLogDirInfo, SupportedVersionRange, TopicDescription, TopicListing,
60    TopicMetadataAndConfig, UnregisterControllerOptions, UnregisterControllerResult, UpdateFeaturesOptions,
61    UpdateFeaturesResult, UpgradeType,
62};
63use crate::admin::{
64    AlterUserScramCredentialsOptions, AlterUserScramCredentialsResult, DescribeUserScramCredentialsOptions,
65    DescribeUserScramCredentialsResult, UserScramCredentialAlteration,
66};
67use crate::common::ElectionType;
68use crate::common::KafkaFuture;
69use crate::common::acl::{AclBinding, AclBindingFilter, AclOperation};
70use crate::common::config::{ConfigResource, config_resource};
71use crate::common::internals::KafkaFutureImpl;
72use crate::common::protocol::Errors;
73use crate::common::quota::{ClientQuotaAlteration, ClientQuotaEntity, ClientQuotaFilter};
74use crate::common::security::auth::KafkaPrincipal;
75use crate::common::security::token::delegation::{DelegationToken, TokenInformation};
76use crate::common::utils::internals::ProducerIdAndEpoch;
77use crate::common::{Error, Node, TopicCollection, TopicPartition, TopicPartitionInfo, TopicPartitionReplica, Uuid};
78use crate::common::{GroupState, GroupType};
79use crate::consumer::OffsetAndMetadata;
80use crate::leave_group_request_data::MemberIdentity;
81
82use std::collections::{BTreeSet, HashSet};
83
84/// Internal per-topic metadata held by the mock.
85///
86/// `Debug` is hand-written: `configs` holds raw config values and renders as
87/// its key set only (see [`config_keys`]).
88#[derive(Clone)]
89struct TopicMetadata {
90    topic_id: Uuid,
91    is_internal: bool,
92    partitions: Vec<TopicPartitionInfo>,
93    // One log dir per partition (Java's `TopicMetadata.partitionLogDirs`),
94    // taken from the first log dir of each partition's leader broker.
95    partition_log_dirs: Vec<String>,
96    // Read by `describe_configs` / `incremental_alter_configs`. Java's
97    // `TopicMetadata.configs` is never null (defaults to an empty map); the
98    // Rust `Option` treats `None` as an empty map. A `None` value is a config
99    // set to `null`, which Java's `Map<String, String>` holds as given.
100    configs: Option<BTreeMap<String, Option<String>>>,
101    marked_for_deletion: bool,
102    fetches_remaining_until_visible: i32,
103}
104
105/// Mutable state, guarded by a mutex (mirrors Java's `synchronized` methods).
106///
107/// `Debug` is hand-written: the config maps hold raw config values and render
108/// as their key sets only (see [`config_keys`]).
109struct State {
110    brokers: Vec<Node>,
111    controller: Node,
112    cluster_id: String,
113    all_topics: BTreeMap<String, TopicMetadata>,
114    topic_ids: BTreeMap<String, Uuid>,
115    topic_names: BTreeMap<Uuid, String>,
116    default_partitions: i32,
117    default_replication_factor: i32,
118    timeout_next_requests: i32,
119    // Per-broker config maps (index = broker id), mirroring Java's
120    // `brokerConfigs`. Each is seeded with `default.replication.factor`. In
121    // these maps, as in the topic configs, a `None` value is a config set to
122    // `null`, which Java's maps hold as given.
123    broker_configs: Vec<BTreeMap<String, Option<String>>>,
124    // Client-metrics subscription configs, keyed by resource name.
125    client_metrics_configs: BTreeMap<String, BTreeMap<String, Option<String>>>,
126    // Group configs, keyed by group id.
127    group_configs: BTreeMap<String, BTreeMap<String, Option<String>>>,
128    // Defaults overlaid onto group configs on read (mirrors Java's
129    // `defaultGroupConfigs`; set by `Builder::set_default_group_configs`).
130    default_group_configs: BTreeMap<String, String>,
131    // Per-broker list of log directories (index = broker id), mirroring Java's
132    // `brokerLogDirs`. Seeded with `DEFAULT_LOG_DIRS` for each broker.
133    broker_log_dirs: Vec<Vec<String>>,
134    // Pending replica moves recorded by `alter_replica_log_dirs`, keyed by
135    // replica (mirrors Java's `replicaMoves`).
136    replica_moves: HashMap<TopicPartitionReplica, ReplicaLogDirInfo>,
137    // Current partition reassignments, keyed by partition (mirrors Java's
138    // `reassignments`).
139    reassignments: HashMap<TopicPartition, NewPartitionReassignment>,
140    // Per-partition beginning / end offsets seeded via `update_beginning_offsets`
141    // / `update_end_offsets` (mirrors Java's `beginningOffsets` / `endOffsets`).
142    beginning_offsets: HashMap<TopicPartition, i64>,
143    end_offsets: HashMap<TopicPartition, i64>,
144    // Committed consumer-group offsets seeded via `update_consumer_group_offsets`,
145    // returned by `list_consumer_group_offsets` (mirrors Java's `committedOffsets`).
146    committed_offsets: HashMap<TopicPartition, i64>,
147    // In-memory delegation tokens (mirrors Java's `allTokens`).
148    all_tokens: Vec<DelegationToken>,
149    // Current finalized feature levels, keyed by feature name (mirrors Java's
150    // `featureLevels`). Mutated by `update_features` unless `validate_only`.
151    feature_levels: HashMap<String, i16>,
152    // Minimum supported feature levels, keyed by feature name (mirrors Java's
153    // `minSupportedFeatureLevels`).
154    min_supported_feature_levels: HashMap<String, i16>,
155    // Maximum supported feature levels, keyed by feature name (mirrors Java's
156    // `maxSupportedFeatureLevels`).
157    max_supported_feature_levels: HashMap<String, i16>,
158    // Whether the mocked cluster runs a KRaft (Raft) controller quorum (mirrors
159    // Java's `usingRaftController`, `false` unless the builder sets it). Read by
160    // `unregister_controller`.
161    using_raft_controller: bool,
162}
163
164/// Renders a raw config map as its key set only, never a value.
165///
166/// Java's `MockAdminClient` has no `toString()`, neither on the client nor on
167/// its `TopicMetadata`, so there is no Java rendering of these maps to mirror.
168/// They are plain `Map<String, String>`s (`MockAdminClient#brokerConfigs`,
169/// `MockAdminClient#groupConfigs`), and a value may be a secret, such as a broker's
170/// `ssl.keystore.password` or a listener's `sasl.jaas.config`, with no
171/// `isSensitive` flag to tell it apart. So no value is printed, just as
172/// `ProducerConfig`'s `Debug` prints no value of its raw `originals` map. The
173/// map is a `BTreeMap`, so the keys are already sorted; they are borrowed, not
174/// copied.
175fn config_keys<V>(configs: &BTreeMap<String, V>) -> BTreeSet<&str> {
176    configs.keys().map(String::as_str).collect()
177}
178
179/// Renders every field as the derive it replaces did, except `configs`, which
180/// renders as its key set only (see [`config_keys`]).
181impl std::fmt::Debug for TopicMetadata {
182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        // Destructured exhaustively, so a field added to the struct must be
184        // considered here.
185        let Self {
186            topic_id,
187            is_internal,
188            partitions,
189            partition_log_dirs,
190            configs,
191            marked_for_deletion,
192            fetches_remaining_until_visible,
193        } = self;
194        f.debug_struct("TopicMetadata")
195            .field("topic_id", topic_id)
196            .field("is_internal", is_internal)
197            .field("partitions", partitions)
198            .field("partition_log_dirs", partition_log_dirs)
199            .field("configs", &configs.as_ref().map(config_keys))
200            .field("marked_for_deletion", marked_for_deletion)
201            .field("fetches_remaining_until_visible", fetches_remaining_until_visible)
202            .finish()
203    }
204}
205
206/// Renders every field as the derive it replaces did, except the config maps
207/// (`broker_configs`, `client_metrics_configs`, `group_configs`,
208/// `default_group_configs`, and each topic's `configs`), which render as their
209/// key sets only (see [`config_keys`]). Java's `MockAdminClient` has no
210/// `toString()` to mirror. The delegation tokens render through
211/// [`DelegationToken`]'s `Debug`, which hides the HMAC.
212impl std::fmt::Debug for State {
213    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214        // Destructured exhaustively, so a field added to the struct must be
215        // considered here.
216        let Self {
217            brokers,
218            controller,
219            cluster_id,
220            all_topics,
221            topic_ids,
222            topic_names,
223            default_partitions,
224            default_replication_factor,
225            timeout_next_requests,
226            broker_configs,
227            client_metrics_configs,
228            group_configs,
229            default_group_configs,
230            broker_log_dirs,
231            replica_moves,
232            reassignments,
233            beginning_offsets,
234            end_offsets,
235            committed_offsets,
236            all_tokens,
237            feature_levels,
238            min_supported_feature_levels,
239            max_supported_feature_levels,
240            using_raft_controller,
241        } = self;
242        let broker_configs: Vec<BTreeSet<&str>> = broker_configs.iter().map(config_keys).collect();
243        let client_metrics_configs: BTreeMap<&str, BTreeSet<&str>> = client_metrics_configs
244            .iter()
245            .map(|(name, configs)| (name.as_str(), config_keys(configs)))
246            .collect();
247        let group_configs: BTreeMap<&str, BTreeSet<&str>> = group_configs
248            .iter()
249            .map(|(group_id, configs)| (group_id.as_str(), config_keys(configs)))
250            .collect();
251        f.debug_struct("State")
252            .field("brokers", brokers)
253            .field("controller", controller)
254            .field("cluster_id", cluster_id)
255            .field("all_topics", all_topics)
256            .field("topic_ids", topic_ids)
257            .field("topic_names", topic_names)
258            .field("default_partitions", default_partitions)
259            .field("default_replication_factor", default_replication_factor)
260            .field("timeout_next_requests", timeout_next_requests)
261            .field("broker_configs", &broker_configs)
262            .field("client_metrics_configs", &client_metrics_configs)
263            .field("group_configs", &group_configs)
264            .field("default_group_configs", &config_keys(default_group_configs))
265            .field("broker_log_dirs", broker_log_dirs)
266            .field("replica_moves", replica_moves)
267            .field("reassignments", reassignments)
268            .field("beginning_offsets", beginning_offsets)
269            .field("end_offsets", end_offsets)
270            .field("committed_offsets", committed_offsets)
271            .field("all_tokens", all_tokens)
272            .field("feature_levels", feature_levels)
273            .field("min_supported_feature_levels", min_supported_feature_levels)
274            .field("max_supported_feature_levels", max_supported_feature_levels)
275            .field("using_raft_controller", using_raft_controller)
276            .finish()
277    }
278}
279
280/// An in-memory [`Admin`] implementation for tests.
281///
282/// Every method Java's `MockAdminClient` implements works on in-memory state;
283/// the ones Java leaves unimplemented return futures failed with an error for
284/// which `Error::is_local_unsupported_operation_error` holds. All futures
285/// returned are immediately resolved.
286#[derive(Debug)]
287#[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient")]
288// Java ships it in the clients test fixtures (clients/src/testFixtures since 4.4) for users to test against, as MockProducer / MockConsumer are public
289#[doc(alias = "public-in-rust")]
290pub struct MockAdminClient {
291    state: Mutex<State>,
292}
293
294/// Builds a [`MockAdminClient`].
295///
296/// It has the setters, defaults and failure points of Java's nested
297/// `MockAdminClient.Builder`. A fresh builder has one broker, `Node(0, "localhost", 1000)`, with
298/// [`MockAdminClient::DEFAULT_LOG_DIRS`].
299///
300/// Java's builder throws from `java.util` collection methods where it reads an
301/// index out of range. The crate has no `IndexOutOfBoundsException`
302/// counterpart, so those failures are errors for which
303/// `Error::is_local_illegal_argument_error` holds (like the mock's other
304/// argument errors), carrying the JDK's message text.
305#[derive(Clone, Debug)]
306#[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder")]
307// Java's nested MockAdminClient.Builder, the way users build the test-fixtures MockAdminClient above
308#[doc(alias = "public-in-rust")]
309pub struct Builder {
310    cluster_id: String,
311    brokers: Vec<Node>,
312    controller: Option<Node>,
313    broker_log_dirs: Vec<Vec<String>>,
314    default_partitions: Option<i16>,
315    using_raft_controller: bool,
316    default_replication_factor: Option<i32>,
317    feature_levels: HashMap<String, i16>,
318    min_supported_feature_levels: HashMap<String, i16>,
319    max_supported_feature_levels: HashMap<String, i16>,
320    default_group_configs: HashMap<String, String>,
321}
322
323impl Default for Builder {
324    fn default() -> Self {
325        Self::new()
326    }
327}
328
329impl Builder {
330    /// Creates a builder with one broker, as Java's `public Builder()`, which
331    /// calls `numBrokers(1)`.
332    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#Builder")]
333    pub fn new() -> Self {
334        let mut builder = Self {
335            cluster_id: MockAdminClient::DEFAULT_CLUSTER_ID.to_string(),
336            brokers: Vec::new(),
337            controller: None,
338            broker_log_dirs: Vec::new(),
339            default_partitions: None,
340            using_raft_controller: false,
341            default_replication_factor: None,
342            feature_levels: HashMap::new(),
343            min_supported_feature_levels: HashMap::new(),
344            max_supported_feature_levels: HashMap::new(),
345            default_group_configs: HashMap::new(),
346        };
347        // `numBrokers(1)` on the empty lists takes only the growing branch,
348        // which cannot fail.
349        builder.add_brokers_up_to(1);
350        builder
351    }
352
353    /// Sets the cluster id.
354    ///
355    /// # Arguments
356    ///
357    /// - `cluster_id` - The cluster id
358    ///
359    /// # Returns
360    ///
361    /// This builder.
362    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#clusterId")]
363    pub fn set_cluster_id(mut self, cluster_id: &str) -> Self {
364        self.cluster_id = cluster_id.to_string();
365        self
366    }
367
368    /// Replaces the broker list.
369    ///
370    /// As Java's `brokers(List<Node>)`, first `numBrokers(brokers.size())` resizes the
371    /// current lists, which keeps existing log-dir entries and pads with
372    /// [`MockAdminClient::DEFAULT_LOG_DIRS`], and only then is the broker list
373    /// replaced.
374    ///
375    /// # Arguments
376    ///
377    /// - `brokers` - The brokers
378    ///
379    /// # Returns
380    ///
381    /// This builder.
382    ///
383    /// # Errors
384    ///
385    /// The errors of [`set_num_brokers`](Self::set_num_brokers)
386    /// (`Error::is_local_illegal_argument_error`). With a
387    /// non-negative count the only reachable one is a log-dir list shorter than
388    /// `brokers` (after [`set_broker_log_dirs`](Self::set_broker_log_dirs)), where
389    /// Java's `brokerLogDirs.subList(0, n)` throws.
390    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#brokers")]
391    pub fn set_brokers(self, brokers: Vec<Node>) -> Result<Self, Error> {
392        // `Collection.size()` saturates at `Integer.MAX_VALUE`, so a length that
393        // does not fit an `i32` becomes `i32::MAX`, as Java's `size()` reports it.
394        let count = i32::try_from(brokers.len()).unwrap_or(i32::MAX);
395        let mut builder = self.set_num_brokers(count)?;
396        builder.brokers = brokers;
397        Ok(builder)
398    }
399
400    /// Sets the number of brokers, keeping the first ones.
401    ///
402    /// Shrinking truncates both the broker list and the per-broker log dirs;
403    /// growing appends `Node(id, "localhost", 1000 + id)` and
404    /// [`MockAdminClient::DEFAULT_LOG_DIRS`] for each new id.
405    ///
406    /// # Arguments
407    ///
408    /// - `num_brokers` - The number of brokers
409    ///
410    /// # Returns
411    ///
412    /// This builder.
413    ///
414    /// # Errors
415    ///
416    /// `Error::is_local_illegal_argument_error` where Java's `subList(0, n)`
417    /// (`AbstractList.subListRangeCheck`) throws:
418    ///
419    /// - `num_brokers` is negative: "fromIndex(0) > toIndex(n)" (Java's
420    ///   `IllegalArgumentException`);
421    /// - shrinking below the broker count while the log-dir list is shorter than
422    ///   `num_brokers`: "toIndex = n" (Java's `IndexOutOfBoundsException`).
423    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#numBrokers")]
424    pub fn set_num_brokers(mut self, num_brokers: i32) -> Result<Self, Error> {
425        let current = self.brokers.len() as i64;
426        if current >= i64::from(num_brokers) {
427            let new_len = sub_list_end(num_brokers, self.brokers.len())?;
428            self.brokers.truncate(new_len);
429            let new_len = sub_list_end(num_brokers, self.broker_log_dirs.len())?;
430            self.broker_log_dirs.truncate(new_len);
431        } else {
432            self.add_brokers_up_to(num_brokers);
433        }
434        Ok(self)
435    }
436
437    /// The growing branch of `numBrokers`: adds brokers `brokers.len()` to
438    /// `num_brokers - 1`, each with the default log dirs.
439    fn add_brokers_up_to(&mut self, num_brokers: i32) {
440        let first = self.brokers.len() as i32;
441        for id in first..num_brokers {
442            self.brokers.push(Node::new(id, "localhost".to_string(), 1000 + id));
443            self.broker_log_dirs.push(MockAdminClient::default_log_dirs());
444        }
445    }
446
447    /// Makes the broker at `index` the controller, reading `brokers.get(index)`
448    /// at this call as Java's `controller(int)` does.
449    ///
450    /// # Arguments
451    ///
452    /// - `index` - The index of the controller in the broker list
453    ///
454    /// # Returns
455    ///
456    /// This builder.
457    ///
458    /// # Errors
459    ///
460    /// `Error::is_local_illegal_argument_error` with the JDK's
461    /// `IndexOutOfBoundsException` text, "Index i out of bounds for length n"
462    /// (`ArrayList.get` → `Objects.checkIndex`), when `index` is not a broker
463    /// index.
464    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#controller")]
465    pub fn set_controller(mut self, index: i32) -> Result<Self, Error> {
466        let node = usize::try_from(index)
467            .ok()
468            .and_then(|i| self.brokers.get(i))
469            .ok_or_else(|| index_out_of_bounds(index, self.brokers.len()))?;
470        self.controller = Some(node.clone());
471        Ok(self)
472    }
473
474    /// Replaces the per-broker log directories. Like Java's
475    /// `brokerLogDirs(List<List<String>>)`, the length is not checked against
476    /// the broker count.
477    ///
478    /// # Arguments
479    ///
480    /// - `broker_log_dirs` - The log directories of each broker, indexed by
481    ///   broker id
482    ///
483    /// # Returns
484    ///
485    /// This builder.
486    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#brokerLogDirs")]
487    pub fn set_broker_log_dirs(mut self, broker_log_dirs: Vec<Vec<String>>) -> Self {
488        self.broker_log_dirs = broker_log_dirs;
489        self
490    }
491
492    /// Sets the replication factor used when `createTopics` does not give one.
493    ///
494    /// [`build`](Self::build) narrows it to 16 bits the way Java's
495    /// `Integer.shortValue()` does: the value wraps, it is not clamped.
496    ///
497    /// # Arguments
498    ///
499    /// - `default_replication_factor` - The default replication factor
500    ///
501    /// # Returns
502    ///
503    /// This builder.
504    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#defaultReplicationFactor")]
505    pub fn set_default_replication_factor(mut self, default_replication_factor: i32) -> Self {
506        self.default_replication_factor = Some(default_replication_factor);
507        self
508    }
509
510    /// Sets whether the mocked cluster runs a KRaft (Raft) controller quorum,
511    /// which decides whether `unregister_controller` succeeds (default
512    /// `false`). The value is fixed once the mock is built.
513    ///
514    /// # Arguments
515    ///
516    /// - `using_raft_controller` - Whether the cluster uses a Raft controller
517    ///
518    /// # Returns
519    ///
520    /// This builder.
521    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#usingRaftController")]
522    pub fn set_using_raft_controller(mut self, using_raft_controller: bool) -> Self {
523        self.using_raft_controller = using_raft_controller;
524        self
525    }
526
527    /// Sets the partition count used when `createTopics` does not give one.
528    ///
529    /// # Arguments
530    ///
531    /// - `num_partitions` - The default partition count
532    ///
533    /// # Returns
534    ///
535    /// This builder.
536    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#defaultPartitions")]
537    pub fn set_default_partitions(mut self, num_partitions: i16) -> Self {
538        self.default_partitions = Some(num_partitions);
539        self
540    }
541
542    /// Sets the finalized feature levels.
543    ///
544    /// # Arguments
545    ///
546    /// - `feature_levels` - The finalized level of each feature, by name
547    ///
548    /// # Returns
549    ///
550    /// This builder.
551    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#featureLevels")]
552    pub fn set_feature_levels(mut self, feature_levels: HashMap<String, i16>) -> Self {
553        self.feature_levels = feature_levels;
554        self
555    }
556
557    /// Sets the minimum supported feature levels.
558    ///
559    /// # Arguments
560    ///
561    /// - `min_supported_feature_levels` - The minimum supported level of each
562    ///   feature, by name
563    ///
564    /// # Returns
565    ///
566    /// This builder.
567    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#minSupportedFeatureLevels")]
568    pub fn set_min_supported_feature_levels(mut self, min_supported_feature_levels: HashMap<String, i16>) -> Self {
569        self.min_supported_feature_levels = min_supported_feature_levels;
570        self
571    }
572
573    /// Sets the maximum supported feature levels.
574    ///
575    /// # Arguments
576    ///
577    /// - `max_supported_feature_levels` - The maximum supported level of each
578    ///   feature, by name
579    ///
580    /// # Returns
581    ///
582    /// This builder.
583    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#maxSupportedFeatureLevels")]
584    pub fn set_max_supported_feature_levels(mut self, max_supported_feature_levels: HashMap<String, i16>) -> Self {
585        self.max_supported_feature_levels = max_supported_feature_levels;
586        self
587    }
588
589    /// Sets the defaults overlaid onto every group's configs.
590    ///
591    /// # Arguments
592    ///
593    /// - `default_group_configs` - The default group configs, by name
594    ///
595    /// # Returns
596    ///
597    /// This builder.
598    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#defaultGroupConfigs")]
599    pub fn set_default_group_configs(mut self, default_group_configs: HashMap<String, String>) -> Self {
600        self.default_group_configs = default_group_configs;
601        self
602    }
603
604    /// Builds the mock.
605    ///
606    /// Defaults: the controller is the first broker, the default partition
607    /// count is 1, and the default replication factor is
608    /// `min(brokers.len(), 3)`.
609    ///
610    /// # Returns
611    ///
612    /// The mock admin client.
613    ///
614    /// # Errors
615    ///
616    /// `Error::is_local_illegal_argument_error` where Java throws:
617    ///
618    /// - no controller was set and there are no brokers: "Index 0 out of bounds
619    ///   for length 0", the JDK's text for Java's `brokers.get(0)`;
620    /// - the controller is no longer one of the brokers (for example
621    ///   `set_controller(2)` followed by `set_num_brokers(1)`): "The controller
622    ///   node must be in the list of brokers".
623    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient$Builder#build")]
624    pub fn build(self) -> Result<MockAdminClient, Error> {
625        let controller = match self.controller {
626            Some(controller) => controller,
627            None => self.brokers.first().cloned().ok_or_else(|| index_out_of_bounds(0, 0))?,
628        };
629        let default_partitions = self.default_partitions.map_or(1, i32::from);
630        // `defaultReplicationFactor.shortValue()`: a wrapping narrowing, then
631        // widened back to the constructor's `int` parameter.
632        let default_replication_factor = match self.default_replication_factor {
633            Some(factor) => i32::from(factor as i16),
634            None => self.brokers.len().min(3) as i32,
635        };
636        MockAdminClient::with_state(
637            self.brokers,
638            controller,
639            self.cluster_id,
640            default_partitions,
641            default_replication_factor,
642            self.broker_log_dirs,
643            self.using_raft_controller,
644            self.feature_levels,
645            self.min_supported_feature_levels,
646            self.max_supported_feature_levels,
647            self.default_group_configs,
648        )
649    }
650}
651
652/// The end index of Java's `list.subList(0, to_index)`, or the error the JDK's
653/// `AbstractList.subListRangeCheck(0, toIndex, size)` throws for it.
654///
655/// The JDK checks `toIndex > size` before `fromIndex > toIndex`, so an index
656/// past the end reports "toIndex = n" and a negative one reports
657/// "fromIndex(0) > toIndex(n)".
658fn sub_list_end(to_index: i32, size: usize) -> Result<usize, Error> {
659    if i64::from(to_index) > size as i64 {
660        return Err(Error::local_illegal_argument(format!("toIndex = {to_index}")));
661    }
662    usize::try_from(to_index).map_err(|_| Error::local_illegal_argument(format!("fromIndex(0) > toIndex({to_index})")))
663}
664
665/// The JDK's `IndexOutOfBoundsException` text for `list.get(index)` on a list
666/// of `length` elements (`Objects.checkIndex`).
667fn index_out_of_bounds(index: i32, length: usize) -> Error {
668    Error::local_illegal_argument(format!("Index {index} out of bounds for length {length}"))
669}
670
671/// Java's `brokerLogDirs.get(brokerId)`. The list is indexed by broker **id**,
672/// not by position in `brokers`, so a broker whose id is not a valid index
673/// (for example brokers 5, 6 and 7 given to [`Builder::set_brokers`], or
674/// [`Node::no_node`]'s id -1) makes Java throw `IndexOutOfBoundsException`;
675/// that is returned as an error here instead of a panic.
676fn broker_log_dirs_of(broker_log_dirs: &[Vec<String>], broker_id: i32) -> Result<&[String], Error> {
677    usize::try_from(broker_id)
678        .ok()
679        .and_then(|index| broker_log_dirs.get(index))
680        .map(Vec::as_slice)
681        .ok_or_else(|| index_out_of_bounds(broker_id, broker_log_dirs.len()))
682}
683
684/// The check of Java's `MockAdminClient#controller(Node)`: the
685/// controller must be one of the brokers.
686fn check_controller(brokers: &[Node], controller: &Node) -> Result<(), Error> {
687    if !brokers.contains(controller) {
688        return Err(Error::local_illegal_argument(
689            "The controller node must be in the list of brokers",
690        ));
691    }
692    Ok(())
693}
694
695impl Default for MockAdminClient {
696    /// Same as [`MockAdminClient::new`].
697    fn default() -> Self {
698        Self::new()
699    }
700}
701
702impl MockAdminClient {
703    /// The cluster id a [`Builder`] uses unless
704    /// [`set_cluster_id`](Builder::set_cluster_id) overrides it.
705    pub const DEFAULT_CLUSTER_ID: &'static str = "I4ZmrWqfT2e-upky_4fdPA";
706
707    /// The log directories a [`Builder`] gives each broker it adds.
708    pub const DEFAULT_LOG_DIRS: &'static [&'static str] = &["/tmp/kafka-logs"];
709
710    /// Returns a new [`Builder`] with one broker.
711    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient#create")]
712    pub fn create() -> Builder {
713        Builder::new()
714    }
715
716    /// Creates a mock with one broker, [`Node::no_node`], which is also the
717    /// controller.
718    ///
719    /// It cannot fail: the controller is the only broker.
720    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient#MockAdminClient()")]
721    pub fn new() -> Self {
722        let node = Node::no_node().clone();
723        Self::with_brokers_controller(vec![node.clone()], node)
724            .expect("the only broker is the controller, so the controller check passes")
725    }
726
727    /// Creates a mock with the given brokers and controller:
728    /// [`DEFAULT_CLUSTER_ID`](Self::DEFAULT_CLUSTER_ID),
729    /// one default partition, a default replication factor of `brokers.len()`
730    /// (unlike [`Builder::build`]'s `min(brokers.len(), 3)`),
731    /// [`DEFAULT_LOG_DIRS`](Self::DEFAULT_LOG_DIRS) for every broker, no raft
732    /// controller and empty feature-level and default-group-config maps.
733    ///
734    /// # Arguments
735    ///
736    /// - `brokers` - The brokers
737    /// - `controller` - The controller, one of `brokers`
738    ///
739    /// # Errors
740    ///
741    /// `Error::is_local_illegal_argument_error`, with Java's message "The
742    /// controller node must be in the list of brokers", when `controller` is not
743    /// one of `brokers`.
744    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient#MockAdminClient(List,Node)")]
745    pub fn with_brokers_controller(brokers: Vec<Node>, controller: Node) -> Result<Self, Error> {
746        let broker_log_dirs = vec![Self::default_log_dirs(); brokers.len()];
747        // Java passes `brokers.size()` as the `int defaultReplicationFactor`
748        // without narrowing it; only the Builder path calls `shortValue()`.
749        let default_replication_factor = brokers.len() as i32;
750        Self::with_state(
751            brokers,
752            controller,
753            Self::DEFAULT_CLUSTER_ID.to_string(),
754            1,
755            default_replication_factor,
756            broker_log_dirs,
757            false,
758            HashMap::new(),
759            HashMap::new(),
760            HashMap::new(),
761            HashMap::new(),
762        )
763    }
764
765    /// Makes `controller` the controller node reported by `describe_cluster`.
766    ///
767    /// # Arguments
768    ///
769    /// - `controller` - The controller, one of the mock's brokers
770    ///
771    /// # Errors
772    ///
773    /// `Error::is_local_illegal_argument_error`, with Java's message "The
774    /// controller node must be in the list of brokers", when `controller` is not
775    /// one of the mock's brokers; the controller is then left unchanged.
776    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient#controller")]
777    pub fn set_controller(&self, controller: Node) -> Result<(), Error> {
778        let mut state = self.state.lock().unwrap();
779        check_controller(&state.brokers, &controller)?;
780        state.controller = controller;
781        Ok(())
782    }
783
784    /// The log directories of one broker, as owned strings.
785    fn default_log_dirs() -> Vec<String> {
786        Self::DEFAULT_LOG_DIRS.iter().map(|dir| (*dir).to_string()).collect()
787    }
788
789    /// Translated from Java's private constructor
790    /// `MockAdminClient(List<Node>, Node, String, int, int, List<List<String>>,
791    /// boolean, Map, Map, Map, Map)`, which [`Builder::build`] calls.
792    ///
793    /// # Errors
794    ///
795    /// Returns [`Error::LocalIllegalArgument`] with Java's message, "The
796    /// controller node must be in the list of brokers", when `controller` is
797    /// not one of `brokers`. Java throws `IllegalArgumentException` from
798    /// `controller(Node)`, which the constructor calls.
799    #[expect(clippy::too_many_arguments)]
800    fn with_state(
801        brokers: Vec<Node>,
802        controller: Node,
803        cluster_id: String,
804        default_partitions: i32,
805        default_replication_factor: i32,
806        broker_log_dirs: Vec<Vec<String>>,
807        using_raft_controller: bool,
808        feature_levels: HashMap<String, i16>,
809        min_supported_feature_levels: HashMap<String, i16>,
810        max_supported_feature_levels: HashMap<String, i16>,
811        default_group_configs: HashMap<String, String>,
812    ) -> Result<Self, Error> {
813        check_controller(&brokers, &controller)?;
814        // Seed one config map per broker with `default.replication.factor`
815        // (mirrors Java's constructor).
816        let broker_configs: Vec<BTreeMap<String, Option<String>>> = brokers
817            .iter()
818            .map(|_| {
819                let mut config = BTreeMap::new();
820                config.insert(
821                    "default.replication.factor".to_string(),
822                    Some(default_replication_factor.to_string()),
823                );
824                config
825            })
826            .collect();
827        Ok(Self {
828            state: Mutex::new(State {
829                brokers,
830                controller,
831                cluster_id,
832                all_topics: BTreeMap::new(),
833                topic_ids: BTreeMap::new(),
834                topic_names: BTreeMap::new(),
835                default_partitions,
836                default_replication_factor,
837                timeout_next_requests: 0,
838                broker_configs,
839                client_metrics_configs: BTreeMap::new(),
840                group_configs: BTreeMap::new(),
841                default_group_configs: default_group_configs.into_iter().collect(),
842                broker_log_dirs,
843                replica_moves: HashMap::new(),
844                reassignments: HashMap::new(),
845                beginning_offsets: HashMap::new(),
846                end_offsets: HashMap::new(),
847                committed_offsets: HashMap::new(),
848                all_tokens: Vec::new(),
849                feature_levels,
850                min_supported_feature_levels,
851                max_supported_feature_levels,
852                using_raft_controller,
853            }),
854        })
855    }
856
857    // --- seeding mutators ---------------------------------------------------
858    //
859    // Convention for this group: a seeding helper whose Java counterpart is a
860    // `void` method that *throws* returns `Result<(), Error>` and reuses
861    // Java's message verbatim, rather than panicking. Java's throws here are all
862    // catchable `IllegalArgumentException`s, and CLAUDE.md §12.2 asks for a
863    // `Result` for a recoverable Java throw even when it is unchecked. A helper
864    // whose Java counterpart cannot fail (`updateBeginningOffsets`,
865    // `updateEndOffsets`, `updateConsumerGroupOffsets`, `timeoutNextRequest`)
866    // stays infallible.
867
868    /// Seeds the beginning offsets returned by `list_offsets` for the given
869    /// partitions.
870    ///
871    /// # Arguments
872    ///
873    /// - `new_offsets` - The beginning offset of each partition
874    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient#updateBeginningOffsets")]
875    pub fn update_beginning_offsets(&self, new_offsets: HashMap<TopicPartition, i64>) {
876        let mut state = self.state.lock().unwrap();
877        state.beginning_offsets.extend(new_offsets);
878    }
879
880    /// Seeds the end offsets returned by `list_offsets` for the given
881    /// partitions.
882    ///
883    /// # Arguments
884    ///
885    /// - `new_offsets` - The end offset of each partition
886    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient#updateEndOffsets")]
887    pub fn update_end_offsets(&self, new_offsets: HashMap<TopicPartition, i64>) {
888        let mut state = self.state.lock().unwrap();
889        state.end_offsets.extend(new_offsets);
890    }
891
892    /// Seeds the committed consumer-group offsets returned by
893    /// `list_consumer_group_offsets_with_group_specs` for the given partitions.
894    ///
895    /// # Arguments
896    ///
897    /// - `new_offsets` - The committed offset of each partition
898    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient#updateConsumerGroupOffsets")]
899    pub fn update_consumer_group_offsets(&self, new_offsets: HashMap<TopicPartition, i64>) {
900        let mut state = self.state.lock().unwrap();
901        state.committed_offsets.extend(new_offsets);
902    }
903
904    /// Adds an existing topic to the mock's state.
905    ///
906    /// # Arguments
907    ///
908    /// - `internal` - Whether the topic is internal
909    /// - `name` - The topic name
910    /// - `partitions` - The topic's partitions, whose leaders, replicas and ISR
911    ///   must be brokers of the mock
912    /// - `configs` - The topic configs, or `None` for none
913    ///
914    /// # Errors
915    ///
916    /// `Error::is_local_illegal_argument_error`, with Java's message, if the
917    /// topic was already added, or if any partition names a broker the mock does
918    /// not have as its leader, in its replica list, or in its ISR.
919    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient#addTopic")]
920    pub fn add_topic(
921        &self,
922        internal: bool,
923        name: &str,
924        partitions: Vec<TopicPartitionInfo>,
925        configs: Option<BTreeMap<String, String>>,
926    ) -> Result<(), Error> {
927        let mut state = self.state.lock().unwrap();
928        if state.all_topics.contains_key(name) {
929            return Err(Error::local_illegal_argument(format!("Topic {name} was already added.")));
930        }
931        // Java validates every partition against the broker list before touching
932        // `brokerLogDirs` (`MockAdminClient#addTopic`). Note that
933        // `brokers.contains(partition.leader())` is false for a null leader, so
934        // Java rejects a leaderless partition here too — which is why the log-dir
935        // loop's `partition.leader() != null` guard below can never fail once
936        // these checks have passed.
937        for partition in &partitions {
938            let known_leader = partition.leader().is_some_and(|leader| state.brokers.contains(leader));
939            if !known_leader {
940                return Err(Error::local_illegal_argument("Leader broker unknown"));
941            }
942            if !partition.replicas().iter().all(|node| state.brokers.contains(node)) {
943                return Err(Error::local_illegal_argument("Unknown brokers in replica list"));
944            }
945            if !partition.isr().iter().all(|node| state.brokers.contains(node)) {
946                return Err(Error::local_illegal_argument("Unknown brokers in isr list"));
947            }
948        }
949        // Each partition starts on the first log directory of its leader broker:
950        // Java's `brokerLogDirs.get(leader.id()).get(0)` (`MockAdminClient#addTopic`).
951        // Both lookups throw `IndexOutOfBoundsException` in Java — the outer one
952        // for a leader whose id is not an index of `brokerLogDirs` (the check
953        // above only proves the leader is one of `brokers`), the inner one for a
954        // broker with no log directory — so both are surfaced as errors rather
955        // than panicked on (CLAUDE.md §10.1).
956        let mut partition_log_dirs: Vec<String> = Vec::with_capacity(partitions.len());
957        for leader in partitions.iter().filter_map(TopicPartitionInfo::leader) {
958            let dirs = broker_log_dirs_of(&state.broker_log_dirs, leader.id())?;
959            let first = dirs.first().ok_or_else(|| {
960                Error::local_illegal_argument(format!("Broker {} has no log directories.", leader.id()))
961            })?;
962            partition_log_dirs.push(first.clone());
963        }
964        let topic_id = Uuid::random_uuid();
965        state.topic_ids.insert(name.to_string(), topic_id);
966        state.topic_names.insert(topic_id, name.to_string());
967        state.all_topics.insert(
968            name.to_string(),
969            TopicMetadata {
970                topic_id,
971                is_internal: internal,
972                partitions,
973                partition_log_dirs,
974                configs: configs.map(|configs| configs.into_iter().map(|(name, value)| (name, Some(value))).collect()),
975                marked_for_deletion: false,
976                fetches_remaining_until_visible: 0,
977            },
978        );
979        Ok(())
980    }
981
982    /// Marks a topic for deletion so `describe_topics_with_topics` treats it as absent.
983    ///
984    /// # Arguments
985    ///
986    /// - `name` - The topic name
987    ///
988    /// # Errors
989    ///
990    /// `Error::is_local_illegal_argument_error`, with Java's message, if the
991    /// topic does not exist.
992    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient#markTopicForDeletion")]
993    pub fn mark_topic_for_deletion(&self, name: &str) -> Result<(), Error> {
994        let mut state = self.state.lock().unwrap();
995        let topic = state
996            .all_topics
997            .get_mut(name)
998            .ok_or_else(|| Error::local_illegal_argument(format!("Topic {name} did not exist.")))?;
999        topic.marked_for_deletion = true;
1000        Ok(())
1001    }
1002
1003    /// Hides a topic from the next `fetches_remaining_until_visible` fetches.
1004    ///
1005    /// Each `list_topics`, `describe_topics` (by name or by id) and topic
1006    /// `describe_configs` that would return the topic decrements the counter
1007    /// instead, until it reaches zero.
1008    ///
1009    /// # Arguments
1010    ///
1011    /// - `topic_name` - The topic name
1012    /// - `fetches_remaining_until_visible` - The number of fetches that do not
1013    ///   return the topic
1014    ///
1015    /// # Errors
1016    ///
1017    /// `Error::is_local_illegal_argument_error`, with Java's message,
1018    /// `"No such topic as <name>"`, if the topic does not exist. Java throws a bare
1019    /// `RuntimeException`, which has no closer counterpart in the crate.
1020    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient#setFetchesRemainingUntilVisible")]
1021    pub fn set_fetches_remaining_until_visible(
1022        &self,
1023        topic_name: &str,
1024        fetches_remaining_until_visible: i32,
1025    ) -> Result<(), Error> {
1026        let mut state = self.state.lock().unwrap();
1027        let metadata = state
1028            .all_topics
1029            .get_mut(topic_name)
1030            .ok_or_else(|| Error::local_illegal_argument(format!("No such topic as {topic_name}")))?;
1031        metadata.fetches_remaining_until_visible = fetches_remaining_until_visible;
1032        Ok(())
1033    }
1034
1035    /// Causes the next `number_of_requests` operations to fail with a timeout.
1036    ///
1037    /// # Arguments
1038    ///
1039    /// - `number_of_requests` - The number of operations to fail
1040    #[doc(alias = "org.apache.kafka.clients.admin.MockAdminClient#timeoutNextRequest")]
1041    pub fn timeout_next_request(&self, number_of_requests: i32) {
1042        self.state.lock().unwrap().timeout_next_requests = number_of_requests;
1043    }
1044}
1045
1046fn timeout_error() -> Error {
1047    Error::timeout("The mock timed out the request.".to_string())
1048}
1049
1050/// Current wall-clock time in milliseconds since the Unix epoch, mirroring
1051/// Java's `System.currentTimeMillis()` used by the mock's delegation-token
1052/// methods.
1053fn current_time_millis() -> i64 {
1054    std::time::SystemTime::now()
1055        .duration_since(std::time::UNIX_EPOCH)
1056        .expect("system clock before Unix epoch")
1057        .as_millis() as i64
1058}
1059
1060/// Computes the `PartitionReassignment` for a partition from the mock's stored
1061/// reassignments and topic metadata.
1062///
1063/// Mirrors `MockAdminClient#findPartitionReassignment`. Returns `Ok(None)` if
1064/// there is no stored reassignment for the partition.
1065///
1066/// # Errors
1067///
1068/// Returns an error when a stored reassignment references a partition with no
1069/// metadata. Java throws a bare `RuntimeException` from both of these branches;
1070/// since `list_partition_reassignments` cannot throw, the caller fails the
1071/// result's future instead (CLAUDE.md §12.1 — a panic here would unwind into C
1072/// through the FFI). This is *not* only reachable through internal corruption:
1073/// `deleteTopics` removes the topic from `all_topics` without pruning
1074/// `reassignments`, exactly as Java's does, so any legal
1075/// alter-reassignment/delete-topic/list-reassignments sequence reaches it.
1076fn find_partition_reassignment(
1077    state: &State,
1078    partition: &TopicPartition,
1079) -> Result<Option<PartitionReassignment>, Error> {
1080    let Some(reassignment) = state.reassignments.get(partition) else {
1081        return Ok(None);
1082    };
1083    let metadata = state.all_topics.get(partition.topic()).ok_or_else(|| {
1084        Error::local_illegal_state(format!(
1085            "Internal MockAdminClient logic error: found reassignment for {partition}, but no TopicMetadata"
1086        ))
1087    })?;
1088    let info = metadata.partitions.get(partition.partition() as usize).ok_or_else(|| {
1089        Error::local_illegal_state(format!(
1090            "Internal MockAdminClient logic error: found reassignment for {partition}, but no TopicPartitionInfo"
1091        ))
1092    })?;
1093    let target_replicas = reassignment.target_replicas();
1094    let mut replicas = Vec::new();
1095    let mut removing_replicas = Vec::new();
1096    let mut adding_replicas: Vec<i32> = target_replicas.to_vec();
1097    for node in info.replicas() {
1098        replicas.push(node.id());
1099        if !target_replicas.contains(&node.id()) {
1100            removing_replicas.push(node.id());
1101        }
1102        if let Some(pos) = adding_replicas.iter().position(|&id| id == node.id()) {
1103            adding_replicas.remove(pos);
1104        }
1105    }
1106    Ok(Some(PartitionReassignment::new(replicas, adding_replicas, removing_replicas)))
1107}
1108
1109fn config_from_new_topic(new_topic: &NewTopic) -> Config {
1110    let entries = new_topic
1111        .configs()
1112        .map(|configs| {
1113            configs
1114                .iter()
1115                .map(|(k, v)| ConfigEntry::new(k.clone(), Some(v.clone())))
1116                .collect::<Vec<_>>()
1117        })
1118        .unwrap_or_default();
1119    Config::new(entries)
1120}
1121
1122/// Builds a [`Config`] from an in-memory config map; a config set to `null`
1123/// gives an entry with a `None` value, as Java's `new ConfigEntry(key, null)`.
1124///
1125/// Corresponds to `MockAdminClient.toConfigObject`.
1126fn to_config_object(map: &BTreeMap<String, Option<String>>) -> Config {
1127    let entries = map
1128        .iter()
1129        .map(|(k, v)| ConfigEntry::new(k.clone(), v.clone()))
1130        .collect::<Vec<_>>();
1131    Config::new(entries)
1132}
1133
1134/// Applies a sequence of [`AlterConfigOp`]s to an in-memory config map.
1135///
1136/// A `Set` stores the entry's value as given, `None` included, as Java's
1137/// `newMap.put(name, value)` stores a `null` value (`MockAdminClient#handleIncrementalResourceAlteration`).
1138///
1139/// Returns an error for an unsupported op type (mirrors Java's
1140/// `InvalidRequestException`). `Append` / `Subtract` are list-type operations
1141/// that Java's mock does not implement, matching its `default` branch.
1142fn apply_alter_ops(map: &mut BTreeMap<String, Option<String>>, ops: &[AlterConfigOp]) -> Result<(), Error> {
1143    for op in ops {
1144        match op.op_type() {
1145            OpType::Set => {
1146                map.insert(
1147                    op.config_entry().name().to_string(),
1148                    op.config_entry().value().map(str::to_string),
1149                );
1150            },
1151            OpType::Delete => {
1152                map.remove(op.config_entry().name());
1153            },
1154            other => {
1155                return Err(Error::with_message(
1156                    Errors::InvalidRequest,
1157                    format!("Unsupported op type {other:?}"),
1158                ));
1159            },
1160        }
1161    }
1162    Ok(())
1163}
1164
1165/// Reads the config description for a single resource.
1166///
1167/// Corresponds to `MockAdminClient.getResourceDescription`.
1168fn get_resource_description(state: &mut State, resource: &ConfigResource) -> Result<Config, Error> {
1169    match resource.r#type() {
1170        config_resource::Type::Broker => {
1171            let broker_id: usize = resource.name().parse().map_err(|_| {
1172                Error::with_message(Errors::InvalidRequest, format!("Broker {} not found.", resource.name()))
1173            })?;
1174            match state.broker_configs.get(broker_id) {
1175                Some(config) => Ok(to_config_object(config)),
1176                None => Err(Error::with_message(
1177                    Errors::InvalidRequest,
1178                    format!("Broker {} not found.", resource.name()),
1179                )),
1180            }
1181        },
1182        config_resource::Type::Topic => {
1183            if let Some(metadata) = state.all_topics.get_mut(resource.name())
1184                && !metadata.marked_for_deletion
1185            {
1186                if metadata.fetches_remaining_until_visible > 0 {
1187                    metadata.fetches_remaining_until_visible = (metadata.fetches_remaining_until_visible - 1).max(0);
1188                } else {
1189                    let config = metadata.configs.clone().unwrap_or_default();
1190                    return Ok(to_config_object(&config));
1191                }
1192            }
1193            Err(Error::with_message(
1194                Errors::UnknownTopicOrPartition,
1195                format!("Resource {resource} not found."),
1196            ))
1197        },
1198        config_resource::Type::ClientMetrics => {
1199            let resource_name = resource.name();
1200            if resource_name.is_empty() {
1201                return Err(Error::with_message(Errors::InvalidRequest, "Empty resource name"));
1202            }
1203            let config = state.client_metrics_configs.get(resource_name).cloned().unwrap_or_default();
1204            Ok(to_config_object(&config))
1205        },
1206        config_resource::Type::Group => {
1207            let resource_name = resource.name();
1208            if resource_name.is_empty() {
1209                return Err(Error::with_message(Errors::InvalidRequest, "Empty resource name"));
1210            }
1211            let mut group_config = state.group_configs.get(resource_name).cloned().unwrap_or_default();
1212            // Overlay the defaults with Java's `putIfAbsent`, which also
1213            // replaces a key set to `null` (`MockAdminClient#getResourceDescription`).
1214            for (k, v) in &state.default_group_configs {
1215                let value = group_config.entry(k.clone()).or_insert(None);
1216                if value.is_none() {
1217                    *value = Some(v.clone());
1218                }
1219            }
1220            Ok(to_config_object(&group_config))
1221        },
1222        // Java throws `UnsupportedOperationException("Not implemented yet")`
1223        // (in
1224        // `org.apache.kafka.clients.admin.MockAdminClient#getResourceDescription`).
1225        _ => Err(Error::local_unsupported_operation("Not implemented yet")),
1226    }
1227}
1228
1229/// Applies an incremental config alteration to a single resource.
1230///
1231/// Corresponds to `MockAdminClient.handleIncrementalResourceAlteration`.
1232fn handle_incremental_resource_alteration(
1233    state: &mut State,
1234    resource: &ConfigResource,
1235    ops: &[AlterConfigOp],
1236) -> Result<(), Error> {
1237    match resource.r#type() {
1238        config_resource::Type::Broker => {
1239            let broker_id: usize = resource.name().parse().map_err(|_| {
1240                Error::with_message(Errors::InvalidRequest, format!("no such broker as {}", resource.name()))
1241            })?;
1242            if broker_id >= state.broker_configs.len() {
1243                return Err(Error::with_message(
1244                    Errors::InvalidRequest,
1245                    format!("no such broker as {broker_id}"),
1246                ));
1247            }
1248            let mut new_map = state.broker_configs[broker_id].clone();
1249            apply_alter_ops(&mut new_map, ops)?;
1250            state.broker_configs[broker_id] = new_map;
1251            Ok(())
1252        },
1253        config_resource::Type::Topic => {
1254            let metadata = state.all_topics.get_mut(resource.name()).ok_or_else(|| {
1255                Error::with_message(Errors::UnknownTopicOrPartition, format!("No such topic as {}", resource.name()))
1256            })?;
1257            let mut new_map = metadata.configs.clone().unwrap_or_default();
1258            apply_alter_ops(&mut new_map, ops)?;
1259            metadata.configs = Some(new_map);
1260            Ok(())
1261        },
1262        config_resource::Type::ClientMetrics => {
1263            let resource_name = resource.name();
1264            if resource_name.is_empty() {
1265                return Err(Error::with_message(Errors::InvalidRequest, "Empty resource name"));
1266            }
1267            let mut new_map = state.client_metrics_configs.get(resource_name).cloned().unwrap_or_default();
1268            apply_alter_ops(&mut new_map, ops)?;
1269            state.client_metrics_configs.insert(resource_name.to_string(), new_map);
1270            Ok(())
1271        },
1272        config_resource::Type::Group => {
1273            let resource_name = resource.name();
1274            if resource_name.is_empty() {
1275                return Err(Error::with_message(Errors::InvalidRequest, "Empty resource name"));
1276            }
1277            let mut new_map = state.group_configs.get(resource_name).cloned().unwrap_or_default();
1278            apply_alter_ops(&mut new_map, ops)?;
1279            state.group_configs.insert(resource_name.to_string(), new_map);
1280            Ok(())
1281        },
1282        // Java returns `new UnsupportedOperationException()`, with no message
1283        // (in
1284        // `org.apache.kafka.clients.admin.MockAdminClient#handleIncrementalResourceAlteration`).
1285        _ => Err(Error::local_unsupported_operation("")),
1286    }
1287}
1288
1289#[async_trait]
1290impl Admin for MockAdminClient {
1291    fn create_topics_with_options(&self, new_topics: &[NewTopic], _options: CreateTopicsOptions) -> CreateTopicsResult {
1292        let mut state = self.state.lock().unwrap();
1293        let mut result: HashMap<String, crate::common::KafkaFuture<TopicMetadataAndConfig>> = HashMap::new();
1294
1295        if state.timeout_next_requests > 0 {
1296            for new_topic in new_topics {
1297                let handle: KafkaFutureImpl<TopicMetadataAndConfig> = KafkaFutureImpl::new();
1298                handle.complete_with_error(timeout_error());
1299                result.insert(new_topic.name().to_string(), handle.future());
1300            }
1301            state.timeout_next_requests -= 1;
1302            return CreateTopicsResult::new(result);
1303        }
1304
1305        for new_topic in new_topics {
1306            let handle: KafkaFutureImpl<TopicMetadataAndConfig> = KafkaFutureImpl::new();
1307            let topic_name = new_topic.name().to_string();
1308
1309            if state.all_topics.contains_key(&topic_name) {
1310                handle.complete_with_error(Error::with_message(
1311                    Errors::TopicAlreadyExists,
1312                    format!("Topic {topic_name} exists already."),
1313                ));
1314                result.insert(topic_name, handle.future());
1315                continue;
1316            }
1317
1318            // Java widens the `short` to `int replicationFactor` (in
1319            // `org.apache.kafka.clients.admin.MockAdminClient#createTopics`).
1320            let mut replication_factor = i32::from(new_topic.replication_factor());
1321            if replication_factor == -1 {
1322                replication_factor = state.default_replication_factor;
1323            }
1324            if replication_factor as usize > state.brokers.len() {
1325                handle.complete_with_error(Error::with_message(
1326                    Errors::InvalidReplicationFactor,
1327                    format!(
1328                        "Replication factor: {} is larger than brokers: {}",
1329                        new_topic.replication_factor(),
1330                        state.brokers.len()
1331                    ),
1332                ));
1333                result.insert(topic_name, handle.future());
1334                continue;
1335            }
1336
1337            let replicas: Vec<Node> = state.brokers[..replication_factor as usize].to_vec();
1338            let mut number_of_partitions = new_topic.num_partitions();
1339            if number_of_partitions == -1 {
1340                number_of_partitions = state.default_partitions;
1341            }
1342            let leader = state.brokers[0].clone();
1343            // Every partition of this topic shares the same leader (above), so
1344            // check its log directories once, before building `partitions`.
1345            // Java's `brokerLogDirs.get(id).get(0)` (in
1346            // `org.apache.kafka.clients.admin.MockAdminClient#createTopics`)
1347            // throws an unchecked `IndexOutOfBoundsException` for a leader whose
1348            // id is not an index of `brokerLogDirs`, and for a broker with no log
1349            // directories; `add_topic` already translates the identical situation
1350            // as an error instead of a panic (CLAUDE.md §10.1), so
1351            // `create_topics` fails the topic's future the same way here. Java
1352            // reads `brokerLogDirs` only inside its per-partition loop, so a
1353            // topic with no partitions never looks it up. Every partition is led
1354            // by `leader`, so they all start on its first log directory.
1355            let partition_log_dirs: Vec<String> = if number_of_partitions > 0 {
1356                match broker_log_dirs_of(&state.broker_log_dirs, leader.id()) {
1357                    Ok(dirs) => match dirs.first() {
1358                        Some(dir) => vec![dir.clone(); number_of_partitions as usize],
1359                        None => {
1360                            handle.complete_with_error(Error::local_illegal_argument(format!(
1361                                "Broker {} has no log directories.",
1362                                leader.id()
1363                            )));
1364                            result.insert(topic_name, handle.future());
1365                            continue;
1366                        },
1367                    },
1368                    Err(error) => {
1369                        handle.complete_with_error(error);
1370                        result.insert(topic_name, handle.future());
1371                        continue;
1372                    },
1373                }
1374            } else {
1375                Vec::new()
1376            };
1377            let partitions: Vec<TopicPartitionInfo> = (0..number_of_partitions)
1378                .map(|i| {
1379                    TopicPartitionInfo::with_elr_last_known_elr(
1380                        i,
1381                        Some(leader.clone()),
1382                        replicas.clone(),
1383                        Vec::new(),
1384                        Vec::new(),
1385                        Vec::new(),
1386                    )
1387                })
1388                .collect();
1389
1390            let topic_id = Uuid::random_uuid();
1391            state.topic_ids.insert(topic_name.clone(), topic_id);
1392            state.topic_names.insert(topic_id, topic_name.clone());
1393            state.all_topics.insert(
1394                topic_name.clone(),
1395                TopicMetadata {
1396                    topic_id,
1397                    is_internal: false,
1398                    partitions,
1399                    partition_log_dirs,
1400                    // Java stores the map as given (`MockAdminClient#createTopics`).
1401                    configs: new_topic
1402                        .configs()
1403                        .map(|configs| configs.iter().map(|(k, v)| (k.clone(), Some(v.clone()))).collect()),
1404                    marked_for_deletion: false,
1405                    fetches_remaining_until_visible: 0,
1406                },
1407            );
1408            handle.complete(TopicMetadataAndConfig::new(
1409                topic_id,
1410                number_of_partitions,
1411                replication_factor,
1412                config_from_new_topic(new_topic),
1413            ));
1414            result.insert(topic_name, handle.future());
1415        }
1416
1417        CreateTopicsResult::new(result)
1418    }
1419
1420    fn delete_topics_with_topic_collection_options(
1421        &self,
1422        topics: TopicCollection,
1423        _options: DeleteTopicsOptions,
1424    ) -> DeleteTopicsResult {
1425        let mut state = self.state.lock().unwrap();
1426        match topics {
1427            TopicCollection::TopicNames(collection) => {
1428                let mut result = HashMap::new();
1429                for name in collection.topic_names().iter().cloned() {
1430                    let handle: KafkaFutureImpl<()> = KafkaFutureImpl::new();
1431                    if state.timeout_next_requests > 0 {
1432                        handle.complete_with_error(timeout_error());
1433                    } else if state.all_topics.remove(&name).is_none() {
1434                        handle.complete_with_error(Error::with_message(
1435                            Errors::UnknownTopicOrPartition,
1436                            format!("Topic {name} does not exist."),
1437                        ));
1438                    } else {
1439                        if let Some(id) = state.topic_ids.remove(&name) {
1440                            state.topic_names.remove(&id);
1441                        }
1442                        handle.complete(());
1443                    }
1444                    result.insert(name, handle.future());
1445                }
1446                if state.timeout_next_requests > 0 {
1447                    state.timeout_next_requests -= 1;
1448                }
1449                DeleteTopicsResult::of_topic_names(result)
1450            },
1451            TopicCollection::TopicIds(collection) => {
1452                let mut result = HashMap::new();
1453                for id in collection.topic_ids().iter().copied() {
1454                    let handle: KafkaFutureImpl<()> = KafkaFutureImpl::new();
1455                    if state.timeout_next_requests > 0 {
1456                        handle.complete_with_error(timeout_error());
1457                    } else {
1458                        let name = state.topic_names.remove(&id);
1459                        let removed = name.as_ref().is_some_and(|n| state.all_topics.remove(n).is_some());
1460                        if !removed {
1461                            handle.complete_with_error(Error::with_message(
1462                                Errors::UnknownTopicOrPartition,
1463                                format!("Topic {id} does not exist."),
1464                            ));
1465                        } else {
1466                            if let Some(n) = name {
1467                                state.topic_ids.remove(&n);
1468                            }
1469                            handle.complete(());
1470                        }
1471                    }
1472                    result.insert(id, handle.future());
1473                }
1474                if state.timeout_next_requests > 0 {
1475                    state.timeout_next_requests -= 1;
1476                }
1477                DeleteTopicsResult::of_topic_ids(result)
1478            },
1479        }
1480    }
1481
1482    fn list_topics_with_options(&self, _options: ListTopicsOptions) -> ListTopicsResult {
1483        let mut state = self.state.lock().unwrap();
1484        let handle: KafkaFutureImpl<HashMap<String, TopicListing>> = KafkaFutureImpl::new();
1485
1486        if state.timeout_next_requests > 0 {
1487            handle.complete_with_error(timeout_error());
1488            state.timeout_next_requests -= 1;
1489            return ListTopicsResult::new(handle.future());
1490        }
1491
1492        let mut listings = HashMap::new();
1493        for (name, metadata) in state.all_topics.iter_mut() {
1494            if metadata.fetches_remaining_until_visible > 0 {
1495                metadata.fetches_remaining_until_visible -= 1;
1496            } else {
1497                listings.insert(
1498                    name.clone(),
1499                    TopicListing::new(name.clone(), metadata.topic_id, metadata.is_internal),
1500                );
1501            }
1502        }
1503        handle.complete(listings);
1504        ListTopicsResult::new(handle.future())
1505    }
1506
1507    fn describe_topics_with_topics_options(
1508        &self,
1509        topics: TopicCollection,
1510        _options: DescribeTopicsOptions,
1511    ) -> DescribeTopicsResult {
1512        let mut state = self.state.lock().unwrap();
1513        match topics {
1514            TopicCollection::TopicNames(collection) => {
1515                let mut result = HashMap::new();
1516                let timing_out = state.timeout_next_requests > 0;
1517                for requested in collection.topic_names() {
1518                    let handle: KafkaFutureImpl<TopicDescription> = KafkaFutureImpl::new();
1519                    if timing_out {
1520                        handle.complete_with_error(timeout_error());
1521                        result.insert(requested.clone(), handle.future());
1522                        continue;
1523                    }
1524                    // Java's
1525                    // `org.apache.kafka.clients.admin.MockAdminClient#handleDescribeTopicsByNames`:
1526                    // a visible topic is described unless its fetch countdown is still
1527                    // running, in which case the countdown is decremented and the topic is
1528                    // reported as not found.
1529                    let visible = match state.all_topics.get_mut(requested) {
1530                        Some(metadata) if !metadata.marked_for_deletion => {
1531                            if metadata.fetches_remaining_until_visible > 0 {
1532                                metadata.fetches_remaining_until_visible -= 1;
1533                                None
1534                            } else {
1535                                Some(&*metadata)
1536                            }
1537                        },
1538                        _ => None,
1539                    };
1540                    match visible {
1541                        Some(metadata) => {
1542                            handle.complete(TopicDescription::with_authorized_operations_topic_id(
1543                                requested.clone(),
1544                                metadata.is_internal,
1545                                metadata.partitions.clone(),
1546                                // Java's mock passes `Collections.emptySet()` here, i.e. a
1547                                // reported-but-empty set rather than null.
1548                                Some(std::collections::BTreeSet::new()),
1549                                metadata.topic_id,
1550                            ));
1551                        },
1552                        _ => {
1553                            handle.complete_with_error(Error::with_message(
1554                                Errors::UnknownTopicOrPartition,
1555                                format!("Topic {requested} not found."),
1556                            ));
1557                        },
1558                    }
1559                    result.insert(requested.clone(), handle.future());
1560                }
1561                if timing_out {
1562                    state.timeout_next_requests -= 1;
1563                }
1564                DescribeTopicsResult::of_topic_names(result)
1565            },
1566            TopicCollection::TopicIds(collection) => {
1567                let mut result = HashMap::new();
1568                let timing_out = state.timeout_next_requests > 0;
1569                for requested in collection.topic_ids() {
1570                    let handle: KafkaFutureImpl<TopicDescription> = KafkaFutureImpl::new();
1571                    if timing_out {
1572                        handle.complete_with_error(timeout_error());
1573                        result.insert(*requested, handle.future());
1574                        continue;
1575                    }
1576                    // Java's
1577                    // `org.apache.kafka.clients.admin.MockAdminClient#handleDescribeTopicsUsingIds`,
1578                    // with the same fetch countdown as the by-name path.
1579                    let state = &mut *state;
1580                    let found = match state.topic_names.get(requested) {
1581                        Some(name) => match state.all_topics.get_mut(name) {
1582                            Some(metadata) if !metadata.marked_for_deletion => {
1583                                if metadata.fetches_remaining_until_visible > 0 {
1584                                    metadata.fetches_remaining_until_visible -= 1;
1585                                    None
1586                                } else {
1587                                    Some((name.clone(), &*metadata))
1588                                }
1589                            },
1590                            _ => None,
1591                        },
1592                        None => None,
1593                    };
1594                    match found {
1595                        Some((name, metadata)) => {
1596                            handle.complete(TopicDescription::with_authorized_operations_topic_id(
1597                                name,
1598                                metadata.is_internal,
1599                                metadata.partitions.clone(),
1600                                // Java's mock passes `Collections.emptySet()` here, i.e. a
1601                                // reported-but-empty set rather than null.
1602                                Some(std::collections::BTreeSet::new()),
1603                                *requested,
1604                            ));
1605                        },
1606                        None => {
1607                            handle.complete_with_error(Error::with_message(
1608                                Errors::UnknownTopicId,
1609                                // Java's text has no space after "id" (in
1610                                // `org.apache.kafka.clients.admin.MockAdminClient#handleDescribeTopicsUsingIds`).
1611                                format!("Topic id{requested} not found."),
1612                            ));
1613                        },
1614                    }
1615                    result.insert(*requested, handle.future());
1616                }
1617                if timing_out {
1618                    state.timeout_next_requests -= 1;
1619                }
1620                DescribeTopicsResult::of_topic_ids(result)
1621            },
1622        }
1623    }
1624
1625    fn create_partitions_with_options(
1626        &self,
1627        new_partitions: &HashMap<String, NewPartitions>,
1628        _options: CreatePartitionsOptions,
1629    ) -> CreatePartitionsResult {
1630        // Java's
1631        // `org.apache.kafka.clients.admin.MockAdminClient#createPartitions`
1632        // throws `UnsupportedOperationException("Not implemented yet")`. Per
1633        // `.claude/rules/admin-client.md` §9 the Rust mock returns an
1634        // "unsupported" `Error` per key instead of panicking (faithful
1635        // translation of the Java behavior).
1636        let mut result = HashMap::new();
1637        for topic in new_partitions.keys() {
1638            let handle: KafkaFutureImpl<()> = KafkaFutureImpl::new();
1639            handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
1640            result.insert(topic.clone(), handle.future());
1641        }
1642        CreatePartitionsResult::new(result)
1643    }
1644
1645    fn delete_records_with_options(
1646        &self,
1647        records_to_delete: &HashMap<TopicPartition, RecordsToDelete>,
1648        _options: DeleteRecordsOptions,
1649    ) -> DeleteRecordsResult {
1650        // Java's `org.apache.kafka.clients.admin.MockAdminClient#deleteRecords`
1651        // returns an empty result for an empty request and otherwise throws
1652        // `UnsupportedOperationException("Not implemented yet")`. Per
1653        // `.claude/rules/admin-client.md` §9 the non-empty case returns an
1654        // "unsupported" `Error` per key instead of panicking (faithful
1655        // translation of the Java behavior).
1656        let mut result = HashMap::new();
1657        for topic_partition in records_to_delete.keys() {
1658            let handle: KafkaFutureImpl<DeletedRecords> = KafkaFutureImpl::new();
1659            handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
1660            result.insert(topic_partition.clone(), handle.future());
1661        }
1662        DeleteRecordsResult::new(result)
1663    }
1664
1665    fn describe_producers_with_options(
1666        &self,
1667        partitions: &[TopicPartition],
1668        _options: DescribeProducersOptions,
1669    ) -> DescribeProducersResult {
1670        // Java's
1671        // `org.apache.kafka.clients.admin.MockAdminClient#describeProducers`
1672        // throws `UnsupportedOperationException("Not implemented yet")`. Per
1673        // `.claude/rules/admin-client.md` §9 the Rust mock returns an
1674        // "unsupported" `Error` per key instead of panicking (faithful
1675        // translation of the Java behavior).
1676        let mut result = HashMap::new();
1677        for topic_partition in partitions {
1678            let handle: KafkaFutureImpl<PartitionProducerState> = KafkaFutureImpl::new();
1679            handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
1680            result.insert(topic_partition.clone(), handle.future());
1681        }
1682        DescribeProducersResult::new(result)
1683    }
1684
1685    fn unregister_controller_with_options(
1686        &self,
1687        _controller_id: i32,
1688        _options: UnregisterControllerOptions,
1689    ) -> UnregisterControllerResult {
1690        // Java's `MockAdminClient.unregisterController` (KAFKA-20395): a Raft
1691        // controller quorum succeeds at once; otherwise the future fails with
1692        // `new UnsupportedVersionException("")` — an empty message, kept verbatim.
1693        let handle: KafkaFutureImpl<()> = KafkaFutureImpl::new();
1694        if self.state.lock().unwrap().using_raft_controller {
1695            handle.complete(());
1696        } else {
1697            handle.complete_with_error(Error::unsupported_version(""));
1698        }
1699        UnregisterControllerResult::new(handle.future())
1700    }
1701
1702    fn abort_transaction_with_options(
1703        &self,
1704        spec: AbortTransactionSpec,
1705        _options: AbortTransactionOptions,
1706    ) -> AbortTransactionResult {
1707        // Java's
1708        // `org.apache.kafka.clients.admin.MockAdminClient#abortTransaction`
1709        // throws `UnsupportedOperationException("Not implemented yet")`. Per
1710        // `.claude/rules/admin-client.md` §9 the Rust mock returns an
1711        // "unsupported" `Error` per key instead of panicking (faithful
1712        // translation of the Java behavior).
1713        let handle: KafkaFutureImpl<()> = KafkaFutureImpl::new();
1714        handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
1715        AbortTransactionResult::new(HashMap::from([(spec.topic_partition().clone(), handle.future())]))
1716    }
1717
1718    fn describe_transactions_with_options(
1719        &self,
1720        transactional_ids: &[String],
1721        _options: DescribeTransactionsOptions,
1722    ) -> DescribeTransactionsResult {
1723        // Java's
1724        // `org.apache.kafka.clients.admin.MockAdminClient#describeTransactions`
1725        // throws `UnsupportedOperationException("Not implemented yet")`. Per
1726        // `.claude/rules/admin-client.md` §9 the Rust mock returns an "unsupported"
1727        // `Error` per key instead of panicking (faithful translation of the Java
1728        // behavior).
1729        let mut result = HashMap::new();
1730        for id in transactional_ids {
1731            let handle: KafkaFutureImpl<TransactionDescription> = KafkaFutureImpl::new();
1732            handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
1733            result.insert(id.clone(), handle.future());
1734        }
1735        DescribeTransactionsResult::new(result)
1736    }
1737
1738    fn fence_producers_with_options(
1739        &self,
1740        transactional_ids: &[String],
1741        _options: FenceProducersOptions,
1742    ) -> FenceProducersResult {
1743        // Java's
1744        // `org.apache.kafka.clients.admin.MockAdminClient#fenceProducers`
1745        // throws `UnsupportedOperationException("Not implemented yet")`. Per
1746        // `.claude/rules/admin-client.md` §9 the Rust mock returns an
1747        // "unsupported" `Error` per key instead of panicking (faithful
1748        // translation of the Java behavior).
1749        let mut result = HashMap::new();
1750        for id in transactional_ids {
1751            let handle: KafkaFutureImpl<ProducerIdAndEpoch> = KafkaFutureImpl::new();
1752            handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
1753            result.insert(id.clone(), handle.future());
1754        }
1755        FenceProducersResult::new(result)
1756    }
1757
1758    fn list_transactions_with_options(&self, _options: ListTransactionsOptions) -> ListTransactionsResult {
1759        // Java's
1760        // `org.apache.kafka.clients.admin.MockAdminClient#listTransactions`
1761        // throws `UnsupportedOperationException("Not implemented yet")`. Per
1762        // `.claude/rules/admin-client.md` §9 the Rust mock completes the
1763        // top-level future exceptionally instead of panicking.
1764        let handle: KafkaFutureImpl<HashMap<i32, KafkaFuture<Vec<TransactionListing>>>> = KafkaFutureImpl::new();
1765        handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
1766        ListTransactionsResult::new(handle.future())
1767    }
1768
1769    fn force_terminate_transaction_with_options(
1770        &self,
1771        transactional_id: &str,
1772        options: TerminateTransactionOptions,
1773    ) -> TerminateTransactionResult {
1774        // Java's
1775        // `org.apache.kafka.clients.admin.MockAdminClient#forceTerminateTransaction`
1776        // throws `UnsupportedOperationException("Not implemented yet")`
1777        // directly — it does *not* delegate. It is the production
1778        // `org.apache.kafka.clients.admin.KafkaAdminClient#forceTerminateTransaction`
1779        // that delegates ("Simply leverage the existing fenceProducers
1780        // implementation"). The Rust mock mirrors that production
1781        // delegation, which lands in the mock's own `fence_producers` — itself
1782        // "Not implemented yet" — so the resulting future carries the same
1783        // "unsupported" error Java's mock throws, by a different route.
1784        let mut fence_options = FenceProducersOptions::new();
1785        if options.timeout_ms().is_some() {
1786            fence_options = fence_options.set_timeout_ms(options.timeout_ms());
1787        }
1788        let ids = vec![transactional_id.to_string()];
1789        let fence_result = self.fence_producers_with_options(&ids, fence_options);
1790        let future = fence_result
1791            .fenced_producers()
1792            .get(transactional_id)
1793            .cloned()
1794            .expect("the transactional id was included in the fenceProducers request");
1795        TerminateTransactionResult::new(future)
1796    }
1797
1798    fn describe_cluster_with_options(&self, _options: DescribeClusterOptions) -> DescribeClusterResult {
1799        let mut state = self.state.lock().unwrap();
1800        let nodes: KafkaFutureImpl<Vec<Node>> = KafkaFutureImpl::new();
1801        let controller: KafkaFutureImpl<Option<Node>> = KafkaFutureImpl::new();
1802        let cluster_id: KafkaFutureImpl<String> = KafkaFutureImpl::new();
1803        let authorized_operations: KafkaFutureImpl<Option<BTreeSet<AclOperation>>> = KafkaFutureImpl::new();
1804
1805        if state.timeout_next_requests > 0 {
1806            let err = timeout_error();
1807            nodes.complete_with_error(err.clone());
1808            controller.complete_with_error(err.clone());
1809            cluster_id.complete_with_error(err.clone());
1810            authorized_operations.complete_with_error(err);
1811            state.timeout_next_requests -= 1;
1812        } else {
1813            nodes.complete(state.brokers.clone());
1814            controller.complete(Some(state.controller.clone()));
1815            cluster_id.complete(state.cluster_id.clone());
1816            // Java completes with an empty set (not null).
1817            authorized_operations.complete(Some(BTreeSet::new()));
1818        }
1819        DescribeClusterResult::new(
1820            nodes.future(),
1821            controller.future(),
1822            cluster_id.future(),
1823            authorized_operations.future(),
1824        )
1825    }
1826
1827    fn describe_configs_with_options(
1828        &self,
1829        config_resources: &[ConfigResource],
1830        _options: DescribeConfigsOptions,
1831    ) -> DescribeConfigsResult {
1832        let mut state = self.state.lock().unwrap();
1833
1834        if state.timeout_next_requests > 0 {
1835            let mut result = HashMap::new();
1836            for resource in config_resources {
1837                let handle: KafkaFutureImpl<Config> = KafkaFutureImpl::new();
1838                handle.complete_with_error(timeout_error());
1839                result.insert(resource.clone(), handle.future());
1840            }
1841            state.timeout_next_requests -= 1;
1842            return DescribeConfigsResult::new(result);
1843        }
1844
1845        let mut result = HashMap::new();
1846        for resource in config_resources {
1847            let handle: KafkaFutureImpl<Config> = KafkaFutureImpl::new();
1848            match get_resource_description(&mut state, resource) {
1849                Ok(config) => handle.complete(config),
1850                Err(e) => handle.complete_with_error(e),
1851            };
1852            result.insert(resource.clone(), handle.future());
1853        }
1854        DescribeConfigsResult::new(result)
1855    }
1856
1857    fn incremental_alter_configs_with_options(
1858        &self,
1859        configs: &HashMap<ConfigResource, Vec<AlterConfigOp>>,
1860        _options: AlterConfigsOptions,
1861    ) -> AlterConfigsResult {
1862        let mut state = self.state.lock().unwrap();
1863        let mut result = HashMap::new();
1864        for (resource, ops) in configs {
1865            let handle: KafkaFutureImpl<()> = KafkaFutureImpl::new();
1866            match handle_incremental_resource_alteration(&mut state, resource, ops) {
1867                Ok(()) => handle.complete(()),
1868                Err(e) => handle.complete_with_error(e),
1869            };
1870            result.insert(resource.clone(), handle.future());
1871        }
1872        AlterConfigsResult::new(result)
1873    }
1874
1875    fn list_config_resources_with_options(
1876        &self,
1877        config_resource_types: &HashSet<config_resource::Type>,
1878        _options: ListConfigResourcesOptions,
1879    ) -> ListConfigResourcesResult {
1880        let state = self.state.lock().unwrap();
1881        let handle: KafkaFutureImpl<Vec<ConfigResource>> = KafkaFutureImpl::new();
1882        // Collect into a set to de-duplicate, mirroring Java's `HashSet`.
1883        let mut config_resources: HashSet<ConfigResource> = HashSet::new();
1884        let all = config_resource_types.is_empty();
1885
1886        if all || config_resource_types.contains(&config_resource::Type::Topic) {
1887            for name in state.all_topics.keys() {
1888                config_resources.insert(ConfigResource::new(config_resource::Type::Topic, name.clone()));
1889            }
1890        }
1891        if all || config_resource_types.contains(&config_resource::Type::Broker) {
1892            for i in 0..state.brokers.len() {
1893                config_resources.insert(ConfigResource::new(config_resource::Type::Broker, i.to_string()));
1894            }
1895        }
1896        if all || config_resource_types.contains(&config_resource::Type::BrokerLogger) {
1897            for i in 0..state.brokers.len() {
1898                config_resources.insert(ConfigResource::new(config_resource::Type::BrokerLogger, i.to_string()));
1899            }
1900        }
1901        if all || config_resource_types.contains(&config_resource::Type::ClientMetrics) {
1902            for name in state.client_metrics_configs.keys() {
1903                config_resources.insert(ConfigResource::new(config_resource::Type::ClientMetrics, name.clone()));
1904            }
1905        }
1906        if all || config_resource_types.contains(&config_resource::Type::Group) {
1907            for name in state.group_configs.keys() {
1908                config_resources.insert(ConfigResource::new(config_resource::Type::Group, name.clone()));
1909            }
1910        }
1911        handle.complete(config_resources.into_iter().collect());
1912        ListConfigResourcesResult::new(handle.future())
1913    }
1914
1915    // Mirrors `MockAdminClient.describeLogDirs`.
1916    fn describe_log_dirs_with_options(
1917        &self,
1918        brokers: &[i32],
1919        _options: DescribeLogDirsOptions,
1920    ) -> DescribeLogDirsResult {
1921        let state = self.state.lock().unwrap();
1922        let mut unwrapped: HashMap<i32, HashMap<String, LogDirDescription>> = HashMap::new();
1923        for &broker in brokers {
1924            unwrapped.entry(broker).or_default();
1925        }
1926
1927        // Two deliberate divergences below, both skipping where Java throws.
1928        // Java dereferences `partitionLogDirs.get(0)` and
1929        // `unwrappedResults.get(node.id())` unchecked (in
1930        // `org.apache.kafka.clients.admin.MockAdminClient#describeLogDirs`), so
1931        // a topic with no log dirs raises `IndexOutOfBoundsException` and a
1932        // replica on a broker the caller did not ask about raises an NPE. Both
1933        // are latent defects in a test helper rather than a contract, and
1934        // reproducing them would mean panicking in a public API (CLAUDE.md
1935        // §12.1), so each case is skipped instead.
1936        for (topic_name, meta) in &state.all_topics {
1937            // For tests, we assume there will always be only 1 log-dir entry.
1938            let Some(log_dir) = meta.partition_log_dirs.first() else {
1939                continue;
1940            };
1941            for tp_info in &meta.partitions {
1942                for node in tp_info.replicas() {
1943                    let Some(map) = unwrapped.get_mut(&node.id()) else {
1944                        continue;
1945                    };
1946                    let existing = map
1947                        .remove(log_dir)
1948                        .unwrap_or_else(|| LogDirDescription::new(None, HashMap::new()));
1949                    let mut replica_infos = existing.replica_infos().clone();
1950                    replica_infos.insert(
1951                        TopicPartition::new(topic_name.clone(), tp_info.partition()),
1952                        ReplicaInfo::new(0, 0, false),
1953                    );
1954                    map.insert(
1955                        log_dir.clone(),
1956                        LogDirDescription::with_total_bytes_usable_bytes(
1957                            existing.error().cloned(),
1958                            replica_infos,
1959                            existing.total_bytes().unwrap_or(DescribeLogDirsResponse::UNKNOWN_VOLUME_BYTES),
1960                            existing.usable_bytes().unwrap_or(DescribeLogDirsResponse::UNKNOWN_VOLUME_BYTES),
1961                        ),
1962                    );
1963                }
1964            }
1965        }
1966
1967        let results = unwrapped
1968            .into_iter()
1969            .map(|(broker, map)| {
1970                let handle: KafkaFutureImpl<HashMap<String, LogDirDescription>> = KafkaFutureImpl::new();
1971                handle.complete(map);
1972                (broker, handle.future())
1973            })
1974            .collect();
1975        DescribeLogDirsResult::new(results)
1976    }
1977
1978    // Mirrors `MockAdminClient.alterReplicaLogDirs`.
1979    fn alter_replica_log_dirs_with_options(
1980        &self,
1981        replica_assignment: &HashMap<TopicPartitionReplica, String>,
1982        _options: AlterReplicaLogDirsOptions,
1983    ) -> AlterReplicaLogDirsResult {
1984        let mut state = self.state.lock().unwrap();
1985        let mut results = HashMap::new();
1986        for (replica, new_log_dir) in replica_assignment {
1987            let handle: KafkaFutureImpl<()> = KafkaFutureImpl::new();
1988            results.insert(replica.clone(), handle.future());
1989
1990            let dirs = state.broker_log_dirs.get(replica.broker_id() as usize);
1991            if dirs.is_none() {
1992                handle.complete_with_error(Error::with_message(
1993                    Errors::ReplicaNotAvailable,
1994                    format!("Can't find {replica}"),
1995                ));
1996                continue;
1997            }
1998            if !dirs.unwrap().contains(new_log_dir) {
1999                handle.complete_with_error(Error::with_message(
2000                    Errors::KafkaStorageError,
2001                    format!("Log directory {new_log_dir} is offline"),
2002                ));
2003                continue;
2004            }
2005            // `usize::try_from` (not an `i32` comparison) rejects a negative
2006            // partition number outright: `(len as i32) > replica.partition()`
2007            // is true for *any* non-negative length when the partition is
2008            // negative, so the old guard let a negative index through and
2009            // `as usize` then wrapped it to a huge index, panicking on the
2010            // `Vec` indexing below. `TopicPartitionReplica` has no
2011            // constructor-time validation (mirroring Java), so this was
2012            // reachable through the public `alter_replica_log_dirs` surface.
2013            let move_info = usize::try_from(replica.partition()).ok().and_then(|idx| {
2014                state.all_topics.get(replica.topic()).and_then(|meta| {
2015                    (idx < meta.partitions.len()).then(|| {
2016                        ReplicaLogDirInfo::new(
2017                            Some(meta.partition_log_dirs[idx].clone()),
2018                            0,
2019                            Some(new_log_dir.clone()),
2020                            0,
2021                        )
2022                    })
2023                })
2024            });
2025            match move_info {
2026                Some(info) => {
2027                    state.replica_moves.insert(replica.clone(), info);
2028                    handle.complete(());
2029                },
2030                None => {
2031                    handle.complete_with_error(Error::with_message(
2032                        Errors::ReplicaNotAvailable,
2033                        format!("Can't find {replica}"),
2034                    ));
2035                },
2036            }
2037        }
2038        AlterReplicaLogDirsResult::new(results)
2039    }
2040
2041    // Mirrors `MockAdminClient.describeReplicaLogDirs`.
2042    fn describe_replica_log_dirs_with_options(
2043        &self,
2044        replicas: &[TopicPartitionReplica],
2045        _options: DescribeReplicaLogDirsOptions,
2046    ) -> DescribeReplicaLogDirsResult {
2047        let state = self.state.lock().unwrap();
2048        let mut results = HashMap::new();
2049        for replica in replicas {
2050            // Replicas of unknown topics are silently omitted from the result,
2051            // mirroring Java's `if (topicMetadata != null)` guard.
2052            let Some(meta) = state.all_topics.get(replica.topic()) else {
2053                continue;
2054            };
2055            let handle: KafkaFutureImpl<ReplicaLogDirInfo> = KafkaFutureImpl::new();
2056            // `currentLogDir(replica)`: null if the partition has no log dir.
2057            // As in `alter_replica_log_dirs` above, `usize::try_from` rejects a
2058            // negative partition number instead of letting an `i32`
2059            // comparison (asymmetric around negative numbers) admit it and
2060            // then wrap to a huge index on the `as usize` cast below.
2061            let current_log_dir = usize::try_from(replica.partition())
2062                .ok()
2063                .filter(|&idx| idx < meta.partition_log_dirs.len())
2064                .map(|idx| meta.partition_log_dirs[idx].clone());
2065            match current_log_dir {
2066                None => {
2067                    handle.complete(ReplicaLogDirInfo::default());
2068                },
2069                Some(dir) => {
2070                    let info = state
2071                        .replica_moves
2072                        .get(replica)
2073                        .cloned()
2074                        .unwrap_or_else(|| ReplicaLogDirInfo::new(Some(dir), 0, None, 0));
2075                    handle.complete(info);
2076                },
2077            }
2078            results.insert(replica.clone(), handle.future());
2079        }
2080        DescribeReplicaLogDirsResult::new(results)
2081    }
2082
2083    // Mirrors `MockAdminClient.electLeaders`, which throws
2084    // `UnsupportedOperationException("Not implemented yet")`.
2085    // Translated to a future failed with an "unsupported" `Error`, not a panic.
2086    fn elect_leaders_with_options(
2087        &self,
2088        _election_type: ElectionType,
2089        _partitions: Option<HashSet<TopicPartition>>,
2090        _options: ElectLeadersOptions,
2091    ) -> ElectLeadersResult {
2092        let handle: KafkaFutureImpl<HashMap<TopicPartition, Option<Error>>> = KafkaFutureImpl::new();
2093        handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
2094        ElectLeadersResult::new(handle.future())
2095    }
2096
2097    // Mirrors `MockAdminClient.alterPartitionReassignments`.
2098    fn alter_partition_reassignments_with_options(
2099        &self,
2100        reassignments: &HashMap<TopicPartition, Option<NewPartitionReassignment>>,
2101        _options: AlterPartitionReassignmentsOptions,
2102    ) -> AlterPartitionReassignmentsResult {
2103        let mut state = self.state.lock().unwrap();
2104        let mut futures = HashMap::new();
2105        for (partition, new_reassignment) in reassignments {
2106            let future: KafkaFutureImpl<()> = KafkaFutureImpl::new();
2107            let topic_metadata = state.all_topics.get(partition.topic());
2108            let out_of_range = partition.partition() < 0
2109                || topic_metadata.is_none_or(|m| (m.partitions.len() as i32) <= partition.partition());
2110            if out_of_range {
2111                future.complete_with_error(Error::new(Errors::UnknownTopicOrPartition));
2112            } else if let Some(reassignment) = new_reassignment {
2113                state.reassignments.insert(partition.clone(), reassignment.clone());
2114                future.complete(());
2115            } else {
2116                state.reassignments.remove(partition);
2117                future.complete(());
2118            }
2119            futures.insert(partition.clone(), future.future());
2120        }
2121        AlterPartitionReassignmentsResult::new(futures)
2122    }
2123
2124    // Mirrors `MockAdminClient.listPartitionReassignments`.
2125    //
2126    // Java throws a `RuntimeException` from `findPartitionReassignment` when a
2127    // stored reassignment names a topic that is no longer in `allTopics`.
2128    // A synchronous throw is not representable in this signature, so the result's single future is failed
2129    // instead — the same accommodation `list_offsets` makes for a
2130    // `TimestampSpec`.
2131    fn list_partition_reassignments_with_partitions_options(
2132        &self,
2133        partitions: Option<HashSet<TopicPartition>>,
2134        _options: ListPartitionReassignmentsOptions,
2135    ) -> ListPartitionReassignmentsResult {
2136        let state = self.state.lock().unwrap();
2137        let mut map: HashMap<TopicPartition, PartitionReassignment> = HashMap::new();
2138        let requested: Vec<TopicPartition> = match partitions {
2139            Some(set) => set.into_iter().collect(),
2140            None => state.reassignments.keys().cloned().collect(),
2141        };
2142        let handle: KafkaFutureImpl<HashMap<TopicPartition, PartitionReassignment>> = KafkaFutureImpl::new();
2143        for partition in requested {
2144            match find_partition_reassignment(&state, &partition) {
2145                Ok(Some(reassignment)) => {
2146                    map.insert(partition, reassignment);
2147                },
2148                Ok(None) => {},
2149                Err(e) => {
2150                    handle.complete_with_error(e);
2151                    return ListPartitionReassignmentsResult::new(handle.future());
2152                },
2153            }
2154        }
2155        handle.complete(map);
2156        ListPartitionReassignmentsResult::new(handle.future())
2157    }
2158
2159    // Mirrors `MockAdminClient.listOffsets`.
2160    //
2161    // Java throws `UnsupportedOperationException` for a `TimestampSpec`
2162    // since a synchronous throw is not
2163    // representable in this signature, the affected partition's future is
2164    // failed with an "unsupported" `Error`.
2165    fn list_offsets_with_options(
2166        &self,
2167        topic_partition_offsets: &HashMap<TopicPartition, OffsetSpec>,
2168        _options: ListOffsetsOptions,
2169    ) -> ListOffsetsResult {
2170        let state = self.state.lock().unwrap();
2171        let mut futures = HashMap::new();
2172        for (tp, spec) in topic_partition_offsets {
2173            let future: KafkaFutureImpl<ListOffsetsResultInfo> = KafkaFutureImpl::new();
2174            match spec {
2175                OffsetSpec::Timestamp(_) => {
2176                    // Java's message is "Not implement yet" (sic), in
2177                    // `org.apache.kafka.clients.admin.MockAdminClient#listOffsets`.
2178                    future.complete_with_error(Error::local_unsupported_operation("Not implement yet"));
2179                },
2180                OffsetSpec::Earliest => {
2181                    let offset = state.beginning_offsets.get(tp).copied().unwrap_or(-1);
2182                    future.complete(ListOffsetsResultInfo::new(offset, -1, None));
2183                },
2184                _ => {
2185                    let offset = state.end_offsets.get(tp).copied().unwrap_or(-1);
2186                    future.complete(ListOffsetsResultInfo::new(offset, -1, None));
2187                },
2188            }
2189            futures.insert(tp.clone(), future.future());
2190        }
2191        ListOffsetsResult::new(futures)
2192    }
2193
2194    fn list_groups_with_options(&self, _options: ListGroupsOptions) -> ListGroupsResult {
2195        // Mirrors Java's `MockAdminClient.listGroups`: one CONSUMER/STABLE
2196        // GroupListing per seeded group config.
2197        let state = self.state.lock().unwrap();
2198        let listings: Vec<Result<GroupListing, Error>> = state
2199            .group_configs
2200            .keys()
2201            .map(|g| {
2202                Ok(GroupListing::new(
2203                    g.clone(),
2204                    Some(GroupType::Consumer),
2205                    ConsumerProtocol::PROTOCOL_TYPE,
2206                    Some(GroupState::Stable),
2207                ))
2208            })
2209            .collect();
2210        let handle: KafkaFutureImpl<Vec<Result<GroupListing, Error>>> = KafkaFutureImpl::new();
2211        handle.complete(listings);
2212        ListGroupsResult::new(handle.future())
2213    }
2214
2215    fn describe_consumer_groups_with_options(
2216        &self,
2217        group_ids: &[String],
2218        _options: DescribeConsumerGroupsOptions,
2219    ) -> DescribeConsumerGroupsResult {
2220        // Java's
2221        // `org.apache.kafka.clients.admin.MockAdminClient#describeConsumerGroups`
2222        // throws `UnsupportedOperationException("Not implemented yet")`. Per
2223        // admin-client.md §9 the Rust mock surfaces that as an exceptional
2224        // future rather than a panic.
2225        let mut futures = HashMap::new();
2226        for group_id in group_ids {
2227            let handle: KafkaFutureImpl<ConsumerGroupDescription> = KafkaFutureImpl::new();
2228            handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
2229            futures.insert(group_id.clone(), handle.future());
2230        }
2231        DescribeConsumerGroupsResult::new(futures)
2232    }
2233
2234    fn describe_classic_groups_with_options(
2235        &self,
2236        group_ids: &[String],
2237        _options: DescribeClassicGroupsOptions,
2238    ) -> DescribeClassicGroupsResult {
2239        // Java's
2240        // `org.apache.kafka.clients.admin.MockAdminClient#describeClassicGroups`
2241        // throws `UnsupportedOperationException("Not implemented yet")`. Per
2242        // admin-client.md §9 the Rust mock surfaces that as an exceptional
2243        // future rather than a panic.
2244        let mut futures = HashMap::new();
2245        for group_id in group_ids {
2246            let handle: KafkaFutureImpl<ClassicGroupDescription> = KafkaFutureImpl::new();
2247            handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
2248            futures.insert(group_id.clone(), handle.future());
2249        }
2250        DescribeClassicGroupsResult::new(futures)
2251    }
2252
2253    fn list_consumer_group_offsets_with_group_specs_options(
2254        &self,
2255        group_specs: &HashMap<String, ListConsumerGroupOffsetsSpec>,
2256        _options: ListConsumerGroupOffsetsOptions,
2257    ) -> ListConsumerGroupOffsetsResult {
2258        // Java ignores the group and assumes each test works on a single group;
2259        // more than one group is "Not implemented yet"
2260        // (`org.apache.kafka.clients.admin.MockAdminClient#listConsumerGroupOffsets`).
2261        // Per admin-client.md §9 the Rust mock surfaces that as an exceptional
2262        // future rather than a panic.
2263        if group_specs.len() != 1 {
2264            let futures = group_specs
2265                .keys()
2266                .map(|group| {
2267                    let handle: KafkaFutureImpl<GroupOffsets> = KafkaFutureImpl::new();
2268                    handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
2269                    (group.clone(), handle.future())
2270                })
2271                .collect();
2272            return ListConsumerGroupOffsetsResult::new(futures);
2273        }
2274
2275        let (group, spec) = group_specs.iter().next().expect("exactly one group");
2276        // `None` topic partitions (or an empty list) means "all partitions".
2277        let include_all = spec.topic_partitions().is_none_or(<[_]>::is_empty);
2278        let state = self.state.lock().unwrap();
2279        // Java builds each row with `new OffsetAndMetadata(entry.getValue())`
2280        // inline in the collect of
2281        // `org.apache.kafka.clients.admin.MockAdminClient#listConsumerGroupOffsets`,
2282        // and that constructor rejects a negative offset with
2283        // `IllegalArgumentException("Invalid negative offset")`
2284        // (`org.apache.kafka.clients.consumer.OffsetAndMetadata#OffsetAndMetadata(long,Optional,String)`).
2285        // A negative offset *is* seedable and nothing upstream establishes
2286        // otherwise: `updateConsumerGroupOffsets` is an unvalidated `putAll`
2287        // (`MockAdminClient#updateConsumerGroupOffsets`), which the Rust mock
2288        // mirrors. Java's throw is a catchable `RuntimeException`; a Rust panic
2289        // here would instead unwind out of the `extern "C"` FFI wrapper —
2290        // `admin_sync_future_op` runs the submit closure inline on the calling
2291        // thread — and abort the process. So the error is surfaced on the group's
2292        // future, which the trait signature can carry (CLAUDE.md §12.1/§12.2,
2293        // admin-client.md §9).
2294        let offsets: Result<GroupOffsets, Error> = state
2295            .committed_offsets
2296            .iter()
2297            .filter(|(tp, _)| include_all || spec.topic_partitions().is_some_and(|tps| tps.contains(tp)))
2298            .map(|(tp, &offset)| OffsetAndMetadata::new(offset).map(|committed| (tp.clone(), Some(committed))))
2299            .collect();
2300        drop(state);
2301
2302        let handle: KafkaFutureImpl<GroupOffsets> = KafkaFutureImpl::new();
2303        match offsets {
2304            Ok(offsets) => {
2305                handle.complete(offsets);
2306            },
2307            Err(error) => {
2308                handle.complete_with_error(error);
2309            },
2310        }
2311        ListConsumerGroupOffsetsResult::new(HashMap::from([(group.clone(), handle.future())]))
2312    }
2313
2314    fn alter_consumer_group_offsets_with_options(
2315        &self,
2316        _group_id: &str,
2317        _offsets: &HashMap<TopicPartition, OffsetAndMetadata>,
2318        _options: AlterConsumerGroupOffsetsOptions,
2319    ) -> AlterConsumerGroupOffsetsResult {
2320        // Java's
2321        // `org.apache.kafka.clients.admin.MockAdminClient#alterConsumerGroupOffsets`
2322        // throws `UnsupportedOperationException("Not implement yet")` (note
2323        // Java's own typo "implement"). Per admin-client.md §9 the Rust mock
2324        // surfaces that as an exceptional future rather than a panic.
2325        let handle: KafkaFutureImpl<HashMap<TopicPartition, Errors>> = KafkaFutureImpl::new();
2326        handle.complete_with_error(Error::local_unsupported_operation("Not implement yet"));
2327        AlterConsumerGroupOffsetsResult::new(handle.future())
2328    }
2329
2330    fn delete_consumer_group_offsets_with_options(
2331        &self,
2332        _group_id: &str,
2333        partitions: &HashSet<TopicPartition>,
2334        _options: DeleteConsumerGroupOffsetsOptions,
2335    ) -> DeleteConsumerGroupOffsetsResult {
2336        // Java's
2337        // `org.apache.kafka.clients.admin.MockAdminClient#deleteConsumerGroupOffsets`
2338        // throws `UnsupportedOperationException("Not implemented yet")`. Per
2339        // admin-client.md §9 the Rust mock surfaces that as an exceptional
2340        // future rather than a panic.
2341        let handle: KafkaFutureImpl<HashMap<TopicPartition, Errors>> = KafkaFutureImpl::new();
2342        handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
2343        DeleteConsumerGroupOffsetsResult::new(handle.future(), partitions.clone())
2344    }
2345
2346    fn delete_consumer_groups_with_options(
2347        &self,
2348        group_ids: &[String],
2349        _options: DeleteConsumerGroupsOptions,
2350    ) -> DeleteConsumerGroupsResult {
2351        // Java's
2352        // `org.apache.kafka.clients.admin.MockAdminClient#deleteConsumerGroups`
2353        // throws `UnsupportedOperationException("Not implemented yet")`. Per
2354        // admin-client.md §9 the Rust mock surfaces that as an exceptional
2355        // future per group rather than a panic.
2356        let mut futures = HashMap::new();
2357        for group_id in group_ids {
2358            let handle: KafkaFutureImpl<()> = KafkaFutureImpl::new();
2359            handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
2360            futures.insert(group_id.clone(), handle.future());
2361        }
2362        DeleteConsumerGroupsResult::new(futures)
2363    }
2364
2365    fn remove_members_from_consumer_group_with_options(
2366        &self,
2367        _group_id: &str,
2368        options: RemoveMembersFromConsumerGroupOptions,
2369    ) -> RemoveMembersFromConsumerGroupResult {
2370        // Java's
2371        // `org.apache.kafka.clients.admin.MockAdminClient#removeMembersFromConsumerGroup`
2372        // throws `UnsupportedOperationException("Not implemented yet")`. Per
2373        // admin-client.md §9 the Rust mock surfaces that as an exceptional
2374        // future rather than a panic.
2375        let handle: KafkaFutureImpl<HashMap<MemberIdentity, Errors>> = KafkaFutureImpl::new();
2376        handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
2377        RemoveMembersFromConsumerGroupResult::new(handle.future(), options.members().clone())
2378    }
2379
2380    fn create_acls_with_options(&self, acls: &[AclBinding], _options: CreateAclsOptions) -> CreateAclsResult {
2381        // Java's `org.apache.kafka.clients.admin.MockAdminClient#createAcls`
2382        // throws `UnsupportedOperationException("Not implemented yet")`. Per
2383        // admin-client.md §9 the Rust mock surfaces that as an exceptional
2384        // future per binding rather than a panic.
2385        let mut futures = HashMap::new();
2386        for acl in acls {
2387            let handle: KafkaFutureImpl<()> = KafkaFutureImpl::new();
2388            handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
2389            futures.insert(acl.clone(), handle.future());
2390        }
2391        CreateAclsResult::new(futures)
2392    }
2393
2394    fn describe_acls_with_options(
2395        &self,
2396        _filter: &AclBindingFilter,
2397        _options: DescribeAclsOptions,
2398    ) -> DescribeAclsResult {
2399        // Java's `org.apache.kafka.clients.admin.MockAdminClient#describeAcls`
2400        // throws `UnsupportedOperationException("Not implemented yet")`. Per
2401        // admin-client.md §9 the Rust mock surfaces that as an exceptional
2402        // future rather than a panic.
2403        let handle: KafkaFutureImpl<Vec<AclBinding>> = KafkaFutureImpl::new();
2404        handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
2405        DescribeAclsResult::new(handle.future())
2406    }
2407
2408    fn delete_acls_with_options(&self, filters: &[AclBindingFilter], _options: DeleteAclsOptions) -> DeleteAclsResult {
2409        // Java's `org.apache.kafka.clients.admin.MockAdminClient#deleteAcls`
2410        // throws `UnsupportedOperationException("Not implemented yet")`. Per
2411        // admin-client.md §9 the Rust mock surfaces that as an exceptional
2412        // future per filter rather than a panic.
2413        let mut futures = HashMap::new();
2414        for filter in filters {
2415            let handle: KafkaFutureImpl<FilterResults> = KafkaFutureImpl::new();
2416            handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
2417            futures.insert(filter.clone(), handle.future());
2418        }
2419        DeleteAclsResult::new(futures)
2420    }
2421
2422    fn describe_client_quotas_with_options(
2423        &self,
2424        _filter: &ClientQuotaFilter,
2425        _options: DescribeClientQuotasOptions,
2426    ) -> DescribeClientQuotasResult {
2427        // Java's
2428        // `org.apache.kafka.clients.admin.MockAdminClient#describeClientQuotas`
2429        // throws `UnsupportedOperationException("Not implement yet")`. Per
2430        // admin-client.md §9 the Rust mock surfaces that as an exceptional
2431        // future rather than a panic.
2432        let handle: KafkaFutureImpl<HashMap<ClientQuotaEntity, HashMap<String, f64>>> = KafkaFutureImpl::new();
2433        handle.complete_with_error(Error::local_unsupported_operation("Not implement yet"));
2434        DescribeClientQuotasResult::new(handle.future())
2435    }
2436
2437    fn alter_client_quotas_with_options(
2438        &self,
2439        entries: &[ClientQuotaAlteration],
2440        _options: AlterClientQuotasOptions,
2441    ) -> AlterClientQuotasResult {
2442        // Java's
2443        // `org.apache.kafka.clients.admin.MockAdminClient#alterClientQuotas`
2444        // throws `UnsupportedOperationException("Not implement yet")`. Per
2445        // admin-client.md §9 the Rust mock surfaces that as an exceptional
2446        // future per entity rather than a panic.
2447        let mut futures = HashMap::new();
2448        for entry in entries {
2449            let handle: KafkaFutureImpl<()> = KafkaFutureImpl::new();
2450            handle.complete_with_error(Error::local_unsupported_operation("Not implement yet"));
2451            futures.insert(entry.entity().clone(), handle.future());
2452        }
2453        AlterClientQuotasResult::new(futures)
2454    }
2455
2456    fn describe_user_scram_credentials_with_users_options(
2457        &self,
2458        _users: &[String],
2459        _options: DescribeUserScramCredentialsOptions,
2460    ) -> DescribeUserScramCredentialsResult {
2461        // Java's
2462        // `org.apache.kafka.clients.admin.MockAdminClient#describeUserScramCredentials`
2463        // throws `UnsupportedOperationException("Not implemented yet")`. Per
2464        // admin-client.md §9 the Rust mock surfaces that as an exceptional
2465        // future rather than a panic.
2466        let handle: KafkaFutureImpl<DescribeUserScramCredentialsResponseData> = KafkaFutureImpl::new();
2467        handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
2468        DescribeUserScramCredentialsResult::new(handle.future())
2469    }
2470
2471    fn alter_user_scram_credentials_with_options(
2472        &self,
2473        alterations: &[UserScramCredentialAlteration],
2474        _options: AlterUserScramCredentialsOptions,
2475    ) -> AlterUserScramCredentialsResult {
2476        // Java's
2477        // `org.apache.kafka.clients.admin.MockAdminClient#alterUserScramCredentials`
2478        // throws `UnsupportedOperationException("Not implemented yet")`. Per
2479        // admin-client.md §9 the Rust mock surfaces that as an exceptional
2480        // future per user rather than a panic.
2481        let mut futures = HashMap::new();
2482        for alteration in alterations {
2483            let handle: KafkaFutureImpl<()> = KafkaFutureImpl::new();
2484            handle.complete_with_error(Error::local_unsupported_operation("Not implemented yet"));
2485            futures.insert(alteration.user().to_string(), handle.future());
2486        }
2487        AlterUserScramCredentialsResult::new(futures)
2488    }
2489
2490    fn create_delegation_token_with_options(
2491        &self,
2492        options: CreateDelegationTokenOptions,
2493    ) -> CreateDelegationTokenResult {
2494        // Mirrors MockAdminClient.createDelegationToken: reject any non-User
2495        // renewer, otherwise mint a token whose id doubles as its HMAC and
2496        // whose owner is the first renewer, and store it in `all_tokens`.
2497        let handle: KafkaFutureImpl<DelegationToken> = KafkaFutureImpl::new();
2498        for renewer in options.renewers() {
2499            if renewer.principal_type() != KafkaPrincipal::USER_TYPE {
2500                handle.complete_with_error(Error::with_message(Errors::InvalidPrincipalType, ""));
2501                return CreateDelegationTokenResult::new(handle.future());
2502            }
2503        }
2504
2505        // Java uses `options.renewers().get(0)` as the owner (in
2506        // `org.apache.kafka.clients.admin.MockAdminClient#createDelegationToken`),
2507        // which throws `IndexOutOfBoundsException` when no renewer was
2508        // supplied. That is a catchable `RuntimeException` in Java, but an
2509        // index panic in Rust — and every FFI path runs this inline on the
2510        // calling thread, so it would unwind across an `extern "C"` boundary
2511        // and abort the process. Per CLAUDE.md §12.1 the future is completed
2512        // exceptionally instead.
2513        let Some(owner) = options.renewers().first().cloned() else {
2514            handle.complete_with_error(Error::local_illegal_argument(
2515                "createDelegationToken requires at least one renewer: MockAdminClient makes the first renewer the owner",
2516            ));
2517            return CreateDelegationTokenResult::new(handle.future());
2518        };
2519
2520        let token_id = Uuid::random_uuid().to_string();
2521        // The delegation token's HMAC is the UTF-8 bytes of the token id.
2522        let token_info = TokenInformation::new(
2523            token_id.clone(),
2524            owner,
2525            options.renewers().to_vec(),
2526            current_time_millis(),
2527            options.max_lifetime_ms(),
2528            -1,
2529        );
2530        let token = DelegationToken::new(token_info, token_id.into_bytes());
2531        self.state.lock().unwrap().all_tokens.push(token.clone());
2532        handle.complete(token);
2533        CreateDelegationTokenResult::new(handle.future())
2534    }
2535
2536    fn renew_delegation_token_with_options(
2537        &self,
2538        hmac: &[u8],
2539        options: RenewDelegationTokenOptions,
2540    ) -> RenewDelegationTokenResult {
2541        // Mirrors MockAdminClient.renewDelegationToken: update the expiry of
2542        // every matching token; error if none matched.
2543        let handle: KafkaFutureImpl<i64> = KafkaFutureImpl::new();
2544        let expiry_timestamp = options.renew_time_period_ms();
2545        let mut token_found = false;
2546        {
2547            let mut state = self.state.lock().unwrap();
2548            for token in &mut state.all_tokens {
2549                if token.hmac() == hmac {
2550                    token.token_info_mut().set_expiry_timestamp(expiry_timestamp);
2551                    token_found = true;
2552                }
2553            }
2554        }
2555        if token_found {
2556            handle.complete(expiry_timestamp);
2557        } else {
2558            handle.complete_with_error(Error::with_message(Errors::DelegationTokenNotFound, ""));
2559        }
2560        RenewDelegationTokenResult::new(handle.future())
2561    }
2562
2563    fn expire_delegation_token_with_options(
2564        &self,
2565        hmac: &[u8],
2566        options: ExpireDelegationTokenOptions,
2567    ) -> ExpireDelegationTokenResult {
2568        // Mirrors MockAdminClient.expireDelegationToken: remove matching tokens
2569        // whose expiry period is the `-1` sentinel or already in the past;
2570        // error if none matched.
2571        let handle: KafkaFutureImpl<i64> = KafkaFutureImpl::new();
2572        let expiry_timestamp = options.expiry_time_period_ms();
2573        let now = current_time_millis();
2574        let mut token_found = false;
2575        let mut tokens_to_remove = Vec::new();
2576        {
2577            let mut state = self.state.lock().unwrap();
2578            for token in &state.all_tokens {
2579                if token.hmac() == hmac {
2580                    if expiry_timestamp == -1 || expiry_timestamp < now {
2581                        tokens_to_remove.push(token.clone());
2582                    }
2583                    token_found = true;
2584                }
2585            }
2586            if token_found {
2587                state.all_tokens.retain(|token| !tokens_to_remove.contains(token));
2588            }
2589        }
2590        if token_found {
2591            handle.complete(expiry_timestamp);
2592        } else {
2593            handle.complete_with_error(Error::with_message(Errors::DelegationTokenNotFound, ""));
2594        }
2595        ExpireDelegationTokenResult::new(handle.future())
2596    }
2597
2598    fn describe_delegation_token_with_options(
2599        &self,
2600        options: DescribeDelegationTokenOptions,
2601    ) -> DescribeDelegationTokenResult {
2602        // Mirrors MockAdminClient.describeDelegationToken: no owners filter
2603        // returns every token; otherwise only tokens whose owner is in the
2604        // filter. (Java NPEs on a null owners list; the Rust option models the
2605        // nullable field, and both a null and an empty filter return all
2606        // tokens — matching the real client's "null describes all" contract.)
2607        let handle: KafkaFutureImpl<Vec<DelegationToken>> = KafkaFutureImpl::new();
2608        let state = self.state.lock().unwrap();
2609        let tokens = match options.owners() {
2610            // Null or empty owners filter -> describe all tokens.
2611            None | Some([]) => state.all_tokens.clone(),
2612            Some(owners) => state
2613                .all_tokens
2614                .iter()
2615                .filter(|token| owners.contains(token.token_info().owner()))
2616                .cloned()
2617                .collect(),
2618        };
2619        handle.complete(tokens);
2620        DescribeDelegationTokenResult::new(handle.future())
2621    }
2622
2623    fn describe_features_with_options(&self, _options: DescribeFeaturesOptions) -> DescribeFeaturesResult {
2624        // Mirrors MockAdminClient.describeFeatures: derive finalized and
2625        // supported ranges from the seeded feature-level maps.
2626        let state = self.state.lock().unwrap();
2627        let handle: KafkaFutureImpl<FeatureMetadata> = KafkaFutureImpl::new();
2628
2629        let mut finalized_features = HashMap::new();
2630        let mut supported_features = HashMap::new();
2631        for (feature, &level) in &state.feature_levels {
2632            let min = state.min_supported_feature_levels.get(feature).copied().unwrap_or(0);
2633            let max = state.max_supported_feature_levels.get(feature).copied().unwrap_or(0);
2634            match (FinalizedVersionRange::new(level, level), SupportedVersionRange::new(min, max)) {
2635                (Ok(finalized), Ok(supported)) => {
2636                    finalized_features.insert(feature.clone(), finalized);
2637                    supported_features.insert(feature.clone(), supported);
2638                },
2639                (Err(e), _) | (_, Err(e)) => {
2640                    handle.complete_with_error(e);
2641                    return DescribeFeaturesResult::new(handle.future());
2642                },
2643            }
2644        }
2645
2646        handle.complete(FeatureMetadata::new(finalized_features, Some(123), supported_features));
2647        DescribeFeaturesResult::new(handle.future())
2648    }
2649
2650    fn update_features_with_options(
2651        &self,
2652        feature_updates: &HashMap<String, FeatureUpdate>,
2653        options: UpdateFeaturesOptions,
2654    ) -> Result<UpdateFeaturesResult, Error> {
2655        // Mirrors MockAdminClient.updateFeatures: validate each update against
2656        // the seeded version bounds; the first failure aborts the whole batch.
2657        let mut state = self.state.lock().unwrap();
2658        let mut error: Option<Error> = None;
2659        for (feature, update) in feature_updates {
2660            let cur = state.feature_levels.get(feature).copied().unwrap_or(0);
2661            let next = update.max_version_level();
2662            let min = state.min_supported_feature_levels.get(feature).copied().unwrap_or(0);
2663            let max = state.max_supported_feature_levels.get(feature).copied().unwrap_or(0);
2664            if let Err(message) = validate_feature_update(cur, next, min, max, update.upgrade_type()) {
2665                error = Some(invalid_update_version(feature, next, &message));
2666                break;
2667            }
2668        }
2669
2670        let mut results: HashMap<String, crate::common::KafkaFuture<()>> = HashMap::new();
2671        for (feature, update) in feature_updates {
2672            let handle: KafkaFutureImpl<()> = KafkaFutureImpl::new();
2673            match &error {
2674                None => {
2675                    handle.complete(());
2676                    if !options.validate_only() {
2677                        state.feature_levels.insert(feature.clone(), update.max_version_level());
2678                    }
2679                },
2680                Some(e) => {
2681                    handle.complete_with_error(e.clone());
2682                },
2683            }
2684            results.insert(feature.clone(), handle.future());
2685        }
2686
2687        Ok(UpdateFeaturesResult::new(results))
2688    }
2689
2690    async fn close_with_timeout(&self, _timeout: Duration) {
2691        // Nothing to close for the in-memory mock.
2692    }
2693}
2694
2695/// Validates a single feature update against the mock's seeded version bounds,
2696/// returning the inner error message on failure. Mirrors the `switch` /
2697/// bounds checks inside `MockAdminClient.updateFeatures`.
2698fn validate_feature_update(cur: i16, next: i16, min: i16, max: i16, upgrade_type: UpgradeType) -> Result<(), String> {
2699    match upgrade_type {
2700        UpgradeType::Unknown => return Err("Invalid upgrade type.".to_string()),
2701        UpgradeType::Upgrade => {
2702            if cur > next {
2703                return Err("Can't upgrade to lower version.".to_string());
2704            }
2705        },
2706        UpgradeType::SafeDowngrade => {
2707            if cur < next {
2708                return Err("Can't downgrade to newer version.".to_string());
2709            }
2710        },
2711        UpgradeType::UnsafeDowngrade => {
2712            if cur < next {
2713                return Err("Can't downgrade to newer version.".to_string());
2714            }
2715            // Simulate a scenario where all the even feature levels are unsafe
2716            // to downgrade from. Mirrors Java exactly: the inner
2717            // `SAFE_DOWNGRADE` guard can never fire in this `UNSAFE_DOWNGRADE`
2718            // branch, so the loop only walks `cur` down to `next`.
2719            let mut cur = cur;
2720            while next != cur {
2721                cur -= 1;
2722            }
2723        },
2724    }
2725    if next < min {
2726        return Err(format!("Can't downgrade below {min}"));
2727    }
2728    if next > max {
2729        return Err(format!("Can't upgrade above {max}"));
2730    }
2731    Ok(())
2732}
2733
2734/// Composes the mock's `InvalidRequestException` for a rejected feature update.
2735/// Mirrors `MockAdminClient.invalidUpdateVersion`.
2736fn invalid_update_version(feature: &str, version: i16, message: &str) -> Error {
2737    Error::with_message(
2738        Errors::InvalidRequest,
2739        format!("Invalid update version {version} for feature {feature}. {message}"),
2740    )
2741}
2742
2743#[cfg(test)]
2744mod tests {
2745    use super::*;
2746
2747    fn admin() -> MockAdminClient {
2748        Builder::new()
2749            .set_num_brokers(3)
2750            .and_then(Builder::build)
2751            .expect("num_brokers is at least 1")
2752    }
2753
2754    // --- Builder broker-count validation -------------------------------------
2755    // (`org.apache.kafka.clients.admin.MockAdminClient.Builder#numBrokers`,
2756    // `MockAdminClient.Builder#build`)
2757
2758    /// Java's `MockAdminClient.Builder#build` reads `brokers.get(0)` for the
2759    /// controller, so `numBrokers(0)` fails at `build()` with
2760    /// the JDK's `IndexOutOfBoundsException` text instead of yielding a
2761    /// broker-less mock.
2762    #[test]
2763    fn build_rejects_zero_brokers_rather_than_fabricating_a_controller() {
2764        let err = Builder::new()
2765            .set_num_brokers(0)
2766            .expect("shrinking to zero brokers is accepted")
2767            .build()
2768            .expect_err("zero brokers must be rejected");
2769        assert!(
2770            matches!(err, Error::LocalIllegalArgument(_)),
2771            "expected IllegalArgument, got {err:?}"
2772        );
2773        assert_eq!(err.message(), "Index 0 out of bounds for length 0");
2774    }
2775
2776    /// `numBrokers(-1)` throws even earlier in Java, from `brokers.subList(0, -1)`
2777    /// in `MockAdminClient.Builder#numBrokers`, whose `subListRangeCheck` throws
2778    /// `IllegalArgumentException("fromIndex(0) > toIndex(-1)")`.
2779    #[test]
2780    fn set_num_brokers_rejects_a_negative_broker_count() {
2781        let err = Builder::new()
2782            .set_num_brokers(-1)
2783            .expect_err("a negative count must be rejected");
2784        assert!(matches!(err, Error::LocalIllegalArgument(_)), "got {err:?}");
2785        assert_eq!(err.message(), "fromIndex(0) > toIndex(-1)");
2786    }
2787
2788    // --- Builder (`org.apache.kafka.clients.admin.MockAdminClient.Builder`) ----
2789    //
2790    // No clients-module Java test uses the Builder (its users are in
2791    // connect/streams/tools), so these pin the Java source directly.
2792
2793    fn default_dirs() -> Vec<String> {
2794        vec!["/tmp/kafka-logs".to_string()]
2795    }
2796
2797    fn dirs(dir: &str) -> Vec<String> {
2798        vec![dir.to_string()]
2799    }
2800
2801    /// `new Builder().build()`: one broker `Node(0, "localhost", 1000)` with
2802    /// `DEFAULT_LOG_DIRS`, controller = `brokers.get(0)`, `DEFAULT_CLUSTER_ID`,
2803    /// 1 default partition, replication factor `min(1, 3)`, no raft controller
2804    /// and empty feature and group-config maps.
2805    #[test]
2806    fn builder_defaults_match_java() {
2807        assert_eq!(MockAdminClient::DEFAULT_CLUSTER_ID, "I4ZmrWqfT2e-upky_4fdPA");
2808        assert_eq!(MockAdminClient::DEFAULT_LOG_DIRS, &["/tmp/kafka-logs"]);
2809
2810        let mock = Builder::new().build().expect("a fresh builder has one broker");
2811        let state = mock.state.lock().unwrap();
2812        let node0 = Node::new(0, "localhost".to_string(), 1000);
2813        assert_eq!(state.brokers, vec![node0.clone()]);
2814        assert_eq!(state.controller, node0);
2815        assert_eq!(state.cluster_id, MockAdminClient::DEFAULT_CLUSTER_ID);
2816        assert_eq!(state.default_partitions, 1);
2817        assert_eq!(state.default_replication_factor, 1);
2818        assert_eq!(state.broker_log_dirs, vec![default_dirs()]);
2819        assert!(!state.using_raft_controller);
2820        assert!(state.feature_levels.is_empty());
2821        assert!(state.min_supported_feature_levels.is_empty());
2822        assert!(state.max_supported_feature_levels.is_empty());
2823        assert!(state.default_group_configs.is_empty());
2824        assert_eq!(
2825            state.broker_configs,
2826            vec![BTreeMap::from([(
2827                "default.replication.factor".to_string(),
2828                Some("1".to_string())
2829            )])]
2830        );
2831    }
2832
2833    /// `MockAdminClient#create` is `new Builder()`,
2834    /// so it builds the same defaults as `Builder::new()`.
2835    #[test]
2836    fn create_returns_a_fresh_builder() {
2837        let from_create = MockAdminClient::create().build().expect("a fresh builder has one broker");
2838        let from_new = Builder::new().build().expect("a fresh builder has one broker");
2839        let created = from_create.state.lock().unwrap();
2840        let fresh = from_new.state.lock().unwrap();
2841        assert_eq!(created.brokers, fresh.brokers);
2842        assert_eq!(created.controller, fresh.controller);
2843        assert_eq!(created.cluster_id, fresh.cluster_id);
2844        assert_eq!(created.cluster_id, MockAdminClient::DEFAULT_CLUSTER_ID);
2845        assert_eq!(created.default_partitions, fresh.default_partitions);
2846        assert_eq!(created.default_replication_factor, fresh.default_replication_factor);
2847        assert_eq!(created.broker_log_dirs, fresh.broker_log_dirs);
2848        assert_eq!(created.broker_configs, fresh.broker_configs);
2849        assert_eq!(created.using_raft_controller, fresh.using_raft_controller);
2850        assert_eq!(created.default_group_configs, fresh.default_group_configs);
2851        assert_eq!(created.feature_levels, fresh.feature_levels);
2852        assert_eq!(created.min_supported_feature_levels, fresh.min_supported_feature_levels);
2853        assert_eq!(created.max_supported_feature_levels, fresh.max_supported_feature_levels);
2854    }
2855
2856    // --- Public constructors (`org.apache.kafka.clients.admin.MockAdminClient#MockAdminClient`) ---
2857    //
2858    // Rust-side tests, no Java counterpart: Java has no tests for these
2859    // constructors or the controller setter. They were added with this port and
2860    // check the behaviour against the Java source cited on each test.
2861
2862    fn four_nodes() -> Vec<Node> {
2863        (0..4).map(|id| Node::new(id, format!("h{id}"), 9092)).collect()
2864    }
2865
2866    /// `new MockAdminClient(brokers, controller)`
2867    /// (`MockAdminClient#MockAdminClient(List,Node)`): the given brokers and
2868    /// controller, `DEFAULT_CLUSTER_ID`, one default partition, a default
2869    /// replication factor of `brokers.size()` (not the Builder's `min(n, 3)`),
2870    /// `DEFAULT_LOG_DIRS` per broker, each broker's `default.replication.factor`
2871    /// config seeded with that factor, no raft controller and empty feature and
2872    /// group-config maps.
2873    #[tokio::test]
2874    async fn with_brokers_controller_matches_java_constructor() {
2875        let nodes = four_nodes();
2876        let mock = MockAdminClient::with_brokers_controller(nodes.clone(), nodes[2].clone())
2877            .expect("the controller is one of the brokers");
2878
2879        let result = mock.describe_cluster_with_options(DescribeClusterOptions::new());
2880        assert_eq!(result.nodes().get().await.unwrap(), nodes);
2881        assert_eq!(result.controller().get().await.unwrap().unwrap().id(), 2);
2882        assert_eq!(result.cluster_id().get().await.unwrap(), MockAdminClient::DEFAULT_CLUSTER_ID);
2883
2884        let state = mock.state.lock().unwrap();
2885        assert_eq!(state.default_partitions, 1);
2886        assert_eq!(state.default_replication_factor, 4, "brokers.size(), not min(4, 3)");
2887        assert_eq!(state.broker_log_dirs, vec![default_dirs(); 4]);
2888        assert_eq!(
2889            state.broker_configs,
2890            vec![BTreeMap::from([("default.replication.factor".to_string(), Some("4".to_string()))]); 4]
2891        );
2892        assert!(!state.using_raft_controller);
2893        assert!(state.feature_levels.is_empty());
2894        assert!(state.min_supported_feature_levels.is_empty());
2895        assert!(state.max_supported_feature_levels.is_empty());
2896        assert!(state.default_group_configs.is_empty());
2897    }
2898
2899    /// `new MockAdminClient()` (`MockAdminClient#MockAdminClient()`) is
2900    /// `this(singletonList(Node.noNode()), Node.noNode())`: one broker with id -1,
2901    /// which is also the controller.
2902    #[tokio::test]
2903    async fn new_has_one_no_node_broker_that_is_the_controller() {
2904        let mock = MockAdminClient::new();
2905        let result = mock.describe_cluster_with_options(DescribeClusterOptions::new());
2906        let nodes = result.nodes().get().await.unwrap();
2907        assert_eq!(nodes, vec![Node::no_node().clone()]);
2908        assert_eq!(nodes[0].id(), -1);
2909        let controller = result.controller().get().await.unwrap().unwrap();
2910        assert_eq!(&controller, Node::no_node());
2911
2912        let state = mock.state.lock().unwrap();
2913        assert_eq!(state.default_replication_factor, 1);
2914        assert_eq!(
2915            state.broker_configs,
2916            vec![BTreeMap::from([(
2917                "default.replication.factor".to_string(),
2918                Some("1".to_string())
2919            )])]
2920        );
2921    }
2922
2923    /// `new MockAdminClient()`'s only broker is `Node.noNode()`, whose id is -1,
2924    /// and `brokerLogDirs` is indexed by broker id, so Java's
2925    /// `MockAdminClient#createTopics` throws
2926    /// `IndexOutOfBoundsException("Index -1 out of bounds for length 1")`. The
2927    /// mock fails the topic with that error instead of panicking.
2928    #[tokio::test]
2929    async fn create_topics_on_new_fails_for_the_no_node_broker_as_java_does() {
2930        let mock = MockAdminClient::new();
2931        let result = mock.create_topics_with_options(
2932            &[NewTopic::with_num_partitions_replication_factor("t", Some(1), Some(1))],
2933            CreateTopicsOptions::new(),
2934        );
2935        let err = result.all().get().await.expect_err("-1 is not a log-dir index");
2936        assert!(matches!(err, Error::LocalIllegalArgument(_)), "got {err:?}");
2937        assert_eq!(err.message(), "Index -1 out of bounds for length 1");
2938    }
2939
2940    /// Java passes `brokers.size()` straight through as the
2941    /// `int defaultReplicationFactor`
2942    /// (`MockAdminClient#MockAdminClient(List,Node)`), so unlike the Builder's
2943    /// `shortValue()` it does not wrap at `Short.MAX_VALUE + 1` brokers: the
2944    /// broker config holds 32768 and a topic created with the default
2945    /// replication factor gets one replica per broker.
2946    #[tokio::test]
2947    async fn with_brokers_controller_keeps_a_broker_count_above_short_max() {
2948        let nodes: Vec<Node> = (0..32_768).map(|id| Node::new(id, format!("h{id}"), 9092)).collect();
2949        let mock = MockAdminClient::with_brokers_controller(nodes.clone(), nodes[0].clone()).unwrap();
2950        {
2951            let state = mock.state.lock().unwrap();
2952            assert_eq!(state.default_replication_factor, 32_768);
2953            assert_eq!(state.broker_configs[0]["default.replication.factor"].as_deref(), Some("32768"));
2954        }
2955
2956        let result = mock.create_topics_with_options(
2957            &[NewTopic::with_num_partitions_replication_factor("t", None, None)],
2958            CreateTopicsOptions::new(),
2959        );
2960        assert_eq!(result.replication_factor("t").get().await.unwrap(), 32_768);
2961    }
2962
2963    /// The constructor calls `MockAdminClient#controller`,
2964    /// which throws `IllegalArgumentException` for a node outside the broker list.
2965    #[test]
2966    fn with_brokers_controller_rejects_a_controller_outside_the_brokers() {
2967        let err = MockAdminClient::with_brokers_controller(four_nodes(), Node::new(7, "h7".to_string(), 9092))
2968            .expect_err("the controller is not a broker");
2969        assert!(matches!(err, Error::LocalIllegalArgument(_)), "got {err:?}");
2970        assert_eq!(err.message(), "The controller node must be in the list of brokers");
2971    }
2972
2973    /// The public setter `MockAdminClient#controller`
2974    /// replaces the controller when the node is a broker and throws, leaving the
2975    /// controller unchanged, when it is not.
2976    #[tokio::test]
2977    async fn set_controller_requires_a_broker() {
2978        let nodes = four_nodes();
2979        let mock = MockAdminClient::with_brokers_controller(nodes.clone(), nodes[2].clone()).unwrap();
2980
2981        mock.set_controller(nodes[3].clone()).expect("node 3 is a broker");
2982        let result = mock.describe_cluster_with_options(DescribeClusterOptions::new());
2983        assert_eq!(result.controller().get().await.unwrap().unwrap().id(), 3);
2984
2985        let err = mock
2986            .set_controller(Node::new(7, "h7".to_string(), 9092))
2987            .expect_err("node 7 is not a broker");
2988        assert!(matches!(err, Error::LocalIllegalArgument(_)), "got {err:?}");
2989        assert_eq!(err.message(), "The controller node must be in the list of brokers");
2990        let result = mock.describe_cluster_with_options(DescribeClusterOptions::new());
2991        assert_eq!(result.controller().get().await.unwrap().unwrap().id(), 3);
2992    }
2993
2994    /// Growing appends `Node(id, "localhost", 1000 + id)` with the default log
2995    /// dirs; the default replication factor is `min(brokers.size(), 3)`.
2996    #[test]
2997    fn set_num_brokers_grows_the_broker_and_log_dir_lists() {
2998        let mock = Builder::new()
2999            .set_num_brokers(5)
3000            .and_then(Builder::build)
3001            .expect("five brokers");
3002        let state = mock.state.lock().unwrap();
3003        let expected: Vec<Node> = (0..5).map(|id| Node::new(id, "localhost".to_string(), 1000 + id)).collect();
3004        assert_eq!(state.brokers, expected);
3005        assert_eq!(state.broker_log_dirs, vec![default_dirs(); 5]);
3006        assert_eq!(state.default_replication_factor, 3, "min(5, 3)");
3007        assert_eq!(state.broker_configs.len(), 5);
3008    }
3009
3010    /// Shrinking keeps the first brokers and the first log-dir entries
3011    /// (`subList(0, n)`).
3012    #[test]
3013    fn set_num_brokers_shrinks_both_lists_to_their_prefix() {
3014        let mock = Builder::new()
3015            .set_num_brokers(3)
3016            .expect("three brokers")
3017            .set_broker_log_dirs(vec![dirs("a"), dirs("b"), dirs("c")])
3018            .set_num_brokers(2)
3019            .and_then(Builder::build)
3020            .expect("two brokers");
3021        let state = mock.state.lock().unwrap();
3022        assert_eq!(
3023            state.brokers,
3024            vec![
3025                Node::new(0, "localhost".to_string(), 1000),
3026                Node::new(1, "localhost".to_string(), 1001)
3027            ]
3028        );
3029        assert_eq!(state.broker_log_dirs, vec![dirs("a"), dirs("b")]);
3030        assert_eq!(state.default_replication_factor, 2);
3031    }
3032
3033    /// `brokerLogDirs.subList(0, n)` throws `IndexOutOfBoundsException("toIndex
3034    /// = n")` when the log-dir list is shorter than the new count, which can
3035    /// happen after `brokerLogDirs(..)` installed a shorter list.
3036    #[test]
3037    fn shrinking_past_a_short_log_dir_list_fails_like_sub_list() {
3038        let short = || {
3039            Builder::new()
3040                .set_num_brokers(3)
3041                .expect("three brokers")
3042                .set_broker_log_dirs(vec![dirs("a")])
3043        };
3044        let err = short().set_num_brokers(2).expect_err("the log-dir list is too short");
3045        assert!(matches!(err, Error::LocalIllegalArgument(_)), "got {err:?}");
3046        assert_eq!(err.message(), "toIndex = 2");
3047
3048        // `brokers(list)` resizes through `numBrokers(list.size())` first.
3049        let two = vec![Node::new(7, "h".to_string(), 7), Node::new(8, "h".to_string(), 8)];
3050        let err = short().set_brokers(two).expect_err("the log-dir list is too short");
3051        assert_eq!(err.message(), "toIndex = 2");
3052    }
3053
3054    /// A negative count reaches `subList(0, n)` with `n < 0`, and
3055    /// `subListRangeCheck` throws `IllegalArgumentException("fromIndex(0) >
3056    /// toIndex(n)")`, also from an already-empty builder.
3057    #[test]
3058    fn a_negative_broker_count_fails_like_sub_list_even_when_empty() {
3059        let err = Builder::new()
3060            .set_num_brokers(0)
3061            .and_then(|builder| builder.set_num_brokers(-3))
3062            .expect_err("a negative count must be rejected");
3063        assert!(matches!(err, Error::LocalIllegalArgument(_)), "got {err:?}");
3064        assert_eq!(err.message(), "fromIndex(0) > toIndex(-3)");
3065    }
3066
3067    /// `brokers(list)` runs `numBrokers(list.size())` on the current lists
3068    /// before replacing the broker list, so existing log-dir entries are kept
3069    /// and the rest padded with `DEFAULT_LOG_DIRS`.
3070    #[test]
3071    fn set_brokers_resizes_the_log_dirs_before_replacing_the_brokers() {
3072        let nodes = vec![
3073            Node::new(5, "h5".to_string(), 5),
3074            Node::new(6, "h6".to_string(), 6),
3075            Node::new(7, "h7".to_string(), 7),
3076        ];
3077        let mock = Builder::new()
3078            .set_broker_log_dirs(vec![dirs("custom")])
3079            .set_brokers(nodes.clone())
3080            .and_then(Builder::build)
3081            .expect("three explicit brokers");
3082        let state = mock.state.lock().unwrap();
3083        assert_eq!(state.brokers, nodes, "the given list replaces the generated brokers");
3084        assert_eq!(
3085            state.broker_log_dirs,
3086            vec![dirs("custom"), default_dirs(), default_dirs()],
3087            "the existing entry is kept and the new ones padded"
3088        );
3089        assert_eq!(state.controller, nodes[0], "brokers.get(0) of the new list");
3090
3091        // Shrinking through `brokers(list)` keeps the log-dir prefix.
3092        let mock = Builder::new()
3093            .set_num_brokers(3)
3094            .expect("three brokers")
3095            .set_broker_log_dirs(vec![dirs("a"), dirs("b"), dirs("c")])
3096            .set_brokers(vec![Node::new(9, "h9".to_string(), 9)])
3097            .and_then(Builder::build)
3098            .expect("one explicit broker");
3099        assert_eq!(mock.state.lock().unwrap().broker_log_dirs, vec![dirs("a")]);
3100    }
3101
3102    /// `brokerLogDirs` is indexed by broker **id**, so with brokers 5, 6 and 7
3103    /// Java's `MockAdminClient#createTopics` and
3104    /// `MockAdminClient#addTopic(boolean,String,List,Map,boolean)` throw
3105    /// `IndexOutOfBoundsException` ("Index 5 out of bounds for length 3"). The
3106    /// mock reports that error instead of panicking. A topic with no partitions
3107    /// never looks the list up, as in Java.
3108    #[tokio::test]
3109    async fn broker_ids_that_are_not_log_dir_indexes_fail_like_java() {
3110        let nodes: Vec<Node> = (5..8).map(|id| Node::new(id, format!("h{id}"), 9092)).collect();
3111        let mock = Builder::new()
3112            .set_brokers(nodes.clone())
3113            .and_then(Builder::build)
3114            .expect("three explicit brokers");
3115
3116        let result = mock.create_topics_with_options(
3117            &[NewTopic::with_num_partitions_replication_factor("t", Some(1), Some(1))],
3118            CreateTopicsOptions::new(),
3119        );
3120        let err = result.all().get().await.expect_err("broker 5 is not a log-dir index");
3121        assert!(matches!(err, Error::LocalIllegalArgument(_)), "got {err:?}");
3122        assert_eq!(err.message(), "Index 5 out of bounds for length 3");
3123        assert!(
3124            !mock.state.lock().unwrap().all_topics.contains_key("t"),
3125            "the topic is not created"
3126        );
3127
3128        let err = mock
3129            .add_topic(
3130                false,
3131                "u",
3132                vec![partition_info(
3133                    0,
3134                    Some(nodes[0].clone()),
3135                    vec![nodes[0].clone()],
3136                    vec![],
3137                )],
3138                None,
3139            )
3140            .expect_err("broker 5 is not a log-dir index");
3141        assert!(matches!(err, Error::LocalIllegalArgument(_)), "got {err:?}");
3142        assert_eq!(err.message(), "Index 5 out of bounds for length 3");
3143
3144        let result = mock.create_topics_with_options(
3145            &[NewTopic::with_num_partitions_replication_factor(
3146                "empty",
3147                Some(0),
3148                Some(1),
3149            )],
3150            CreateTopicsOptions::new(),
3151        );
3152        result.all().get().await.expect("no partition, so no log-dir lookup");
3153    }
3154
3155    /// `controller(index)` reads `brokers.get(index)` at the call; the JDK's
3156    /// `ArrayList.get` throws `IndexOutOfBoundsException("Index i out of bounds
3157    /// for length n")` for an index outside the list.
3158    #[test]
3159    fn set_controller_picks_the_broker_at_index_or_fails_at_the_call() {
3160        let three = || Builder::new().set_num_brokers(3).expect("three brokers");
3161        let mock = three().set_controller(1).and_then(Builder::build).expect("broker 1 exists");
3162        assert_eq!(
3163            mock.state.lock().unwrap().controller,
3164            Node::new(1, "localhost".to_string(), 1001)
3165        );
3166
3167        let err = three().set_controller(3).expect_err("index 3 is past the end");
3168        assert!(matches!(err, Error::LocalIllegalArgument(_)), "got {err:?}");
3169        assert_eq!(err.message(), "Index 3 out of bounds for length 3");
3170        let err = three().set_controller(-1).expect_err("a negative index");
3171        assert_eq!(err.message(), "Index -1 out of bounds for length 3");
3172    }
3173
3174    /// `build()` passes the chosen controller to the constructor, whose
3175    /// `controller(Node)` throws `IllegalArgumentException("The controller node
3176    /// must be in the list of brokers")` when a later resize or replacement
3177    /// dropped it (`MockAdminClient#controller`).
3178    #[test]
3179    fn build_rejects_a_controller_no_longer_in_the_broker_list() {
3180        let err = Builder::new()
3181            .set_num_brokers(3)
3182            .and_then(|builder| builder.set_controller(2))
3183            .and_then(|builder| builder.set_num_brokers(1))
3184            .and_then(Builder::build)
3185            .expect_err("broker 2 was removed");
3186        assert!(matches!(err, Error::LocalIllegalArgument(_)), "got {err:?}");
3187        assert_eq!(err.message(), "The controller node must be in the list of brokers");
3188
3189        let err = Builder::new()
3190            .set_controller(0)
3191            .and_then(|builder| builder.set_brokers(vec![Node::new(9, "h9".to_string(), 9)]))
3192            .and_then(Builder::build)
3193            .expect_err("the original broker 0 was replaced");
3194        assert_eq!(err.message(), "The controller node must be in the list of brokers");
3195    }
3196
3197    /// Each value-only setter reaches the built mock.
3198    #[test]
3199    fn builder_setters_reach_the_built_mock() {
3200        let features = HashMap::from([("f".to_string(), 3i16)]);
3201        let min = HashMap::from([("f".to_string(), 1i16)]);
3202        let max = HashMap::from([("f".to_string(), 5i16)]);
3203        let group_defaults = HashMap::from([("group.session.timeout.ms".to_string(), "45000".to_string())]);
3204        let mock = Builder::new()
3205            .set_cluster_id("my-cluster")
3206            .set_default_partitions(7)
3207            .set_default_replication_factor(2)
3208            .set_using_raft_controller(true)
3209            .set_feature_levels(features.clone())
3210            .set_min_supported_feature_levels(min.clone())
3211            .set_max_supported_feature_levels(max.clone())
3212            .set_default_group_configs(group_defaults.clone())
3213            .build()
3214            .expect("one broker");
3215        let state = mock.state.lock().unwrap();
3216        assert_eq!(state.cluster_id, "my-cluster");
3217        assert_eq!(state.default_partitions, 7);
3218        assert_eq!(state.default_replication_factor, 2);
3219        assert!(state.using_raft_controller);
3220        assert_eq!(state.feature_levels, features);
3221        assert_eq!(state.min_supported_feature_levels, min);
3222        assert_eq!(state.max_supported_feature_levels, max);
3223        assert_eq!(
3224            state.default_group_configs,
3225            group_defaults.into_iter().collect::<BTreeMap<_, _>>()
3226        );
3227        assert_eq!(state.broker_configs[0]["default.replication.factor"].as_deref(), Some("2"));
3228    }
3229
3230    /// `build()` narrows the replication factor with `Integer.shortValue()`,
3231    /// which wraps rather than clamps.
3232    #[test]
3233    fn build_narrows_the_default_replication_factor_like_short_value() {
3234        for (factor, narrowed) in [(65_537, 1i32), (32_768, -32_768), (-1, -1), (70_000, 4_464)] {
3235            let mock = Builder::new()
3236                .set_default_replication_factor(factor)
3237                .build()
3238                .expect("one broker");
3239            let state = mock.state.lock().unwrap();
3240            assert_eq!(state.default_replication_factor, narrowed, "shortValue() of {factor}");
3241            assert_eq!(
3242                state.broker_configs[0]["default.replication.factor"],
3243                Some(narrowed.to_string()),
3244                "String.valueOf of the narrowed value for {factor}"
3245            );
3246        }
3247    }
3248
3249    /// The controller Java picks is `brokers.get(0)` — an element of the broker
3250    /// list, hence always present in `describeCluster().nodes()`. This pins that
3251    /// invariant for every valid count; the count at which the fabricated
3252    /// `Node::new(0, "localhost", 1000)` fallback broke it is now unreachable, and
3253    /// is covered by `build_rejects_zero_brokers_rather_than_fabricating_a_controller`.
3254    #[tokio::test]
3255    async fn controller_is_always_one_of_the_seeded_nodes() {
3256        for num_brokers in 1..=3 {
3257            let mock = Builder::new()
3258                .set_num_brokers(num_brokers)
3259                .and_then(Builder::build)
3260                .expect("num_brokers is at least 1");
3261            let described = mock.describe_cluster_with_options(DescribeClusterOptions::new());
3262            let nodes = described.nodes().get().await.expect("nodes");
3263            let controller = described.controller().get().await.expect("controller").expect("a controller");
3264            assert!(
3265                nodes.contains(&controller),
3266                "controller {controller:?} is absent from nodes {nodes:?} for num_brokers={num_brokers}"
3267            );
3268            assert_eq!(controller.id(), 0);
3269            assert_eq!(nodes.len(), num_brokers as usize);
3270        }
3271    }
3272
3273    /// A mock seeded with a single feature `feature` at level 3, supported over
3274    /// the range [1, 5] (mirrors the shape used by Java's `MockAdminClient`
3275    /// feature tests).
3276    fn admin_with_features() -> MockAdminClient {
3277        Builder::new()
3278            .set_feature_levels(HashMap::from([("feature".to_string(), 3i16)]))
3279            .set_min_supported_feature_levels(HashMap::from([("feature".to_string(), 1i16)]))
3280            .set_max_supported_feature_levels(HashMap::from([("feature".to_string(), 5i16)]))
3281            .build()
3282            .expect("a fresh builder has one broker")
3283    }
3284
3285    async fn update_one(mock: &MockAdminClient, next: i16, upgrade_type: UpgradeType) -> Result<(), Error> {
3286        let updates = HashMap::from([("feature".to_string(), FeatureUpdate::new(next, upgrade_type).unwrap())]);
3287        let result = mock
3288            .update_features_with_options(&updates, UpdateFeaturesOptions::new())
3289            .unwrap();
3290        result.values()["feature"].get().await
3291    }
3292
3293    /// Java's `MockAdminClient.unregisterController` without a Raft controller
3294    /// (the builder default): `new UnsupportedVersionException("")`.
3295    #[tokio::test]
3296    async fn mock_unregister_controller_without_raft_controller_is_unsupported() {
3297        let mock = admin();
3298        let err = mock.unregister_controller(1).all().get().await.unwrap_err();
3299        assert_eq!(err.error(), Errors::UnsupportedVersion);
3300        assert_eq!(err.message(), "");
3301    }
3302
3303    /// With `usingRaftController(true)` the future is already completed.
3304    #[tokio::test]
3305    async fn mock_unregister_controller_with_raft_controller_succeeds() {
3306        let mock = Builder::new()
3307            .set_using_raft_controller(true)
3308            .build()
3309            .expect("a fresh builder has one broker");
3310        let result = mock.unregister_controller_with_options(1, UnregisterControllerOptions::new());
3311        assert!(result.all().is_done());
3312        result.all().get().await.unwrap();
3313    }
3314    #[tokio::test]
3315    async fn mock_describe_features_returns_seeded_ranges() {
3316        let mock = admin_with_features();
3317        let metadata = mock
3318            .describe_features_with_options(DescribeFeaturesOptions::new())
3319            .feature_metadata()
3320            .get()
3321            .await
3322            .unwrap();
3323        assert_eq!(metadata.finalized_features_epoch(), Some(123));
3324        assert_eq!(
3325            metadata.finalized_features()["feature"],
3326            FinalizedVersionRange::new(3, 3).unwrap()
3327        );
3328        assert_eq!(
3329            metadata.supported_features()["feature"],
3330            SupportedVersionRange::new(1, 5).unwrap()
3331        );
3332    }
3333
3334    #[tokio::test]
3335    async fn mock_update_features_upgrade_succeeds_and_mutates_level() {
3336        let mock = admin_with_features();
3337        update_one(&mock, 4, UpgradeType::Upgrade).await.unwrap();
3338        // The finalized level is now 4.
3339        let metadata = mock
3340            .describe_features_with_options(DescribeFeaturesOptions::new())
3341            .feature_metadata()
3342            .get()
3343            .await
3344            .unwrap();
3345        assert_eq!(
3346            metadata.finalized_features()["feature"],
3347            FinalizedVersionRange::new(4, 4).unwrap()
3348        );
3349    }
3350
3351    #[tokio::test]
3352    async fn mock_update_features_validate_only_does_not_mutate() {
3353        let mock = admin_with_features();
3354        let updates = HashMap::from([("feature".to_string(), FeatureUpdate::new(4, UpgradeType::Upgrade).unwrap())]);
3355        let result = mock
3356            .update_features_with_options(&updates, UpdateFeaturesOptions::new().set_validate_only(true))
3357            .unwrap();
3358        result.values()["feature"].get().await.unwrap();
3359        // Level unchanged because validate_only was set.
3360        let metadata = mock
3361            .describe_features_with_options(DescribeFeaturesOptions::new())
3362            .feature_metadata()
3363            .get()
3364            .await
3365            .unwrap();
3366        assert_eq!(
3367            metadata.finalized_features()["feature"],
3368            FinalizedVersionRange::new(3, 3).unwrap()
3369        );
3370    }
3371
3372    #[tokio::test]
3373    async fn mock_update_features_rejects_upgrade_to_lower_version() {
3374        let mock = admin_with_features();
3375        let err = update_one(&mock, 2, UpgradeType::Upgrade).await.unwrap_err();
3376        assert_eq!(err.error(), Errors::InvalidRequest);
3377        assert_eq!(
3378            err.message(),
3379            "Invalid update version 2 for feature feature. Can't upgrade to lower version."
3380        );
3381    }
3382
3383    #[tokio::test]
3384    async fn mock_update_features_rejects_safe_downgrade_to_newer_version() {
3385        let mock = admin_with_features();
3386        let err = update_one(&mock, 4, UpgradeType::SafeDowngrade).await.unwrap_err();
3387        assert_eq!(err.error(), Errors::InvalidRequest);
3388        assert_eq!(
3389            err.message(),
3390            "Invalid update version 4 for feature feature. Can't downgrade to newer version."
3391        );
3392    }
3393
3394    #[tokio::test]
3395    async fn mock_update_features_rejects_upgrade_above_max() {
3396        let mock = admin_with_features();
3397        let err = update_one(&mock, 6, UpgradeType::Upgrade).await.unwrap_err();
3398        assert_eq!(err.error(), Errors::InvalidRequest);
3399        assert_eq!(
3400            err.message(),
3401            "Invalid update version 6 for feature feature. Can't upgrade above 5"
3402        );
3403    }
3404
3405    #[tokio::test]
3406    async fn mock_update_features_rejects_downgrade_below_min() {
3407        let mock = admin_with_features();
3408        // next = 0 (a deletion), with SAFE_DOWNGRADE; min is 1.
3409        let err = update_one(&mock, 0, UpgradeType::SafeDowngrade).await.unwrap_err();
3410        assert_eq!(err.error(), Errors::InvalidRequest);
3411        assert_eq!(
3412            err.message(),
3413            "Invalid update version 0 for feature feature. Can't downgrade below 1"
3414        );
3415    }
3416
3417    #[tokio::test]
3418    async fn mock_update_features_rejects_unknown_upgrade_type() {
3419        let mock = admin_with_features();
3420        let err = update_one(&mock, 2, UpgradeType::Unknown).await.unwrap_err();
3421        assert_eq!(err.error(), Errors::InvalidRequest);
3422        assert_eq!(
3423            err.message(),
3424            "Invalid update version 2 for feature feature. Invalid upgrade type."
3425        );
3426    }
3427
3428    #[tokio::test]
3429    async fn mock_update_features_unsafe_downgrade_succeeds() {
3430        let mock = admin_with_features();
3431        // cur = 3, next = 2, UNSAFE_DOWNGRADE: allowed (the mock's even-level
3432        // guard is dead code, mirroring Java).
3433        update_one(&mock, 2, UpgradeType::UnsafeDowngrade).await.unwrap();
3434        let metadata = mock
3435            .describe_features_with_options(DescribeFeaturesOptions::new())
3436            .feature_metadata()
3437            .get()
3438            .await
3439            .unwrap();
3440        assert_eq!(
3441            metadata.finalized_features()["feature"],
3442            FinalizedVersionRange::new(2, 2).unwrap()
3443        );
3444    }
3445
3446    #[tokio::test]
3447    async fn create_then_list_and_describe() {
3448        let client = admin();
3449        let result = client.create_topics_with_options(
3450            &[NewTopic::with_num_partitions_replication_factor("t", Some(2), Some(2))],
3451            CreateTopicsOptions::new(),
3452        );
3453        result.all().get().await.unwrap();
3454        assert_eq!(result.num_partitions("t").get().await.unwrap(), 2);
3455        assert_eq!(result.replication_factor("t").get().await.unwrap(), 2);
3456
3457        let names = client
3458            .list_topics_with_options(ListTopicsOptions::new())
3459            .names()
3460            .get()
3461            .await
3462            .unwrap();
3463        assert!(names.contains("t"));
3464
3465        let desc = client
3466            .describe_topics_with_topics_options(
3467                TopicCollection::of_topic_names(vec!["t".to_string()]),
3468                DescribeTopicsOptions::new(),
3469            )
3470            .all_topic_names()
3471            .unwrap()
3472            .get()
3473            .await
3474            .unwrap();
3475        assert_eq!(desc["t"].partitions().len(), 2);
3476    }
3477
3478    #[tokio::test]
3479    async fn create_existing_topic_fails_with_topic_exists() {
3480        let client = admin();
3481        client
3482            .create_topics_with_options(
3483                &[NewTopic::with_num_partitions_replication_factor("t", Some(1), Some(1))],
3484                CreateTopicsOptions::new(),
3485            )
3486            .all()
3487            .get()
3488            .await
3489            .unwrap();
3490        let result = client.create_topics_with_options(
3491            &[NewTopic::with_num_partitions_replication_factor("t", Some(1), Some(1))],
3492            CreateTopicsOptions::new(),
3493        );
3494        let err = result.values()["t"].get().await.unwrap_err();
3495        assert_eq!(err.error(), Errors::TopicAlreadyExists);
3496        assert_eq!(err.message(), "Topic t exists already.");
3497    }
3498
3499    #[tokio::test]
3500    async fn create_with_replication_factor_too_large_fails() {
3501        let client = Builder::new().build().expect("a fresh builder has one broker");
3502        let result = client.create_topics_with_options(
3503            &[NewTopic::with_num_partitions_replication_factor("t", Some(1), Some(5))],
3504            CreateTopicsOptions::new(),
3505        );
3506        let err = result.values()["t"].get().await.unwrap_err();
3507        assert_eq!(err.error(), Errors::InvalidReplicationFactor);
3508    }
3509
3510    #[tokio::test]
3511    async fn mock_create_topics_rejects_a_leader_with_no_log_directories() {
3512        let client = Builder::new()
3513            .set_broker_log_dirs(vec![Vec::new()])
3514            .build()
3515            .expect("a fresh builder has one broker");
3516        let result = client.create_topics_with_options(
3517            &[NewTopic::with_num_partitions_replication_factor("t", Some(1), Some(1))],
3518            CreateTopicsOptions::new(),
3519        );
3520        let err = result.values()["t"].get().await.unwrap_err();
3521        assert_eq!(err.message(), "Broker 0 has no log directories.");
3522    }
3523
3524    #[tokio::test]
3525    async fn describe_nonexistent_topic_is_unknown_topic() {
3526        let client = admin();
3527        let result = client.describe_topics_with_topics_options(
3528            TopicCollection::of_topic_names(vec!["missing".to_string()]),
3529            DescribeTopicsOptions::new(),
3530        );
3531        let err = result.topic_name_values().unwrap()["missing"].get().await.unwrap_err();
3532        assert_eq!(err.error(), Errors::UnknownTopicOrPartition);
3533        assert_eq!(err.message(), "Topic missing not found.");
3534    }
3535
3536    #[tokio::test]
3537    async fn delete_then_gone() {
3538        let client = admin();
3539        client
3540            .create_topics_with_options(
3541                &[NewTopic::with_num_partitions_replication_factor("t", Some(1), Some(1))],
3542                CreateTopicsOptions::new(),
3543            )
3544            .all()
3545            .get()
3546            .await
3547            .unwrap();
3548        client
3549            .delete_topics_with_topic_collection_options(
3550                TopicCollection::of_topic_names(vec!["t".to_string()]),
3551                DeleteTopicsOptions::new(),
3552            )
3553            .all()
3554            .get()
3555            .await
3556            .unwrap();
3557        let names = client
3558            .list_topics_with_options(ListTopicsOptions::new())
3559            .names()
3560            .get()
3561            .await
3562            .unwrap();
3563        assert!(!names.contains("t"));
3564    }
3565
3566    #[tokio::test]
3567    async fn delete_missing_topic_fails() {
3568        let client = admin();
3569        let result = client.delete_topics_with_topic_collection_options(
3570            TopicCollection::of_topic_names(vec!["nope".to_string()]),
3571            DeleteTopicsOptions::new(),
3572        );
3573        let err = result.topic_name_values().unwrap()["nope"].get().await.unwrap_err();
3574        assert_eq!(err.error(), Errors::UnknownTopicOrPartition);
3575    }
3576
3577    #[tokio::test]
3578    async fn timeout_next_request_times_out_create() {
3579        let client = admin();
3580        client.timeout_next_request(1);
3581        let result = client.create_topics_with_options(
3582            &[NewTopic::with_num_partitions_replication_factor("t", Some(1), Some(1))],
3583            CreateTopicsOptions::new(),
3584        );
3585        assert!(matches!(result.values()["t"].get().await, Err(Error::Timeout(_))));
3586        // Next request succeeds.
3587        let result2 = client.create_topics_with_options(
3588            &[NewTopic::with_num_partitions_replication_factor("t2", Some(1), Some(1))],
3589            CreateTopicsOptions::new(),
3590        );
3591        result2.all().get().await.unwrap();
3592    }
3593
3594    #[tokio::test]
3595    async fn describe_cluster_returns_brokers_and_controller() {
3596        let client = admin();
3597        let result = client.describe_cluster_with_options(DescribeClusterOptions::new());
3598        let nodes = result.nodes().get().await.unwrap();
3599        assert_eq!(nodes.len(), 3);
3600        let controller = result.controller().get().await.unwrap();
3601        assert_eq!(controller.unwrap().id(), 0);
3602        assert_eq!(result.cluster_id().get().await.unwrap(), MockAdminClient::DEFAULT_CLUSTER_ID);
3603        assert!(result.authorized_operations().get().await.unwrap().unwrap().is_empty());
3604    }
3605
3606    #[tokio::test]
3607    async fn describe_cluster_timeout_recovers_on_next_call() {
3608        let client = admin();
3609        client.timeout_next_request(1);
3610        // First call times out on every future.
3611        let timed_out = client.describe_cluster_with_options(DescribeClusterOptions::new());
3612        assert!(matches!(timed_out.nodes().get().await, Err(Error::Timeout(_))));
3613        assert!(matches!(timed_out.controller().get().await, Err(Error::Timeout(_))));
3614        assert!(matches!(timed_out.cluster_id().get().await, Err(Error::Timeout(_))));
3615        // The counter is decremented, so the next call succeeds.
3616        let recovered = client.describe_cluster_with_options(DescribeClusterOptions::new());
3617        assert_eq!(recovered.nodes().get().await.unwrap().len(), 3);
3618    }
3619
3620    /// Describes one resource's configs from `client`.
3621    async fn described(client: &MockAdminClient, resource: &ConfigResource) -> Config {
3622        let result =
3623            client.describe_configs_with_options(std::slice::from_ref(resource), DescribeConfigsOptions::new());
3624        result.values()[resource].get().await.unwrap()
3625    }
3626
3627    /// New test, no Java original: Java's `incrementalAlterConfigs` stores a
3628    /// `SET` value as given, `null` included, for every resource type
3629    /// (`MockAdminClient#handleIncrementalResourceAlteration`), so `describeConfigs` reads
3630    /// the config back with a `null` value. For a group, Java then overlays the
3631    /// default configs with `putIfAbsent` (`MockAdminClient#getResourceDescription`), which also replaces a
3632    /// `null` value, so a group config set to `null` that has a default reads
3633    /// back as the default.
3634    #[tokio::test]
3635    async fn describe_configs_returns_a_null_value_set_by_incremental_alter_configs() {
3636        let client = Builder::new()
3637            .set_default_group_configs(HashMap::from([(
3638                "consumer.session.timeout.ms".to_string(),
3639                "45000".to_string(),
3640            )]))
3641            .build()
3642            .unwrap();
3643        client
3644            .create_topics_with_options(
3645                &[NewTopic::with_num_partitions_replication_factor("t", Some(1), Some(1))],
3646                CreateTopicsOptions::new(),
3647            )
3648            .all()
3649            .get()
3650            .await
3651            .unwrap();
3652        let set_null = |name: &str| AlterConfigOp::new(ConfigEntry::new(name.to_string(), None), OpType::Set);
3653        let topic = ConfigResource::new(config_resource::Type::Topic, "t".to_string());
3654        let broker = ConfigResource::new(config_resource::Type::Broker, "0".to_string());
3655        let metrics = ConfigResource::new(config_resource::Type::ClientMetrics, "metrics".to_string());
3656        let group = ConfigResource::new(config_resource::Type::Group, "group".to_string());
3657        let configs = HashMap::from([
3658            (topic.clone(), vec![set_null("cleanup.policy")]),
3659            (broker.clone(), vec![set_null("log.retention.ms")]),
3660            (metrics.clone(), vec![set_null("interval.ms")]),
3661            (
3662                group.clone(),
3663                vec![
3664                    set_null("consumer.heartbeat.interval.ms"),
3665                    set_null("consumer.session.timeout.ms"),
3666                ],
3667            ),
3668        ]);
3669        client
3670            .incremental_alter_configs_with_options(&configs, AlterConfigsOptions::new())
3671            .all()
3672            .get()
3673            .await
3674            .unwrap();
3675
3676        for (resource, name) in [
3677            (&topic, "cleanup.policy"),
3678            (&broker, "log.retention.ms"),
3679            (&metrics, "interval.ms"),
3680            (&group, "consumer.heartbeat.interval.ms"),
3681        ] {
3682            let config = described(&client, resource).await;
3683            assert_eq!(
3684                config
3685                    .get(name)
3686                    .unwrap_or_else(|| panic!("{name} is stored for {resource}"))
3687                    .value(),
3688                None,
3689                "{resource}"
3690            );
3691        }
3692        let group_config = described(&client, &group).await;
3693        assert_eq!(group_config.get("consumer.session.timeout.ms").unwrap().value(), Some("45000"));
3694    }
3695
3696    #[tokio::test]
3697    async fn describe_configs_topic_returns_stored_configs() {
3698        let client = admin();
3699        let mut configs = BTreeMap::new();
3700        configs.insert("retention.ms".to_string(), "1000".to_string());
3701        let new_topic =
3702            NewTopic::with_num_partitions_replication_factor("t", Some(1), Some(1)).set_configs(Some(configs));
3703        client
3704            .create_topics_with_options(&[new_topic], CreateTopicsOptions::new())
3705            .all()
3706            .get()
3707            .await
3708            .unwrap();
3709
3710        let resource = ConfigResource::new(config_resource::Type::Topic, "t".to_string());
3711        let result =
3712            client.describe_configs_with_options(std::slice::from_ref(&resource), DescribeConfigsOptions::new());
3713        let config = result.values()[&resource].get().await.unwrap();
3714        assert_eq!(config.get("retention.ms").unwrap().value(), Some("1000"));
3715    }
3716
3717    #[tokio::test]
3718    async fn describe_configs_broker_returns_default_replication_factor() {
3719        let client = admin();
3720        let resource = ConfigResource::new(config_resource::Type::Broker, "0".to_string());
3721        let result =
3722            client.describe_configs_with_options(std::slice::from_ref(&resource), DescribeConfigsOptions::new());
3723        let config = result.values()[&resource].get().await.unwrap();
3724        assert_eq!(config.get("default.replication.factor").unwrap().value(), Some("3"));
3725    }
3726
3727    #[tokio::test]
3728    async fn describe_configs_unknown_topic_is_unknown_topic_error() {
3729        let client = admin();
3730        let resource = ConfigResource::new(config_resource::Type::Topic, "missing".to_string());
3731        let result =
3732            client.describe_configs_with_options(std::slice::from_ref(&resource), DescribeConfigsOptions::new());
3733        let err = result.values()[&resource].get().await.unwrap_err();
3734        assert_eq!(err.error(), Errors::UnknownTopicOrPartition);
3735        assert_eq!(err.message(), "Resource ConfigResource(type=TOPIC, name='missing') not found.");
3736    }
3737
3738    #[tokio::test]
3739    async fn describe_configs_unknown_broker_is_invalid_request() {
3740        let client = admin();
3741        let resource = ConfigResource::new(config_resource::Type::Broker, "99".to_string());
3742        let result =
3743            client.describe_configs_with_options(std::slice::from_ref(&resource), DescribeConfigsOptions::new());
3744        let err = result.values()[&resource].get().await.unwrap_err();
3745        assert_eq!(err.error(), Errors::InvalidRequest);
3746        assert_eq!(err.message(), "Broker 99 not found.");
3747    }
3748
3749    #[tokio::test]
3750    async fn describe_configs_timeout_recovers_on_next_call() {
3751        let client = admin();
3752        client.timeout_next_request(1);
3753        let resource = ConfigResource::new(config_resource::Type::Broker, "0".to_string());
3754        let timed_out =
3755            client.describe_configs_with_options(std::slice::from_ref(&resource), DescribeConfigsOptions::new());
3756        assert!(matches!(timed_out.values()[&resource].get().await, Err(Error::Timeout(_))));
3757        let recovered =
3758            client.describe_configs_with_options(std::slice::from_ref(&resource), DescribeConfigsOptions::new());
3759        recovered.values()[&resource].get().await.unwrap();
3760    }
3761
3762    #[tokio::test]
3763    async fn incremental_alter_configs_topic_set_and_delete() {
3764        let client = admin();
3765        client
3766            .create_topics_with_options(
3767                &[NewTopic::with_num_partitions_replication_factor("t", Some(1), Some(1))],
3768                CreateTopicsOptions::new(),
3769            )
3770            .all()
3771            .get()
3772            .await
3773            .unwrap();
3774        let resource = ConfigResource::new(config_resource::Type::Topic, "t".to_string());
3775
3776        // SET.
3777        let set_op = AlterConfigOp::new(
3778            ConfigEntry::new("retention.ms".to_string(), Some("42".to_string())),
3779            OpType::Set,
3780        );
3781        let mut configs = HashMap::new();
3782        configs.insert(resource.clone(), vec![set_op]);
3783        client
3784            .incremental_alter_configs_with_options(&configs, AlterConfigsOptions::new())
3785            .all()
3786            .get()
3787            .await
3788            .unwrap();
3789
3790        let described =
3791            client.describe_configs_with_options(std::slice::from_ref(&resource), DescribeConfigsOptions::new());
3792        assert_eq!(
3793            described.values()[&resource]
3794                .get()
3795                .await
3796                .unwrap()
3797                .get("retention.ms")
3798                .unwrap()
3799                .value(),
3800            Some("42")
3801        );
3802
3803        // DELETE.
3804        let delete_op = AlterConfigOp::new(ConfigEntry::new("retention.ms".to_string(), None), OpType::Delete);
3805        let mut configs = HashMap::new();
3806        configs.insert(resource.clone(), vec![delete_op]);
3807        client
3808            .incremental_alter_configs_with_options(&configs, AlterConfigsOptions::new())
3809            .all()
3810            .get()
3811            .await
3812            .unwrap();
3813        let described =
3814            client.describe_configs_with_options(std::slice::from_ref(&resource), DescribeConfigsOptions::new());
3815        assert!(described.values()[&resource].get().await.unwrap().get("retention.ms").is_none());
3816    }
3817
3818    #[tokio::test]
3819    async fn incremental_alter_configs_unknown_topic_is_unknown_topic_error() {
3820        let client = admin();
3821        let resource = ConfigResource::new(config_resource::Type::Topic, "missing".to_string());
3822        let op = AlterConfigOp::new(ConfigEntry::new("k".to_string(), Some("v".to_string())), OpType::Set);
3823        let mut configs = HashMap::new();
3824        configs.insert(resource.clone(), vec![op]);
3825        let result = client.incremental_alter_configs_with_options(&configs, AlterConfigsOptions::new());
3826        let err = result.values()[&resource].get().await.unwrap_err();
3827        assert_eq!(err.error(), Errors::UnknownTopicOrPartition);
3828        assert_eq!(err.message(), "No such topic as missing");
3829    }
3830
3831    /// Java's `MockAdminClient#handleIncrementalResourceAlteration` returns
3832    /// `new UnsupportedOperationException()`, with no message, for a resource
3833    /// type it does not handle.
3834    #[tokio::test]
3835    async fn incremental_alter_configs_broker_logger_is_unsupported_without_message() {
3836        let client = admin();
3837        let resource = ConfigResource::new(config_resource::Type::BrokerLogger, "0".to_string());
3838        let op = AlterConfigOp::new(ConfigEntry::new("k".to_string(), Some("v".to_string())), OpType::Set);
3839        let configs = HashMap::from([(resource.clone(), vec![op])]);
3840        let result = client.incremental_alter_configs_with_options(&configs, AlterConfigsOptions::new());
3841        let err = result.values()[&resource].get().await.unwrap_err();
3842        assert!(err.is_local_unsupported_operation_error(), "{err:?}");
3843        assert_eq!(err.message(), "");
3844    }
3845
3846    #[tokio::test]
3847    async fn incremental_alter_configs_client_metrics_creates_resource() {
3848        let client = admin();
3849        let resource = ConfigResource::new(config_resource::Type::ClientMetrics, "cm".to_string());
3850        let op = AlterConfigOp::new(
3851            ConfigEntry::new("interval.ms".to_string(), Some("5000".to_string())),
3852            OpType::Set,
3853        );
3854        let mut configs = HashMap::new();
3855        configs.insert(resource.clone(), vec![op]);
3856        client
3857            .incremental_alter_configs_with_options(&configs, AlterConfigsOptions::new())
3858            .all()
3859            .get()
3860            .await
3861            .unwrap();
3862
3863        // The new client-metrics resource now shows up in list_config_resources.
3864        let listed = client
3865            .list_config_resources_with_options(
3866                &HashSet::from([config_resource::Type::ClientMetrics]),
3867                ListConfigResourcesOptions::new(),
3868            )
3869            .all()
3870            .get()
3871            .await
3872            .unwrap();
3873        assert!(listed.contains(&resource));
3874    }
3875
3876    #[tokio::test]
3877    async fn incremental_alter_configs_empty_client_metrics_name_is_invalid_request() {
3878        let client = admin();
3879        let resource = ConfigResource::new(config_resource::Type::ClientMetrics, String::new());
3880        let op = AlterConfigOp::new(ConfigEntry::new("k".to_string(), Some("v".to_string())), OpType::Set);
3881        let mut configs = HashMap::new();
3882        configs.insert(resource.clone(), vec![op]);
3883        let result = client.incremental_alter_configs_with_options(&configs, AlterConfigsOptions::new());
3884        let err = result.values()[&resource].get().await.unwrap_err();
3885        assert_eq!(err.error(), Errors::InvalidRequest);
3886        assert_eq!(err.message(), "Empty resource name");
3887    }
3888
3889    #[tokio::test]
3890    async fn list_config_resources_all_types_when_empty() {
3891        let client = admin();
3892        client
3893            .create_topics_with_options(
3894                &[NewTopic::with_num_partitions_replication_factor("t", Some(1), Some(1))],
3895                CreateTopicsOptions::new(),
3896            )
3897            .all()
3898            .get()
3899            .await
3900            .unwrap();
3901        let listed = client
3902            .list_config_resources_with_options(&HashSet::new(), ListConfigResourcesOptions::new())
3903            .all()
3904            .get()
3905            .await
3906            .unwrap();
3907        let set: HashSet<ConfigResource> = listed.into_iter().collect();
3908        assert!(set.contains(&ConfigResource::new(config_resource::Type::Topic, "t".to_string())));
3909        // 3 brokers -> broker 0..2 and broker-logger 0..2.
3910        for i in 0..3 {
3911            assert!(set.contains(&ConfigResource::new(config_resource::Type::Broker, i.to_string())));
3912            assert!(set.contains(&ConfigResource::new(config_resource::Type::BrokerLogger, i.to_string())));
3913        }
3914    }
3915
3916    #[tokio::test]
3917    async fn list_config_resources_filters_by_type() {
3918        let client = admin();
3919        client
3920            .create_topics_with_options(
3921                &[NewTopic::with_num_partitions_replication_factor("t", Some(1), Some(1))],
3922                CreateTopicsOptions::new(),
3923            )
3924            .all()
3925            .get()
3926            .await
3927            .unwrap();
3928        let listed = client
3929            .list_config_resources_with_options(
3930                &HashSet::from([config_resource::Type::Topic]),
3931                ListConfigResourcesOptions::new(),
3932            )
3933            .all()
3934            .get()
3935            .await
3936            .unwrap();
3937        assert_eq!(listed, vec![ConfigResource::new(config_resource::Type::Topic, "t".to_string())]);
3938    }
3939
3940    // --- Delegation tokens ---
3941    //
3942    // There are ZERO Java client-side unit tests for delegation tokens anywhere
3943    // in `clients/src/test/java` (Milestone-11 finding #10). The tests below are
3944    // NEW, written against `org.apache.kafka.clients.admin.MockAdminClient`'s
3945    // real in-memory logic (`createDelegationToken`, `renewDelegationToken`,
3946    // `expireDelegationToken` and `describeDelegationToken`), which is the
3947    // authoritative behavioral reference for this phase.
3948
3949    fn user(name: &str) -> KafkaPrincipal {
3950        KafkaPrincipal::new(KafkaPrincipal::USER_TYPE, name)
3951    }
3952
3953    /// New test, no Java original: a non-`User`-type renewer is rejected with
3954    /// `InvalidPrincipalType` and the exact (empty) message Java uses.
3955    #[tokio::test]
3956    async fn create_delegation_token_rejects_non_user_renewer() {
3957        let client = admin();
3958        let options = CreateDelegationTokenOptions::new().set_renewers(vec![KafkaPrincipal::new("Group", "admins")]);
3959        let err = client
3960            .create_delegation_token_with_options(options)
3961            .delegation_token()
3962            .get()
3963            .await
3964            .unwrap_err();
3965        assert_eq!(err.error(), Errors::InvalidPrincipalType);
3966        assert_eq!(err.message(), "");
3967    }
3968
3969    /// New test, no Java original: with no renewer at all the future completes
3970    /// exceptionally rather than panicking. Java's `options.renewers().get(0)`
3971    /// (in `MockAdminClient#createDelegationToken`) throws a catchable
3972    /// `IndexOutOfBoundsException` here; an index panic in Rust would unwind
3973    /// across the C FFI boundary and abort the process, so the mock reports it
3974    /// as an error instead. `CreateDelegationTokenOptions::new()` defaults the
3975    /// renewer list to empty, so this is the *default* call.
3976    #[tokio::test]
3977    async fn create_delegation_token_without_a_renewer_reports_an_error() {
3978        let client = admin();
3979        let err = client
3980            .create_delegation_token_with_options(CreateDelegationTokenOptions::new())
3981            .delegation_token()
3982            .get()
3983            .await
3984            .unwrap_err();
3985        assert_eq!(
3986            err.message(),
3987            "createDelegationToken requires at least one renewer: MockAdminClient makes the first renewer the owner"
3988        );
3989        // Nothing was stored, so a describe still finds no tokens.
3990        assert!(
3991            client
3992                .describe_delegation_token_with_options(DescribeDelegationTokenOptions::new())
3993                .delegation_tokens()
3994                .get()
3995                .await
3996                .unwrap()
3997                .is_empty()
3998        );
3999    }
4000
4001    /// New test, no Java original: a created token is owned by the first
4002    /// renewer, has the `-1` (unexpired) sentinel, and is listed by an
4003    /// unfiltered describe.
4004    #[tokio::test]
4005    async fn create_then_describe_lists_token() {
4006        let client = admin();
4007        let options = CreateDelegationTokenOptions::new()
4008            .set_renewers(vec![user("alice")])
4009            .set_max_lifetime_ms(1000);
4010        let token = client
4011            .create_delegation_token_with_options(options)
4012            .delegation_token()
4013            .get()
4014            .await
4015            .unwrap();
4016        assert_eq!(token.token_info().owner(), &user("alice"));
4017        assert_eq!(token.token_info().max_timestamp(), 1000);
4018        assert_eq!(token.token_info().expiry_timestamp(), -1);
4019        assert_eq!(token.hmac(), token.token_info().token_id().as_bytes());
4020
4021        let listed = client
4022            .describe_delegation_token_with_options(DescribeDelegationTokenOptions::new())
4023            .delegation_tokens()
4024            .get()
4025            .await
4026            .unwrap();
4027        assert_eq!(listed, vec![token]);
4028    }
4029
4030    /// New test, no Java original: `{:?}` of a mock holding a token does not
4031    /// print the token's HMAC. The mock's HMAC is the UTF-8 bytes of the token
4032    /// id, and the id itself is rendered (Java's `TokenInformation.toString()`
4033    /// prints it too), so the check is on the byte rendering a derived `Debug`
4034    /// of the HMAC would produce.
4035    #[tokio::test]
4036    async fn debug_does_not_render_token_hmac() {
4037        let client = admin();
4038        let token = client
4039            .create_delegation_token_with_options(CreateDelegationTokenOptions::new().set_renewers(vec![user("alice")]))
4040            .delegation_token()
4041            .get()
4042            .await
4043            .unwrap();
4044        let rendered = format!("{client:?}");
4045        assert!(rendered.contains("hmac=[*******]"), "{rendered}");
4046        assert!(!rendered.contains(&format!("{:?}", token.hmac())), "HMAC leaked: {rendered}");
4047        // The pretty form spreads a byte list over indented lines, so check
4048        // for the derived field itself rather than for one fixed layout.
4049        let pretty = format!("{client:#?}");
4050        assert!(pretty.contains("hmac=[*******]"), "{pretty}");
4051        assert!(!pretty.contains("hmac: ["), "HMAC leaked: {pretty}");
4052    }
4053
4054    /// New test, no Java original (Java's `MockAdminClient` has no
4055    /// `toString()`): `{:?}` of a mock holding config values renders every
4056    /// config map as its key set, never a value. Covers the broker, topic,
4057    /// client-metrics and group configs and the group defaults, each holding a
4058    /// distinct value.
4059    #[tokio::test]
4060    async fn debug_does_not_render_config_values() {
4061        const BROKER_KEY: &str = "listener.name.sasl_ssl.plain.sasl.jaas.config";
4062        const BROKER_SECRET: &str = "broker-jaas-S3cr3t-6a1d";
4063        const TOPIC_KEY: &str = "retention.ms";
4064        const TOPIC_SECRET: &str = "topic-value-S3cr3t-0c5e";
4065        const CLIENT_METRICS_KEY: &str = "interval.ms";
4066        const CLIENT_METRICS_SECRET: &str = "metrics-value-S3cr3t-8b27";
4067        const GROUP_KEY: &str = "consumer.session.timeout.ms";
4068        const GROUP_SECRET: &str = "group-value-S3cr3t-3f90";
4069        const DEFAULT_GROUP_KEY: &str = "consumer.heartbeat.interval.ms";
4070        const DEFAULT_GROUP_SECRET: &str = "group-default-S3cr3t-d14b";
4071
4072        let client = admin();
4073        client
4074            .add_topic(
4075                false,
4076                "orders",
4077                Vec::new(),
4078                Some(BTreeMap::from([(TOPIC_KEY.to_string(), TOPIC_SECRET.to_string())])),
4079            )
4080            .unwrap();
4081        let set = |name: &str, value: &str| {
4082            AlterConfigOp::new(ConfigEntry::new(name.to_string(), Some(value.to_string())), OpType::Set)
4083        };
4084        let configs = HashMap::from([
4085            (
4086                ConfigResource::new(config_resource::Type::Broker, "0".to_string()),
4087                vec![set(BROKER_KEY, BROKER_SECRET)],
4088            ),
4089            (
4090                ConfigResource::new(config_resource::Type::ClientMetrics, "metrics".to_string()),
4091                vec![set(CLIENT_METRICS_KEY, CLIENT_METRICS_SECRET)],
4092            ),
4093            (
4094                ConfigResource::new(config_resource::Type::Group, "group".to_string()),
4095                vec![set(GROUP_KEY, GROUP_SECRET)],
4096            ),
4097        ]);
4098        client
4099            .incremental_alter_configs_with_options(&configs, AlterConfigsOptions::new())
4100            .all()
4101            .get()
4102            .await
4103            .unwrap();
4104        {
4105            // No public seeding API reaches the group defaults (Java's
4106            // `Builder.defaultGroupConfigs`), so seed them directly. The other
4107            // values are asserted stored, so the renderings below are what
4108            // hides them.
4109            let mut state = client.state.lock().unwrap();
4110            state
4111                .default_group_configs
4112                .insert(DEFAULT_GROUP_KEY.to_string(), DEFAULT_GROUP_SECRET.to_string());
4113            assert_eq!(state.broker_configs[0][BROKER_KEY].as_deref(), Some(BROKER_SECRET));
4114            assert_eq!(
4115                state.all_topics["orders"].configs.as_ref().unwrap()[TOPIC_KEY].as_deref(),
4116                Some(TOPIC_SECRET)
4117            );
4118            assert_eq!(
4119                state.client_metrics_configs["metrics"][CLIENT_METRICS_KEY].as_deref(),
4120                Some(CLIENT_METRICS_SECRET)
4121            );
4122            assert_eq!(state.group_configs["group"][GROUP_KEY].as_deref(), Some(GROUP_SECRET));
4123        }
4124
4125        let rendered = format!("{client:?}");
4126        assert!(rendered.contains("default_partitions: 1"), "{rendered}");
4127        assert!(
4128            rendered.contains(&format!(
4129                "broker_configs: [{{\"default.replication.factor\", \"{BROKER_KEY}\"}}, \
4130                 {{\"default.replication.factor\"}}, {{\"default.replication.factor\"}}]"
4131            )),
4132            "{rendered}"
4133        );
4134        assert!(rendered.contains(&format!("configs: Some({{\"{TOPIC_KEY}\"}})")), "{rendered}");
4135        assert!(
4136            rendered.contains(&format!(
4137                "client_metrics_configs: {{\"metrics\": {{\"{CLIENT_METRICS_KEY}\"}}}}"
4138            )),
4139            "{rendered}"
4140        );
4141        assert!(
4142            rendered.contains(&format!("group_configs: {{\"group\": {{\"{GROUP_KEY}\"}}}}")),
4143            "{rendered}"
4144        );
4145        assert!(
4146            rendered.contains(&format!("default_group_configs: {{\"{DEFAULT_GROUP_KEY}\"}}")),
4147            "{rendered}"
4148        );
4149        let pretty = format!("{client:#?}");
4150        for key in [BROKER_KEY, TOPIC_KEY, CLIENT_METRICS_KEY, GROUP_KEY, DEFAULT_GROUP_KEY] {
4151            assert!(pretty.contains(&format!("\"{key}\",")), "key {key} missing: {pretty}");
4152        }
4153        for rendered in [rendered, pretty] {
4154            for secret in [
4155                BROKER_SECRET,
4156                TOPIC_SECRET,
4157                CLIENT_METRICS_SECRET,
4158                GROUP_SECRET,
4159                DEFAULT_GROUP_SECRET,
4160            ] {
4161                assert!(!rendered.contains(secret), "config value {secret} leaked: {rendered}");
4162            }
4163            // The broker default is a config value too: only its key renders.
4164            assert!(!rendered.contains("\"default.replication.factor\": "), "{rendered}");
4165        }
4166    }
4167
4168    /// New test, no Java original: renewing an unknown HMAC fails with
4169    /// `DelegationTokenNotFound`; renewing a known HMAC updates the expiry.
4170    #[tokio::test]
4171    async fn renew_delegation_token_found_and_not_found() {
4172        let client = admin();
4173        let unknown = client
4174            .renew_delegation_token_with_options(
4175                b"nope",
4176                RenewDelegationTokenOptions::new().set_renew_time_period_ms(10),
4177            )
4178            .expiry_timestamp()
4179            .get()
4180            .await
4181            .unwrap_err();
4182        assert_eq!(unknown.error(), Errors::DelegationTokenNotFound);
4183        assert_eq!(unknown.message(), "");
4184
4185        let token = client
4186            .create_delegation_token_with_options(CreateDelegationTokenOptions::new().set_renewers(vec![user("alice")]))
4187            .delegation_token()
4188            .get()
4189            .await
4190            .unwrap();
4191        let expiry = client
4192            .renew_delegation_token_with_options(
4193                token.hmac(),
4194                RenewDelegationTokenOptions::new().set_renew_time_period_ms(4242),
4195            )
4196            .expiry_timestamp()
4197            .get()
4198            .await
4199            .unwrap();
4200        assert_eq!(expiry, 4242);
4201    }
4202
4203    /// New test, no Java original: expiring an unknown HMAC fails with
4204    /// `DelegationTokenNotFound`.
4205    #[tokio::test]
4206    async fn expire_delegation_token_not_found() {
4207        let client = admin();
4208        let err = client
4209            .expire_delegation_token_with_options(b"nope", ExpireDelegationTokenOptions::new())
4210            .expiry_timestamp()
4211            .get()
4212            .await
4213            .unwrap_err();
4214        assert_eq!(err.error(), Errors::DelegationTokenNotFound);
4215        assert_eq!(err.message(), "");
4216    }
4217
4218    /// New test, no Java original: expiring with the `-1` sentinel removes the
4219    /// token so a later describe no longer lists it.
4220    #[tokio::test]
4221    async fn expire_delegation_token_negative_one_removes_token() {
4222        let client = admin();
4223        let token = client
4224            .create_delegation_token_with_options(CreateDelegationTokenOptions::new().set_renewers(vec![user("alice")]))
4225            .delegation_token()
4226            .get()
4227            .await
4228            .unwrap();
4229
4230        let expiry = client
4231            .expire_delegation_token_with_options(
4232                token.hmac(),
4233                ExpireDelegationTokenOptions::new().set_expiry_time_period_ms(-1),
4234            )
4235            .expiry_timestamp()
4236            .get()
4237            .await
4238            .unwrap();
4239        assert_eq!(expiry, -1);
4240
4241        let listed = client
4242            .describe_delegation_token_with_options(DescribeDelegationTokenOptions::new())
4243            .delegation_tokens()
4244            .get()
4245            .await
4246            .unwrap();
4247        assert!(listed.is_empty());
4248    }
4249
4250    /// New test, no Java original: a describe with an `owners` filter returns
4251    /// only tokens whose owner matches.
4252    #[tokio::test]
4253    async fn describe_delegation_token_owners_filter() {
4254        let client = admin();
4255        let token_alice = client
4256            .create_delegation_token_with_options(CreateDelegationTokenOptions::new().set_renewers(vec![user("alice")]))
4257            .delegation_token()
4258            .get()
4259            .await
4260            .unwrap();
4261        let _token_bob = client
4262            .create_delegation_token_with_options(CreateDelegationTokenOptions::new().set_renewers(vec![user("bob")]))
4263            .delegation_token()
4264            .get()
4265            .await
4266            .unwrap();
4267
4268        let listed = client
4269            .describe_delegation_token_with_options(
4270                DescribeDelegationTokenOptions::new().set_owners(Some(vec![user("alice")])),
4271            )
4272            .delegation_tokens()
4273            .get()
4274            .await
4275            .unwrap();
4276        assert_eq!(listed, vec![token_alice]);
4277    }
4278
4279    /// Seeds one topic and reassigns its only partition.
4280    async fn admin_with_reassignment() -> (MockAdminClient, TopicPartition) {
4281        let client = admin();
4282        let new_topic = NewTopic::with_num_partitions_replication_factor("rt", Some(1), Some(3));
4283        client
4284            .create_topics_with_options(std::slice::from_ref(&new_topic), CreateTopicsOptions::new())
4285            .all()
4286            .get()
4287            .await
4288            .unwrap();
4289
4290        let tp = TopicPartition::new("rt".to_string(), 0);
4291        let target = NewPartitionReassignment::new(vec![1, 2]).unwrap();
4292        client
4293            .alter_partition_reassignments_with_options(
4294                &HashMap::from([(tp.clone(), Some(target))]),
4295                AlterPartitionReassignmentsOptions::new(),
4296            )
4297            .all()
4298            .get()
4299            .await
4300            .unwrap();
4301        (client, tp)
4302    }
4303
4304    #[tokio::test]
4305    async fn alter_then_list_partition_reassignments_reports_adding_and_removing() {
4306        let (client, tp) = admin_with_reassignment().await;
4307
4308        let listed = client
4309            .list_partition_reassignments_with_partitions_options(None, ListPartitionReassignmentsOptions::new())
4310            .reassignments()
4311            .get()
4312            .await
4313            .unwrap();
4314        let reassignment = &listed[&tp];
4315        // The mock seeds every partition with all three brokers as replicas, so
4316        // targeting {1, 2} removes broker 0 and adds nothing.
4317        assert_eq!(reassignment.replicas(), &[0, 1, 2]);
4318        assert_eq!(reassignment.adding_replicas(), &[] as &[i32]);
4319        assert_eq!(reassignment.removing_replicas(), &[0]);
4320
4321        // An empty `Optional` cancels
4322        // (`org.apache.kafka.clients.admin.MockAdminClient#alterPartitionReassignments`).
4323        client
4324            .alter_partition_reassignments_with_options(
4325                &HashMap::from([(tp.clone(), None)]),
4326                AlterPartitionReassignmentsOptions::new(),
4327            )
4328            .all()
4329            .get()
4330            .await
4331            .unwrap();
4332        let listed = client
4333            .list_partition_reassignments_with_partitions_options(None, ListPartitionReassignmentsOptions::new())
4334            .reassignments()
4335            .get()
4336            .await
4337            .unwrap();
4338        assert!(listed.is_empty());
4339    }
4340
4341    /// Regression: `deleteTopics` drops the topic from `all_topics` without
4342    /// pruning `reassignments` (as Java's does), so a subsequent
4343    /// `list_partition_reassignments` reaches `findPartitionReassignment`'s
4344    /// "no TopicMetadata" branch. Java throws a `RuntimeException` there; this
4345    /// client must fail the future rather than panic, because the panic would
4346    /// unwind out of a C FFI entry point.
4347    #[tokio::test]
4348    async fn list_partition_reassignments_after_topic_deletion_fails_the_future() {
4349        let (client, _tp) = admin_with_reassignment().await;
4350        client
4351            .delete_topics_with_topic_collection_options(
4352                TopicCollection::of_topic_names(vec!["rt".to_string()]),
4353                DeleteTopicsOptions::new(),
4354            )
4355            .all()
4356            .get()
4357            .await
4358            .unwrap();
4359
4360        let error = client
4361            .list_partition_reassignments_with_partitions_options(None, ListPartitionReassignmentsOptions::new())
4362            .reassignments()
4363            .get()
4364            .await
4365            .unwrap_err();
4366        assert_eq!(
4367            error.message(),
4368            "Internal MockAdminClient logic error: found reassignment for rt-0, but no TopicMetadata"
4369        );
4370    }
4371
4372    /// Regression for `MockAdminClient#findPartitionReassignment`'s *second*
4373    /// guard: the topic exists again, but the stale reassignment names a
4374    /// partition index the recreated topic no longer has.
4375    ///
4376    /// This branch is dead in Java — `metadata.partitions` is an `ArrayList`,
4377    /// so `get(i)` on an out-of-range index throws `IndexOutOfBoundsException`
4378    /// and can never return null — but it is live in Rust, where
4379    /// `Vec::get(i)` returns `None`. Rust therefore reports Java's intended
4380    /// message instead of Java's `IndexOutOfBoundsException`, and above all
4381    /// does not panic across the FFI boundary.
4382    #[tokio::test]
4383    async fn list_partition_reassignments_after_topic_shrink_fails_the_future() {
4384        let client = admin();
4385        let wide = NewTopic::with_num_partitions_replication_factor("rt2", Some(2), Some(3));
4386        client
4387            .create_topics_with_options(std::slice::from_ref(&wide), CreateTopicsOptions::new())
4388            .all()
4389            .get()
4390            .await
4391            .unwrap();
4392
4393        // Reassign the *second* partition, so the index survives the topic's
4394        // removal but not its recreation.
4395        let tp = TopicPartition::new("rt2".to_string(), 1);
4396        let target = NewPartitionReassignment::new(vec![1, 2]).unwrap();
4397        client
4398            .alter_partition_reassignments_with_options(
4399                &HashMap::from([(tp.clone(), Some(target))]),
4400                AlterPartitionReassignmentsOptions::new(),
4401            )
4402            .all()
4403            .get()
4404            .await
4405            .unwrap();
4406
4407        client
4408            .delete_topics_with_topic_collection_options(
4409                TopicCollection::of_topic_names(vec!["rt2".to_string()]),
4410                DeleteTopicsOptions::new(),
4411            )
4412            .all()
4413            .get()
4414            .await
4415            .unwrap();
4416
4417        let narrow = NewTopic::with_num_partitions_replication_factor("rt2", Some(1), Some(3));
4418        client
4419            .create_topics_with_options(std::slice::from_ref(&narrow), CreateTopicsOptions::new())
4420            .all()
4421            .get()
4422            .await
4423            .unwrap();
4424
4425        let error = client
4426            .list_partition_reassignments_with_partitions_options(None, ListPartitionReassignmentsOptions::new())
4427            .reassignments()
4428            .get()
4429            .await
4430            .unwrap_err();
4431        assert_eq!(
4432            error.message(),
4433            "Internal MockAdminClient logic error: found reassignment for rt2-1, but no TopicPartitionInfo"
4434        );
4435    }
4436    // --- add_topic broker validation -----------------------------------------
4437    // (`org.apache.kafka.clients.admin.MockAdminClient#addTopic(boolean,String,List,Map,boolean)`)
4438
4439    /// Builds a `TopicPartitionInfo` with the given leader / replicas / isr and
4440    /// no offline, ELR or last-known-ELR replicas.
4441    fn partition_info(partition: i32, leader: Option<Node>, replicas: Vec<Node>, isr: Vec<Node>) -> TopicPartitionInfo {
4442        TopicPartitionInfo::with_elr_last_known_elr(partition, leader, replicas, isr, Vec::new(), Vec::new())
4443    }
4444
4445    /// The nodes a [`Builder`] seeds, so a test can name a broker
4446    /// the mock actually has (`Node::new(id, "localhost", 1000 + id)`).
4447    fn seeded_broker(id: i32) -> Node {
4448        Node::new(id, "localhost".to_string(), 1000 + id)
4449    }
4450
4451    /// A node no seeded broker equals, for the "unknown broker" arms.
4452    fn unknown_broker() -> Node {
4453        Node::new(99, "elsewhere".to_string(), 9999)
4454    }
4455
4456    #[test]
4457    fn mock_add_topic_accepts_partitions_whose_brokers_are_all_known() {
4458        let mock = admin();
4459        let leader = seeded_broker(0);
4460        let replicas = vec![seeded_broker(0), seeded_broker(1)];
4461        mock.add_topic(
4462            false,
4463            "topic",
4464            vec![partition_info(0, Some(leader), replicas.clone(), replicas)],
4465            None,
4466        )
4467        .expect("every named broker is one of the mock's three");
4468    }
4469
4470    #[test]
4471    fn mock_add_topic_rejects_a_duplicate_topic() {
4472        let mock = admin();
4473        let leader = seeded_broker(0);
4474        let partitions = vec![partition_info(
4475            0,
4476            Some(leader),
4477            vec![seeded_broker(0)],
4478            vec![seeded_broker(0)],
4479        )];
4480        mock.add_topic(false, "topic", partitions.clone(), None).unwrap();
4481        let error = mock.add_topic(false, "topic", partitions, None).unwrap_err();
4482        assert!(
4483            matches!(error, Error::LocalIllegalArgument(_)),
4484            "Java throws IllegalArgumentException: {error:?}"
4485        );
4486        assert_eq!(error.message(), "Topic topic was already added.");
4487    }
4488
4489    #[tokio::test]
4490    async fn mock_add_topic_rejects_an_unknown_leader() {
4491        let mock = admin();
4492        let partitions = vec![partition_info(
4493            0,
4494            Some(unknown_broker()),
4495            vec![seeded_broker(0)],
4496            vec![],
4497        )];
4498        let error = mock.add_topic(false, "topic", partitions, None).unwrap_err();
4499        assert_eq!(error.message(), "Leader broker unknown");
4500        // Java's `brokers.contains(null)` is false for a leaderless partition, so
4501        // it takes this same branch rather than reaching the log-dir loop.
4502        let leaderless = vec![partition_info(0, None, vec![seeded_broker(0)], vec![])];
4503        let error = mock.add_topic(false, "other", leaderless, None).unwrap_err();
4504        assert_eq!(error.message(), "Leader broker unknown");
4505        // Neither rejected topic was recorded.
4506        let listed = mock
4507            .list_topics_with_options(ListTopicsOptions::new())
4508            .names()
4509            .get()
4510            .await
4511            .expect("listTopics succeeds");
4512        assert!(listed.is_empty(), "a rejected add_topic must not be recorded: {listed:?}");
4513    }
4514
4515    #[test]
4516    fn mock_add_topic_rejects_unknown_brokers_in_the_replica_list() {
4517        let mock = admin();
4518        let partitions = vec![partition_info(
4519            0,
4520            Some(seeded_broker(0)),
4521            vec![seeded_broker(0), unknown_broker()],
4522            vec![],
4523        )];
4524        let error = mock.add_topic(false, "topic", partitions, None).unwrap_err();
4525        assert_eq!(error.message(), "Unknown brokers in replica list");
4526    }
4527
4528    #[test]
4529    fn mock_add_topic_rejects_unknown_brokers_in_the_isr_list() {
4530        let mock = admin();
4531        // The replica list is fine here, so only the ISR check can fire -- which
4532        // pins the check order as well as the message.
4533        let partitions = vec![partition_info(
4534            0,
4535            Some(seeded_broker(0)),
4536            vec![seeded_broker(0)],
4537            vec![unknown_broker()],
4538        )];
4539        let error = mock.add_topic(false, "topic", partitions, None).unwrap_err();
4540        assert_eq!(error.message(), "Unknown brokers in isr list");
4541    }
4542
4543    #[test]
4544    fn mock_add_topic_rejects_a_leader_with_no_log_directories() {
4545        let mock = Builder::new()
4546            .set_broker_log_dirs(vec![Vec::new()])
4547            .build()
4548            .expect("a fresh builder has one broker");
4549        let partitions = vec![partition_info(
4550            0,
4551            Some(seeded_broker(0)),
4552            vec![seeded_broker(0)],
4553            vec![],
4554        )];
4555        let error = mock.add_topic(false, "topic", partitions, None).unwrap_err();
4556        assert_eq!(error.message(), "Broker 0 has no log directories.");
4557    }
4558
4559    // --- `org.apache.kafka.clients.admin.MockAdminClient#setFetchesRemainingUntilVisible` ---
4560    //
4561    // Rust-side tests, no Java counterpart: Java has no tests for the fetch
4562    // countdown. They were added with this port and check the behaviour against
4563    // the Java source cited on each test.
4564
4565    fn admin_with_topic(name: &str) -> MockAdminClient {
4566        let mock = admin();
4567        let leader = seeded_broker(0);
4568        mock.add_topic(
4569            false,
4570            name,
4571            vec![partition_info(
4572                0,
4573                Some(leader),
4574                vec![seeded_broker(0)],
4575                vec![seeded_broker(0)],
4576            )],
4577            None,
4578        )
4579        .expect("the leader is a seeded broker");
4580        mock
4581    }
4582
4583    /// `MockAdminClient#handleDescribeTopicsByNames`: while the
4584    /// counter is positive, each describe decrements it and reports
4585    /// `UnknownTopicOrPartitionException("Topic <name> not found.")`.
4586    #[tokio::test]
4587    async fn describe_topics_by_name_hides_the_topic_until_visible() {
4588        let mock = admin_with_topic("t");
4589        mock.set_fetches_remaining_until_visible("t", 2).expect("t exists");
4590        for _ in 0..2 {
4591            let result = mock.describe_topics_with_topics_options(
4592                TopicCollection::of_topic_names(vec!["t".to_string()]),
4593                DescribeTopicsOptions::new(),
4594            );
4595            let err = result.topic_name_values().unwrap()["t"]
4596                .get()
4597                .await
4598                .expect_err("not visible yet");
4599            assert!(matches!(err, Error::UnknownTopicOrPartition(_)), "got {err:?}");
4600            assert_eq!(err.message(), "Topic t not found.");
4601        }
4602        let result = mock.describe_topics_with_topics_options(
4603            TopicCollection::of_topic_names(vec!["t".to_string()]),
4604            DescribeTopicsOptions::new(),
4605        );
4606        let description = result.topic_name_values().unwrap()["t"].get().await.expect("now visible");
4607        assert_eq!(description.name(), "t");
4608    }
4609
4610    /// `MockAdminClient#handleDescribeTopicsUsingIds`: the same
4611    /// countdown, reporting `UnknownTopicIdException("Topic id" + id +
4612    /// " not found.")` -- Java's message has no space after "id".
4613    #[tokio::test]
4614    async fn describe_topics_by_id_hides_the_topic_until_visible() {
4615        let mock = admin_with_topic("t");
4616        let topic_id = mock.state.lock().unwrap().topic_ids["t"];
4617        mock.set_fetches_remaining_until_visible("t", 2).expect("t exists");
4618        for _ in 0..2 {
4619            let result = mock.describe_topics_with_topics_options(
4620                TopicCollection::of_topic_ids(vec![topic_id]),
4621                DescribeTopicsOptions::new(),
4622            );
4623            let err = result.topic_id_values().unwrap()[&topic_id]
4624                .get()
4625                .await
4626                .expect_err("not visible yet");
4627            assert!(matches!(err, Error::UnknownTopicId(_)), "got {err:?}");
4628            assert_eq!(err.message(), format!("Topic id{topic_id} not found."));
4629        }
4630        let result = mock.describe_topics_with_topics_options(
4631            TopicCollection::of_topic_ids(vec![topic_id]),
4632            DescribeTopicsOptions::new(),
4633        );
4634        let description = result.topic_id_values().unwrap()[&topic_id].get().await.expect("now visible");
4635        assert_eq!(description.name(), "t");
4636    }
4637
4638    /// Java throws `RuntimeException("No such topic as " + topicName)` for a
4639    /// topic the mock does not have.
4640    #[test]
4641    fn set_fetches_remaining_until_visible_rejects_an_unknown_topic() {
4642        let mock = admin();
4643        let err = mock
4644            .set_fetches_remaining_until_visible("nope", 1)
4645            .expect_err("nope does not exist");
4646        assert!(matches!(err, Error::LocalIllegalArgument(_)), "got {err:?}");
4647        assert_eq!(err.message(), "No such topic as nope");
4648    }
4649
4650    /// `MockAdminClient#listTopics` and the topic arm of
4651    /// `MockAdminClient#getResourceDescription` count down the same counter.
4652    #[tokio::test]
4653    async fn list_topics_and_describe_configs_count_down_the_same_counter() {
4654        let mock = admin_with_topic("t");
4655        mock.set_fetches_remaining_until_visible("t", 2).expect("t exists");
4656        let listed = mock
4657            .list_topics_with_options(ListTopicsOptions::new())
4658            .names()
4659            .get()
4660            .await
4661            .unwrap();
4662        assert!(listed.is_empty(), "first fetch hides t: {listed:?}");
4663        let resource = ConfigResource::new(config_resource::Type::Topic, "t".to_string());
4664        let err = mock
4665            .describe_configs_with_options(std::slice::from_ref(&resource), DescribeConfigsOptions::new())
4666            .values()[&resource]
4667            .get()
4668            .await
4669            .expect_err("second fetch hides t");
4670        assert!(matches!(err, Error::UnknownTopicOrPartition(_)), "got {err:?}");
4671        let listed = mock
4672            .list_topics_with_options(ListTopicsOptions::new())
4673            .names()
4674            .get()
4675            .await
4676            .unwrap();
4677        assert!(listed.contains("t"), "the counter reached zero: {listed:?}");
4678    }
4679
4680    #[test]
4681    fn mock_mark_topic_for_deletion_rejects_an_unknown_topic() {
4682        let mock = admin();
4683        let error = mock.mark_topic_for_deletion("nope").unwrap_err();
4684        assert!(
4685            matches!(error, Error::LocalIllegalArgument(_)),
4686            "Java throws IllegalArgumentException: {error:?}"
4687        );
4688        assert_eq!(error.message(), "Topic nope did not exist.");
4689    }
4690
4691    // --- list_consumer_group_offsets with a negative seeded offset -----------
4692
4693    #[tokio::test]
4694    async fn mock_list_consumer_group_offsets_rejects_a_negative_seeded_offset() {
4695        // `org.apache.kafka.clients.admin.MockAdminClient#updateConsumerGroupOffsets`
4696        // is an unvalidated `putAll` in Java, so -1 -- Kafka's own invalid-offset
4697        // sentinel -- is seedable. Java then throws
4698        // `IllegalArgumentException("Invalid negative offset")` from
4699        // `new OffsetAndMetadata(...)` while building the row (in
4700        // `MockAdminClient#listConsumerGroupOffsets` and
4701        // `org.apache.kafka.clients.consumer.OffsetAndMetadata#OffsetAndMetadata(long,Optional,String)`).
4702        // The Rust mock must surface a `Error`, not panic: the FFI runs this
4703        // inline on the caller's thread, so a panic would unwind out of
4704        // `extern "C"`.
4705        let mock = admin();
4706        let tp = TopicPartition::new("topic".to_string(), 0);
4707        mock.update_consumer_group_offsets(HashMap::from([(tp.clone(), -1i64)]));
4708
4709        let specs = HashMap::from([("group".to_string(), ListConsumerGroupOffsetsSpec::new())]);
4710        let error = mock
4711            .list_consumer_group_offsets_with_group_specs_options(&specs, ListConsumerGroupOffsetsOptions::new())
4712            .partitions_to_offset_and_metadata()
4713            .expect("exactly one group was requested")
4714            .get()
4715            .await
4716            .unwrap_err();
4717        assert!(
4718            matches!(error, Error::LocalIllegalArgument(_)),
4719            "Java throws IllegalArgumentException: {error:?}"
4720        );
4721        assert_eq!(error.message(), "Invalid negative offset");
4722
4723        // The mock is still usable afterwards -- which is the assertion that
4724        // distinguishes "returned an error" from "aborted the process".
4725        mock.update_consumer_group_offsets(HashMap::from([(tp.clone(), 7i64)]));
4726        let offsets = mock
4727            .list_consumer_group_offsets_with_group_specs_options(&specs, ListConsumerGroupOffsetsOptions::new())
4728            .partitions_to_offset_and_metadata()
4729            .expect("exactly one group was requested")
4730            .get()
4731            .await
4732            .expect("a non-negative offset lists cleanly");
4733        assert_eq!(offsets[&tp].as_ref().map(OffsetAndMetadata::offset), Some(7));
4734    }
4735
4736    #[tokio::test]
4737    async fn mock_list_consumer_group_offsets_negative_offset_outside_the_selection_is_ignored() {
4738        // The rejection follows Java's filter: a negative offset for a partition
4739        // the spec did not select is never turned into an `OffsetAndMetadata`, so
4740        // it cannot fail the call.
4741        let mock = admin();
4742        let selected = TopicPartition::new("topic".to_string(), 0);
4743        let other = TopicPartition::new("topic".to_string(), 1);
4744        mock.update_consumer_group_offsets(HashMap::from([(selected.clone(), 5i64), (other, -1i64)]));
4745
4746        let specs = HashMap::from([(
4747            "group".to_string(),
4748            ListConsumerGroupOffsetsSpec::new().set_topic_partitions(Some(vec![selected.clone()])),
4749        )]);
4750        let offsets = mock
4751            .list_consumer_group_offsets_with_group_specs_options(&specs, ListConsumerGroupOffsetsOptions::new())
4752            .partitions_to_offset_and_metadata()
4753            .expect("exactly one group was requested")
4754            .get()
4755            .await
4756            .expect("the unselected negative offset is filtered out before the constructor");
4757        assert_eq!(offsets.len(), 1);
4758        assert_eq!(offsets[&selected].as_ref().map(OffsetAndMetadata::offset), Some(5));
4759    }
4760}