Skip to main content

krabka_client_admin/
quotas.rs

1//! Client-quota admin RPCs (KIP-546): `DescribeClientQuotas` (`api_key` 48)
2//! and `AlterClientQuotas` (`api_key` 49), as Kafka's
3//! `Admin.describeClientQuotas` and `alterClientQuotas`.
4//!
5//! An entity is a map from entity type to entity name. Kafka's brokers accept
6//! the types [`ENTITY_USER`], [`ENTITY_CLIENT_ID`] and [`ENTITY_IP`], alone or
7//! as the pair `(user, client-id)`. A `None` name is the default entity of its
8//! type. As in Kafka's client, the broker validates the combination.
9//!
10//! The `KafkaUser` reconciler uses the per-user shortcuts
11//! [`AdminClient::describe_user_quotas`] and
12//! [`AdminClient::alter_user_quotas`].
13
14use std::collections::BTreeMap;
15
16use krabka_protocol::owned::{
17    alter_client_quotas_request::{
18        AlterClientQuotasRequest, EntityData as AlterEntity, EntryData as AlterEntry,
19        OpData as AlterOp,
20    },
21    alter_client_quotas_response::AlterClientQuotasResponse,
22    describe_client_quotas_request::{ComponentData, DescribeClientQuotasRequest},
23    describe_client_quotas_response::DescribeClientQuotasResponse,
24};
25
26use crate::{
27    AdminClient, AdminError, KafkaError, kafka_error_if, kafka_error_name, retry::ControllerRetry,
28};
29
30/// The entity type of a user principal, Kafka's `ClientQuotaEntity.USER`.
31pub const ENTITY_USER: &str = "user";
32/// The entity type of a client ID, Kafka's `ClientQuotaEntity.CLIENT_ID`.
33pub const ENTITY_CLIENT_ID: &str = "client-id";
34/// The entity type of a client IP address, Kafka's `ClientQuotaEntity.IP`.
35pub const ENTITY_IP: &str = "ip";
36
37/// Wire `match_type` constants of `DescribeClientQuotasRequest.json`.
38const MATCH_TYPE_EXACT: i8 = 0;
39const MATCH_TYPE_DEFAULT: i8 = 1;
40const MATCH_TYPE_SPECIFIED: i8 = 2;
41
42/// `UNKNOWN_SERVER_ERROR`.
43const UNKNOWN_SERVER_ERROR: i16 = -1;
44
45/// One mutation of a quota entity, as Kafka's `ClientQuotaAlteration.Op`.
46#[derive(Debug, Clone, PartialEq)]
47pub enum QuotaOp {
48    /// Upsert `key` → `value`. `value` must be finite and non-negative;
49    /// for `request_percentage` the broker also requires `value <= 100`.
50    Set { key: String, value: f64 },
51    /// Tombstone `key` for this entity. Kafka sends it for an `Op` with a
52    /// null value, as `remove=true`.
53    Remove { key: String },
54}
55
56/// Snapshot of the broker's quota state for a single user. An empty map means
57/// no per-user quotas are configured.
58pub type UserQuotaConfig = BTreeMap<String, f64>;
59
60/// A quota entity, as Kafka's `ClientQuotaEntity`: entity type → entity
61/// name, where `None` is the default entity of that type.
62pub type ClientQuotaEntity = BTreeMap<String, Option<String>>;
63
64/// The quota values of each entity, as Kafka's `DescribeClientQuotasResult`.
65pub type ClientQuotas = BTreeMap<ClientQuotaEntity, BTreeMap<String, f64>>;
66
67/// What one filter component matches, as the three constructors of Kafka's
68/// `ClientQuotaFilterComponent`.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum ClientQuotaMatch {
71    /// The entity with this name (`ofEntity`).
72    Exact(String),
73    /// The default entity of the type (`ofDefaultEntity`).
74    Default,
75    /// Any entity of the type, default or not (`ofEntityType`).
76    Specified,
77}
78
79/// One component of a [`ClientQuotaFilter`], as Kafka's
80/// `ClientQuotaFilterComponent`.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct ClientQuotaFilterComponent {
83    /// The entity type, such as [`ENTITY_USER`].
84    pub entity_type: String,
85    /// Which entities of that type match.
86    pub matches: ClientQuotaMatch,
87}
88
89impl ClientQuotaFilterComponent {
90    /// The entity of `entity_type` named `name`.
91    #[must_use]
92    pub fn of_entity(entity_type: impl Into<String>, name: impl Into<String>) -> Self {
93        Self {
94            entity_type: entity_type.into(),
95            matches: ClientQuotaMatch::Exact(name.into()),
96        }
97    }
98
99    /// The default entity of `entity_type`.
100    #[must_use]
101    pub fn of_default_entity(entity_type: impl Into<String>) -> Self {
102        Self {
103            entity_type: entity_type.into(),
104            matches: ClientQuotaMatch::Default,
105        }
106    }
107
108    /// Any entity of `entity_type`.
109    #[must_use]
110    pub fn of_entity_type(entity_type: impl Into<String>) -> Self {
111        Self {
112            entity_type: entity_type.into(),
113            matches: ClientQuotaMatch::Specified,
114        }
115    }
116}
117
118/// Which entities a describe returns, as Kafka's `ClientQuotaFilter`.
119#[derive(Debug, Clone, Default, PartialEq, Eq, bon::Builder)]
120pub struct ClientQuotaFilter {
121    /// Each component that a matched entity must satisfy.
122    #[builder(default)]
123    pub components: Vec<ClientQuotaFilterComponent>,
124    /// Whether a matched entity may have only the component types
125    /// (`containsOnly`), not others as well (`contains`).
126    #[builder(default)]
127    pub strict: bool,
128}
129
130impl ClientQuotaFilter {
131    /// The entities that satisfy every component and may have other entity
132    /// types as well (`ClientQuotaFilter.contains`).
133    #[must_use]
134    pub const fn contains(components: Vec<ClientQuotaFilterComponent>) -> Self {
135        Self {
136            components,
137            strict: false,
138        }
139    }
140
141    /// The entities that satisfy every component and have no other entity
142    /// type (`ClientQuotaFilter.containsOnly`).
143    #[must_use]
144    pub const fn contains_only(components: Vec<ClientQuotaFilterComponent>) -> Self {
145        Self {
146            components,
147            strict: true,
148        }
149    }
150
151    /// Every entity (`ClientQuotaFilter.all`).
152    #[must_use]
153    pub const fn all() -> Self {
154        Self::contains(Vec::new())
155    }
156}
157
158/// The mutations of one entity, as Kafka's `ClientQuotaAlteration`.
159#[derive(Debug, Clone, PartialEq)]
160pub struct ClientQuotaAlteration {
161    /// The entity to change.
162    pub entity: ClientQuotaEntity,
163    /// The changes of its quota values.
164    pub ops: Vec<QuotaOp>,
165}
166
167/// The `DescribeClientQuotas` request of `filter`, as Kafka's
168/// `DescribeClientQuotasRequest.Builder` builds it.
169fn describe_request(filter: &ClientQuotaFilter) -> DescribeClientQuotasRequest {
170    DescribeClientQuotasRequest {
171        components: filter
172            .components
173            .iter()
174            .map(|component| {
175                let (match_type, match_) = match &component.matches {
176                    ClientQuotaMatch::Exact(name) => (MATCH_TYPE_EXACT, Some(name.clone())),
177                    ClientQuotaMatch::Default => (MATCH_TYPE_DEFAULT, None),
178                    ClientQuotaMatch::Specified => (MATCH_TYPE_SPECIFIED, None),
179                };
180                ComponentData {
181                    entity_type: component.entity_type.clone(),
182                    match_type,
183                    match_,
184                    ..Default::default()
185                }
186            })
187            .collect(),
188        strict: filter.strict,
189        ..Default::default()
190    }
191}
192
193/// The quotas of a `DescribeClientQuotas` answer, as Kafka's
194/// `DescribeClientQuotasResponse.complete` reads it. A top-level error fails
195/// the call.
196fn describe_result(response: DescribeClientQuotasResponse) -> Result<ClientQuotas, AdminError> {
197    if response.error_code != 0 {
198        return Err(AdminError::Broker {
199            api: "DescribeClientQuotas",
200            code: response.error_code,
201            name: kafka_error_name(response.error_code),
202            message: response.error_message,
203        });
204    }
205    Ok(response
206        .entries
207        .unwrap_or_default()
208        .into_iter()
209        .map(|entry| {
210            let entity = entry
211                .entity
212                .into_iter()
213                .map(|entity| (entity.entity_type, entity.entity_name))
214                .collect();
215            let values = entry
216                .values
217                .into_iter()
218                .map(|value| (value.key, value.value))
219                .collect();
220            (entity, values)
221        })
222        .collect())
223}
224
225/// The `AlterClientQuotas` request of `alterations`, as Kafka's
226/// `AlterClientQuotasRequest.Builder` builds it.
227fn alter_request(
228    alterations: &[ClientQuotaAlteration],
229    validate_only: bool,
230) -> AlterClientQuotasRequest {
231    AlterClientQuotasRequest {
232        entries: alterations
233            .iter()
234            .map(|alteration| AlterEntry {
235                entity: alteration
236                    .entity
237                    .iter()
238                    .map(|(entity_type, entity_name)| AlterEntity {
239                        entity_type: entity_type.clone(),
240                        entity_name: entity_name.clone(),
241                        ..Default::default()
242                    })
243                    .collect(),
244                ops: alteration.ops.iter().map(op_to_wire).collect(),
245                ..Default::default()
246            })
247            .collect(),
248        validate_only,
249        ..Default::default()
250    }
251}
252
253/// The result of each entity of `alterations`, as Kafka's
254/// `AlterClientQuotasResponse.complete` gives it. An entity that the answer
255/// does not name gets `UNKNOWN_SERVER_ERROR`, and an entity that nobody asked
256/// for is skipped.
257fn alter_results(
258    alterations: &[ClientQuotaAlteration],
259    response: AlterClientQuotasResponse,
260) -> BTreeMap<ClientQuotaEntity, Result<(), KafkaError>> {
261    let mut out = BTreeMap::new();
262    for entry in response.entries {
263        let entity: ClientQuotaEntity = entry
264            .entity
265            .into_iter()
266            .map(|entity| (entity.entity_type, entity.entity_name))
267            .collect();
268        if !alterations
269            .iter()
270            .any(|alteration| alteration.entity == entity)
271        {
272            tracing::warn!(
273                ?entity,
274                "the AlterClientQuotas response names an entity that is not in the request"
275            );
276            continue;
277        }
278        let result = kafka_error_if(entry.error_code, entry.error_message).map_or(Ok(()), Err);
279        out.insert(entity, result);
280    }
281    for alteration in alterations {
282        out.entry(alteration.entity.clone()).or_insert_with(|| {
283            Err(KafkaError {
284                code: UNKNOWN_SERVER_ERROR,
285                name: kafka_error_name(UNKNOWN_SERVER_ERROR),
286                message: Some(format!(
287                    "the AlterClientQuotas response did not contain a result for entity {:?}",
288                    alteration.entity
289                )),
290            })
291        });
292    }
293    out
294}
295
296/// The single-user entity `{user: name}`.
297fn user_entity(username: &str) -> ClientQuotaEntity {
298    maplit::btreemap! {
299        ENTITY_USER.to_owned() => Some(username.to_owned()),
300    }
301}
302
303impl AdminClient {
304    /// Describes the quotas of every entity that `filter` matches, as
305    /// Kafka's `describeClientQuotas` operation does.
306    ///
307    /// The client sends one `DescribeClientQuotas` request on its connection
308    /// and stops at `default.api.timeout.ms` (60 s).
309    ///
310    /// # Errors
311    /// Returns [`AdminError::Broker`] for a top-level error, such as
312    /// `CLUSTER_AUTHORIZATION_FAILED` (31) or `INVALID_REQUEST` (42) for a
313    /// filter the broker refuses, and with `REQUEST_TIMED_OUT` (7) at the
314    /// deadline, or a transport error.
315    pub async fn describe_client_quotas(
316        &self,
317        filter: &ClientQuotaFilter,
318    ) -> Result<ClientQuotas, AdminError> {
319        let retry = ControllerRetry::new("DescribeClientQuotas", self.retry);
320        let response = retry
321            .bounded(self.conn.send(describe_request(filter)))
322            .await?;
323        describe_result(response)
324    }
325
326    /// Changes the quotas of each entity of `alterations`, as Kafka's
327    /// `alterClientQuotas` operation does. With `validate_only` the broker
328    /// validates the changes and applies none.
329    ///
330    /// The result has one entry for each entity: `Ok(())`, or the error the
331    /// broker gave for it, such as `INVALID_REQUEST` (42) for an entity type
332    /// combination it does not accept.
333    ///
334    /// # Errors
335    /// Returns a transport error, and [`AdminError::Broker`] with
336    /// `REQUEST_TIMED_OUT` (7) at `default.api.timeout.ms` (60 s).
337    pub async fn alter_client_quotas(
338        &self,
339        alterations: &[ClientQuotaAlteration],
340        validate_only: bool,
341    ) -> Result<BTreeMap<ClientQuotaEntity, Result<(), KafkaError>>, AdminError> {
342        let retry = ControllerRetry::new("AlterClientQuotas", self.retry);
343        let response = retry
344            .bounded(self.conn.send(alter_request(alterations, validate_only)))
345            .await?;
346        Ok(alter_results(alterations, response))
347    }
348
349    /// Reads the quotas of the user entity `{user: username}`.
350    ///
351    /// The filter is strict on the single component `("user", username)`, as
352    /// `ClientQuotaFilter.containsOnly`: an entry whose entity also has a
353    /// `client-id` does not match.
354    ///
355    /// # Errors
356    /// See [`Self::describe_client_quotas`].
357    pub async fn describe_user_quotas(
358        &mut self,
359        username: &str,
360    ) -> Result<UserQuotaConfig, AdminError> {
361        let filter = ClientQuotaFilter::contains_only(vec![ClientQuotaFilterComponent::of_entity(
362            ENTITY_USER,
363            username,
364        )]);
365        Ok(self
366            .describe_client_quotas(&filter)
367            .await?
368            .into_values()
369            .flatten()
370            .collect())
371    }
372
373    /// Applies `ops` to the user entity `{user: username}`. Returns the
374    /// error the broker gave for the entity, or `None` on success. No
375    /// request is sent for an empty `ops`.
376    ///
377    /// # Errors
378    /// See [`Self::alter_client_quotas`].
379    pub async fn alter_user_quotas(
380        &mut self,
381        username: &str,
382        ops: &[QuotaOp],
383        validate_only: bool,
384    ) -> Result<Option<KafkaError>, AdminError> {
385        if ops.is_empty() {
386            return Ok(None);
387        }
388        let alteration = ClientQuotaAlteration {
389            entity: user_entity(username),
390            ops: ops.to_vec(),
391        };
392        Ok(self
393            .alter_client_quotas(std::slice::from_ref(&alteration), validate_only)
394            .await?
395            .into_values()
396            .next()
397            .and_then(Result::err))
398    }
399}
400
401fn op_to_wire(op: &QuotaOp) -> AlterOp {
402    match op {
403        QuotaOp::Set { key, value } => AlterOp {
404            key: key.clone(),
405            value: *value,
406            ..Default::default()
407        },
408        QuotaOp::Remove { key } => AlterOp {
409            key: key.clone(),
410            remove: true,
411            ..Default::default()
412        },
413    }
414}
415
416/// Pure function. It diffs the desired key-set against the current key-set and
417/// produces the minimal `(set, remove)` op stream. Floats compare bit-equal,
418/// so it does not re-issue a no-op `Set` with the same value.
419#[must_use]
420pub fn diff_user_quotas(current: &UserQuotaConfig, desired: &UserQuotaConfig) -> Vec<QuotaOp> {
421    let mut ops = Vec::new();
422    for (k, v) in desired {
423        match current.get(k) {
424            Some(cur) if cur.to_bits() == v.to_bits() => {}
425            _ => ops.push(QuotaOp::Set {
426                key: k.clone(),
427                value: *v,
428            }),
429        }
430    }
431    for k in current.keys() {
432        if !desired.contains_key(k) {
433            ops.push(QuotaOp::Remove { key: k.clone() });
434        }
435    }
436    ops
437}
438
439#[cfg(test)]
440mod tests {
441    use std::sync::{Arc, Mutex};
442
443    use bytes::{Buf, BytesMut};
444    use krabka_client_core::MockBroker;
445    use krabka_protocol::{
446        Decode, Encode, UnknownTaggedFields,
447        owned::{
448            alter_client_quotas_request,
449            alter_client_quotas_response::{AlterClientQuotasResponse, EntityData, EntryData},
450            api_versions_request,
451            api_versions_response::{ApiVersion, ApiVersionsResponse},
452            describe_client_quotas_request,
453            describe_client_quotas_response::{
454                DescribeClientQuotasResponse, EntityData as DescribeEntityData,
455                EntryData as DescribeEntryData, ValueData as DescribeValueData,
456            },
457        },
458    };
459
460    use super::*;
461
462    fn encode_v0(resp: &impl Encode) -> Vec<u8> {
463        let mut buf = BytesMut::new();
464        resp.encode(&mut buf, 0).unwrap();
465        buf.to_vec()
466    }
467
468    fn api_versions_response(api_key: i16, version: i16) -> Vec<u8> {
469        encode_v0(&ApiVersionsResponse {
470            api_keys: vec![
471                ApiVersion {
472                    api_key: api_versions_request::API_KEY,
473                    min_version: 0,
474                    max_version: 0,
475                    ..Default::default()
476                },
477                ApiVersion {
478                    api_key,
479                    min_version: version,
480                    max_version: version,
481                    ..Default::default()
482                },
483            ],
484            ..Default::default()
485        })
486    }
487
488    fn request_body_after_header(mut body: &[u8], flexible_header: bool) -> &[u8] {
489        let client_id_len = body.get_i16();
490        assert2::assert!(client_id_len >= 0);
491        body.advance(usize::try_from(client_id_len).expect("client id length is non-negative"));
492        if flexible_header {
493            assert2::assert!(body.get_u8() == 0);
494        }
495        body
496    }
497
498    #[test]
499    fn diff_no_change_returns_empty() {
500        let mut c = UserQuotaConfig::new();
501        c.insert("producer_byte_rate".into(), 1_048_576.0);
502        let d = c.clone();
503        assert2::assert!(diff_user_quotas(&c, &d).is_empty());
504    }
505
506    #[test]
507    fn diff_set_added_keys() {
508        let c = UserQuotaConfig::new();
509        let mut d = UserQuotaConfig::new();
510        d.insert("producer_byte_rate".into(), 1_048_576.0);
511        d.insert("request_percentage".into(), 25.0);
512        let ops = diff_user_quotas(&c, &d);
513        // `desired` is a BTreeMap, so `Set` ops come out in key order.
514        assert2::assert!(
515            ops == vec![
516                QuotaOp::Set {
517                    key: "producer_byte_rate".to_string(),
518                    value: 1_048_576.0,
519                },
520                QuotaOp::Set {
521                    key: "request_percentage".to_string(),
522                    value: 25.0,
523                },
524            ]
525        );
526    }
527
528    #[test]
529    fn diff_remove_dropped_keys() {
530        let mut c = UserQuotaConfig::new();
531        c.insert("producer_byte_rate".into(), 1.0);
532        c.insert("consumer_byte_rate".into(), 2.0);
533        let mut d = UserQuotaConfig::new();
534        d.insert("producer_byte_rate".into(), 1.0);
535        let ops = diff_user_quotas(&c, &d);
536        assert2::assert!(
537            ops == vec![QuotaOp::Remove {
538                key: "consumer_byte_rate".into()
539            }]
540        );
541    }
542
543    #[test]
544    fn diff_value_change_is_a_set() {
545        let mut c = UserQuotaConfig::new();
546        c.insert("producer_byte_rate".into(), 1.0);
547        let mut d = UserQuotaConfig::new();
548        d.insert("producer_byte_rate".into(), 2.0);
549        let ops = diff_user_quotas(&c, &d);
550        assert2::assert!(
551            ops == vec![QuotaOp::Set {
552                key: "producer_byte_rate".into(),
553                value: 2.0,
554            }]
555        );
556    }
557
558    #[test]
559    fn diff_mixed_add_change_remove() {
560        let mut c = UserQuotaConfig::new();
561        c.insert("producer_byte_rate".into(), 1.0);
562        c.insert("consumer_byte_rate".into(), 2.0);
563        let mut d = UserQuotaConfig::new();
564        d.insert("producer_byte_rate".into(), 5.0); // change
565        d.insert("request_percentage".into(), 25.0); // add
566        // consumer_byte_rate dropped
567        let ops = diff_user_quotas(&c, &d);
568        // Sets come first (in `desired` key order), then removes (in
569        // `current` key order) — both maps are BTreeMaps.
570        assert2::assert!(
571            ops == vec![
572                QuotaOp::Set {
573                    key: "producer_byte_rate".to_string(),
574                    value: 5.0,
575                },
576                QuotaOp::Set {
577                    key: "request_percentage".to_string(),
578                    value: 25.0,
579                },
580                QuotaOp::Remove {
581                    key: "consumer_byte_rate".to_string(),
582                },
583            ]
584        );
585    }
586
587    #[test]
588    fn op_to_wire_set() {
589        let op = QuotaOp::Set {
590            key: "producer_byte_rate".into(),
591            value: 1.0,
592        };
593        let w = op_to_wire(&op);
594        assert2::assert!(
595            w == AlterOp {
596                key: "producer_byte_rate".to_string(),
597                value: 1.0,
598                remove: false,
599                unknown_tagged_fields: UnknownTaggedFields(vec![]),
600            }
601        );
602    }
603
604    #[test]
605    fn op_to_wire_remove_sends_zero_value_and_flag() {
606        let op = QuotaOp::Remove {
607            key: "producer_byte_rate".into(),
608        };
609        let w = op_to_wire(&op);
610        assert2::assert!(
611            w == AlterOp {
612                key: "producer_byte_rate".to_string(),
613                value: 0.0,
614                remove: true,
615                unknown_tagged_fields: UnknownTaggedFields(vec![]),
616            }
617        );
618    }
619
620    fn entity(parts: &[(&str, Option<&str>)]) -> ClientQuotaEntity {
621        parts
622            .iter()
623            .map(|(entity_type, name)| ((*entity_type).to_owned(), name.map(str::to_owned)))
624            .collect()
625    }
626
627    fn component(entity_type: &str, match_type: i8, match_: Option<&str>) -> ComponentData {
628        ComponentData {
629            entity_type: entity_type.to_owned(),
630            match_type,
631            match_: match_.map(str::to_owned),
632            ..Default::default()
633        }
634    }
635
636    /// Kafka's `DescribeClientQuotasRequest.Builder` maps `ofEntity`,
637    /// `ofDefaultEntity` and `ofEntityType` to match types 0, 1 and 2, and
638    /// `containsOnly` to `strict`.
639    #[test]
640    fn describe_request_maps_each_filter_component() {
641        for (name, filter, expected) in [
642            (
643                "all entities",
644                ClientQuotaFilter::all(),
645                DescribeClientQuotasRequest::default(),
646            ),
647            (
648                "one user and any client id",
649                ClientQuotaFilter::contains_only(vec![
650                    ClientQuotaFilterComponent::of_entity(ENTITY_USER, "alice"),
651                    ClientQuotaFilterComponent::of_entity_type(ENTITY_CLIENT_ID),
652                ]),
653                DescribeClientQuotasRequest {
654                    components: vec![
655                        component("user", 0, Some("alice")),
656                        component("client-id", 2, None),
657                    ],
658                    strict: true,
659                    ..Default::default()
660                },
661            ),
662            (
663                "the default ip",
664                ClientQuotaFilter::contains(vec![ClientQuotaFilterComponent::of_default_entity(
665                    ENTITY_IP,
666                )]),
667                DescribeClientQuotasRequest {
668                    components: vec![component("ip", 1, None)],
669                    strict: false,
670                    ..Default::default()
671                },
672            ),
673        ] {
674            assert2::assert!(describe_request(&filter) == expected, "case {name}");
675        }
676    }
677
678    /// Kafka's `AlterClientQuotasRequest.Builder` sends each entity with its
679    /// entity types and ops, a default entity as a null name, and a removed
680    /// key as `remove=true`.
681    #[test]
682    fn alter_request_carries_each_entity_type() {
683        let alterations = [
684            ClientQuotaAlteration {
685                entity: entity(&[("user", Some("alice")), ("client-id", None)]),
686                ops: vec![QuotaOp::Set {
687                    key: "producer_byte_rate".to_owned(),
688                    value: 1024.0,
689                }],
690            },
691            ClientQuotaAlteration {
692                entity: entity(&[("ip", Some("10.0.0.1"))]),
693                ops: vec![QuotaOp::Remove {
694                    key: "connection_creation_rate".to_owned(),
695                }],
696            },
697        ];
698        let alter_entity = |entity_type: &str, name: Option<&str>| AlterEntity {
699            entity_type: entity_type.to_owned(),
700            entity_name: name.map(str::to_owned),
701            ..Default::default()
702        };
703        assert2::assert!(
704            alter_request(&alterations, true)
705                == AlterClientQuotasRequest {
706                    entries: vec![
707                        AlterEntry {
708                            entity: vec![
709                                alter_entity("client-id", None),
710                                alter_entity("user", Some("alice")),
711                            ],
712                            ops: vec![AlterOp {
713                                key: "producer_byte_rate".to_owned(),
714                                value: 1024.0,
715                                ..Default::default()
716                            }],
717                            ..Default::default()
718                        },
719                        AlterEntry {
720                            entity: vec![alter_entity("ip", Some("10.0.0.1"))],
721                            ops: vec![AlterOp {
722                                key: "connection_creation_rate".to_owned(),
723                                remove: true,
724                                ..Default::default()
725                            }],
726                            ..Default::default()
727                        },
728                    ],
729                    validate_only: true,
730                    ..Default::default()
731                }
732        );
733    }
734
735    /// Kafka's `describeClientQuotas` returns the values of each entity of
736    /// every type, retries a lost connection, and fails the call on a
737    /// top-level error.
738    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
739    async fn describe_client_quotas_maps_every_entity_type() {
740        use krabka_client_core::MockReply;
741
742        use crate::partition_leaders::test_support::{
743            ApiVersionRange, encode_response, scripted_broker,
744        };
745
746        let entries = vec![
747            DescribeEntryData {
748                entity: vec![
749                    DescribeEntityData {
750                        entity_type: "user".into(),
751                        entity_name: Some("alice".into()),
752                        ..Default::default()
753                    },
754                    DescribeEntityData {
755                        entity_type: "client-id".into(),
756                        entity_name: None,
757                        ..Default::default()
758                    },
759                ],
760                values: vec![DescribeValueData {
761                    key: "producer_byte_rate".into(),
762                    value: 1024.0,
763                    ..Default::default()
764                }],
765                ..Default::default()
766            },
767            DescribeEntryData {
768                entity: vec![DescribeEntityData {
769                    entity_type: "ip".into(),
770                    entity_name: Some("10.0.0.1".into()),
771                    ..Default::default()
772                }],
773                values: vec![DescribeValueData {
774                    key: "connection_creation_rate".into(),
775                    value: 5.0,
776                    ..Default::default()
777                }],
778                ..Default::default()
779            },
780        ];
781        let quotas = ClientQuotas::from([
782            (
783                entity(&[("user", Some("alice")), ("client-id", None)]),
784                maplit::btreemap! {
785                    "producer_byte_rate".to_owned() => 1024.0,
786                },
787            ),
788            (
789                entity(&[("ip", Some("10.0.0.1"))]),
790                maplit::btreemap! {
791                    "connection_creation_rate".to_owned() => 5.0,
792                },
793            ),
794        ]);
795        for (name, close_first, error_code, expected) in [
796            ("success", false, 0, (Ok(quotas.clone()), 1)),
797            (
798                "a lost connection is retried",
799                true,
800                0,
801                (Ok(quotas.clone()), 2),
802            ),
803            (
804                "a top-level error fails the call",
805                false,
806                31,
807                (Err(("DescribeClientQuotas", 31)), 1),
808            ),
809        ] {
810            let requests = Arc::new(Mutex::new(0_usize));
811            let handler_requests = Arc::clone(&requests);
812            let entries = entries.clone();
813            let broker = scripted_broker(
814                vec![
815                    ApiVersionRange::builder()
816                        .api_key(describe_client_quotas_request::API_KEY)
817                        .max_version(1)
818                        .build(),
819                ],
820                move |api_key, version, _, _| {
821                    if api_key != describe_client_quotas_request::API_KEY {
822                        return MockReply::Silent;
823                    }
824                    let mut requests = handler_requests.lock().expect("requests lock");
825                    *requests += 1;
826                    if close_first && *requests == 1 {
827                        return MockReply::Close;
828                    }
829                    MockReply::Respond(encode_response(
830                        &DescribeClientQuotasResponse {
831                            error_code,
832                            entries: (error_code == 0).then(|| entries.clone()),
833                            ..Default::default()
834                        },
835                        version,
836                        true,
837                    ))
838                },
839            )
840            .await;
841            let admin = AdminClient::connect(&[broker.addr.to_string()])
842                .await
843                .expect("admin connects");
844
845            let result = admin
846                .describe_client_quotas(&ClientQuotaFilter::all())
847                .await
848                .map_err(|error| match error {
849                    AdminError::Broker { api, code, .. } => (api, code),
850                    other => panic!("case {name}: unexpected error {other:?}"),
851                });
852
853            broker.stop();
854            assert2::assert!(
855                (result, *requests.lock().expect("requests lock")) == expected,
856                "case {name}"
857            );
858        }
859    }
860
861    /// Kafka's `AlterClientQuotasResponse.complete` gives each entity its own
862    /// result. An entity the answer leaves out gets `UNKNOWN_SERVER_ERROR`.
863    #[test]
864    fn alter_results_give_each_entity_its_result() {
865        let alice = entity(&[("user", Some("alice")), ("client-id", Some("app"))]);
866        let ip = entity(&[("ip", None)]);
867        let alterations = [
868            ClientQuotaAlteration {
869                entity: alice.clone(),
870                ops: Vec::new(),
871            },
872            ClientQuotaAlteration {
873                entity: ip.clone(),
874                ops: Vec::new(),
875            },
876        ];
877        let answer = |entity_type: &str, entity_name: Option<&str>, error_code| EntryData {
878            error_code,
879            error_message: (error_code != 0).then(|| "bad".to_owned()),
880            entity: vec![EntityData {
881                entity_type: entity_type.to_owned(),
882                entity_name: entity_name.map(str::to_owned),
883                ..Default::default()
884            }],
885            ..Default::default()
886        };
887        let mut alice_answer = answer("user", Some("alice"), 0);
888        alice_answer.entity.push(EntityData {
889            entity_type: "client-id".to_owned(),
890            entity_name: Some("app".to_owned()),
891            ..Default::default()
892        });
893        let unknown = Err(KafkaError {
894            code: -1,
895            name: "UNKNOWN_SERVER_ERROR",
896            message: Some(format!(
897                "the AlterClientQuotas response did not contain a result for entity {ip:?}"
898            )),
899        });
900        for (name, entries, expected) in [
901            (
902                "each entity has its result",
903                vec![alice_answer.clone(), answer("ip", None, 42)],
904                maplit::btreemap! {
905                    alice.clone() => Ok(()),
906                    ip.clone() => Err(KafkaError {
907                    code: 42,
908                    name: "INVALID_REQUEST",
909                    message: Some("bad".to_owned()),
910                }),
911                },
912            ),
913            (
914                "a missing entity and an unasked entity",
915                vec![alice_answer.clone(), answer("user", Some("bob"), 0)],
916                maplit::btreemap! {
917                    alice.clone() => Ok(()),
918                    ip.clone() => unknown,
919                },
920            ),
921        ] {
922            let response = AlterClientQuotasResponse {
923                entries,
924                ..Default::default()
925            };
926            assert2::assert!(
927                alter_results(&alterations, response) == expected,
928                "case {name}"
929            );
930        }
931    }
932
933    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
934    async fn describe_user_quotas_sends_strict_user_component() {
935        let seen_request = Arc::new(Mutex::new(None));
936        let captured_request = Arc::clone(&seen_request);
937        let mock = MockBroker::start(move |api_key, version, _corr_id, body| {
938            if api_key == api_versions_request::API_KEY {
939                return Some(api_versions_response(
940                    describe_client_quotas_request::API_KEY,
941                    0,
942                ));
943            }
944            if api_key == describe_client_quotas_request::API_KEY {
945                let mut body = request_body_after_header(
946                    body,
947                    version >= describe_client_quotas_request::FLEXIBLE_MIN,
948                );
949                let request = DescribeClientQuotasRequest::decode(&mut body, version)
950                    .expect("describe quotas request decodes");
951                assert2::assert!(body.is_empty());
952                *captured_request.lock().expect("request capture lock") = Some(request);
953                return Some(encode_v0(&DescribeClientQuotasResponse {
954                    entries: Some(vec![DescribeEntryData {
955                        entity: vec![DescribeEntityData {
956                            entity_type: "user".into(),
957                            entity_name: Some("alice".into()),
958                            ..Default::default()
959                        }],
960                        values: vec![DescribeValueData {
961                            key: "producer_byte_rate".into(),
962                            value: 1024.0,
963                            ..Default::default()
964                        }],
965                        ..Default::default()
966                    }]),
967                    ..Default::default()
968                }));
969            }
970            None
971        })
972        .await;
973        let mut admin = AdminClient::connect(&[mock.addr.to_string()])
974            .await
975            .expect("admin connects to mock broker");
976
977        let quotas = admin
978            .describe_user_quotas("alice")
979            .await
980            .expect("describe quotas response maps");
981
982        assert2::assert!(quotas.get("producer_byte_rate") == Some(&1024.0));
983        let request = seen_request
984            .lock()
985            .expect("request capture lock")
986            .take()
987            .expect("describe quotas request was captured");
988        assert2::assert!(
989            request
990                == DescribeClientQuotasRequest {
991                    components: vec![ComponentData {
992                        entity_type: "user".into(),
993                        match_type: MATCH_TYPE_EXACT,
994                        match_: Some("alice".into()),
995                        ..Default::default()
996                    }],
997                    strict: true,
998                    ..Default::default()
999                }
1000        );
1001        mock.stop();
1002    }
1003
1004    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1005    async fn alter_user_quotas_surfaces_broker_entry_error() {
1006        let seen_request = Arc::new(Mutex::new(None));
1007        let captured_request = Arc::clone(&seen_request);
1008        let mock = MockBroker::start(move |api_key, version, _corr_id, body| {
1009            if api_key == api_versions_request::API_KEY {
1010                return Some(api_versions_response(
1011                    alter_client_quotas_request::API_KEY,
1012                    0,
1013                ));
1014            }
1015            if api_key == alter_client_quotas_request::API_KEY {
1016                let mut body = request_body_after_header(
1017                    body,
1018                    version >= alter_client_quotas_request::FLEXIBLE_MIN,
1019                );
1020                let request = AlterClientQuotasRequest::decode(&mut body, version)
1021                    .expect("alter quotas request decodes");
1022                assert2::assert!(body.is_empty());
1023                *captured_request.lock().expect("request capture lock") = Some(request);
1024                return Some(encode_v0(&AlterClientQuotasResponse {
1025                    entries: vec![EntryData {
1026                        error_code: 40,
1027                        error_message: Some("invalid quota".into()),
1028                        entity: vec![EntityData {
1029                            entity_type: "user".into(),
1030                            entity_name: Some("alice".into()),
1031                            ..Default::default()
1032                        }],
1033                        ..Default::default()
1034                    }],
1035                    ..Default::default()
1036                }));
1037            }
1038            None
1039        })
1040        .await;
1041        let mut admin = AdminClient::connect(&[mock.addr.to_string()])
1042            .await
1043            .expect("admin connects to mock broker");
1044
1045        let error = admin
1046            .alter_user_quotas(
1047                "alice",
1048                &[
1049                    QuotaOp::Set {
1050                        key: "producer_byte_rate".into(),
1051                        value: 1024.0,
1052                    },
1053                    QuotaOp::Remove {
1054                        key: "consumer_byte_rate".into(),
1055                    },
1056                ],
1057                true,
1058            )
1059            .await
1060            .expect("alter quotas maps broker entry")
1061            .expect("non-zero broker error is returned");
1062
1063        assert2::assert!((error.code, error.message.as_deref()) == (40, Some("invalid quota")));
1064        let request = seen_request
1065            .lock()
1066            .expect("request capture lock")
1067            .take()
1068            .expect("alter quotas request was captured");
1069        assert2::assert!(
1070            request
1071                == AlterClientQuotasRequest {
1072                    entries: vec![AlterEntry {
1073                        entity: vec![AlterEntity {
1074                            entity_type: "user".into(),
1075                            entity_name: Some("alice".into()),
1076                            ..Default::default()
1077                        }],
1078                        ops: vec![
1079                            AlterOp {
1080                                key: "producer_byte_rate".into(),
1081                                value: 1024.0,
1082                                ..Default::default()
1083                            },
1084                            AlterOp {
1085                                key: "consumer_byte_rate".into(),
1086                                remove: true,
1087                                ..Default::default()
1088                            },
1089                        ],
1090                        ..Default::default()
1091                    }],
1092                    validate_only: true,
1093                    ..Default::default()
1094                }
1095        );
1096        mock.stop();
1097    }
1098}