krabka-client-admin 0.7.0

Operator-side admin client for Krabka clusters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//! Admin client settings, as Kafka's `AdminClientConfig` defines them.

use std::sync::atomic::{AtomicU32, Ordering};

use krabka_client_core::{
    ClientDnsLookup, ClientDnsTimeout, ClientFrameMax, ConnectionDispatchQueueCapacity,
    ConnectionOptions, DEFAULT_METADATA_RECOVERY_REBOOTSTRAP_TRIGGER, MetadataRecoveryStrategy,
    security::ClientSecurity,
};
use krabka_units::{
    ByteSize, Time,
    convert::{ByteSizeExt as _, TimeExt as _},
    millis, secs,
};

use crate::{AdminError, retry::RetryPolicy};

/// Kafka's `request.timeout.ms` default for the admin client.
pub const DEFAULT_ADMIN_REQUEST_TIMEOUT: Time = secs(30);
/// Kafka's `default.api.timeout.ms` default.
pub const DEFAULT_API_TIMEOUT: Time = secs(60);
/// Kafka's `retry.backoff.ms` default.
pub const DEFAULT_RETRY_BACKOFF: Time = millis(100);
/// Kafka's `retry.backoff.max.ms` default.
pub const DEFAULT_RETRY_BACKOFF_MAX: Time = secs(1);
/// Kafka's `socket.connection.setup.timeout.ms` default.
pub const DEFAULT_SOCKET_CONNECTION_SETUP_TIMEOUT: Time = secs(10);
/// Kafka's `socket.connection.setup.timeout.max.ms` default.
pub const DEFAULT_SOCKET_CONNECTION_SETUP_TIMEOUT_MAX: Time = secs(30);
/// Kafka's admin client `connections.max.idle.ms` default (5 minutes).
pub const DEFAULT_ADMIN_CONNECTIONS_MAX_IDLE: Time = krabka_units::minutes(5);
/// Kafka's `enable.metrics.push` default.
pub const DEFAULT_ENABLE_METRICS_PUSH: bool = true;

/// `CommonClientConfigs.RETRY_BACKOFF_JITTER`.
const RETRY_BACKOFF_JITTER: f64 = 0.2;

/// The sequence of generated client ids, as Kafka's
/// `KafkaAdminClient.ADMIN_CLIENT_ID_SEQUENCE`. The first id is
/// `adminclient-1`.
static ADMIN_CLIENT_ID_SEQUENCE: AtomicU32 = AtomicU32::new(1);

/// The settings of an [`AdminClient`](crate::AdminClient).
///
/// `Default` gives Kafka's `AdminClientConfig` defaults. A setting that is
/// `None` is not set, which matters where Kafka checks whether the user set
/// a value (`client.id`, `default.api.timeout.ms`).
#[derive(Clone, Debug)]
pub struct AdminClientConfig {
    /// `client.id`. `None` or an empty id gives a new `adminclient-<n>` for
    /// each client, as `KafkaAdminClient.generateClientId` does.
    pub client_id: Option<String>,
    /// `request.timeout.ms`: the deadline of one request.
    pub request_timeout: Time,
    /// `default.api.timeout.ms`: the deadline of a call and its retries when
    /// the call sets no timeout. `None` uses 60 s, raised to
    /// [`Self::request_timeout`] when that is larger.
    pub default_api_timeout: Option<Time>,
    /// `retries`: the number of retries of a call before its deadline.
    /// Kafka's default is `Integer.MAX_VALUE`.
    pub retries: u32,
    /// `retry.backoff.ms`.
    pub retry_backoff: Time,
    /// `retry.backoff.max.ms`.
    pub retry_backoff_max: Time,
    /// `socket.connection.setup.timeout.ms`: the connection setup deadline
    /// of the first attempt.
    pub socket_connection_setup_timeout: Time,
    /// `socket.connection.setup.timeout.max.ms`: the setup deadline grows
    /// per failed attempt up to this value.
    pub socket_connection_setup_timeout_max: Time,
    /// `connections.max.idle.ms`: a connection with no traffic closes after
    /// this time.
    pub connections_max_idle: Time,
    /// The DNS lookup deadline of one broker address.
    pub dns_timeout: ClientDnsTimeout,
    /// Bootstrap DNS address selection policy.
    pub client_dns_lookup: ClientDnsLookup,
    /// Initial reconnect delay.
    pub reconnect_backoff: Time,
    /// Maximum reconnect delay.
    pub reconnect_backoff_max: Time,
    /// Outbound socket send buffer; None selects the OS default.
    pub send_buffer: Option<ByteSize>,
    /// Outbound socket receive buffer; None selects the OS default.
    pub receive_buffer: Option<ByteSize>,
    /// Capacity of every connection's dispatch queue.
    pub dispatch_queue_capacity: ConnectionDispatchQueueCapacity,
    /// Maximum accepted response frame size.
    pub frame_max: ClientFrameMax,
    /// `security.protocol` and its TLS and SASL settings. `None` is
    /// plaintext.
    pub security: Option<ClientSecurity>,
    /// `metadata.recovery.strategy` (KIP-1102).
    pub metadata_recovery_strategy: MetadataRecoveryStrategy,
    /// `metadata.recovery.rebootstrap.trigger.ms` (KIP-1102).
    pub metadata_recovery_rebootstrap_trigger: Time,
    /// `enable.metrics.push` (KIP-714, default `true`): push the client
    /// metrics that a broker's client metrics subscription names, with a
    /// terminating push on close. When it is `false`, the client sends
    /// neither `GetTelemetrySubscriptions` nor `PushTelemetry`, and
    /// `client_instance_id` fails.
    pub enable_metrics_push: bool,
}

impl Default for AdminClientConfig {
    fn default() -> Self {
        Self {
            client_id: None,
            request_timeout: DEFAULT_ADMIN_REQUEST_TIMEOUT,
            default_api_timeout: None,
            retries: u32::MAX,
            retry_backoff: DEFAULT_RETRY_BACKOFF,
            retry_backoff_max: DEFAULT_RETRY_BACKOFF_MAX,
            socket_connection_setup_timeout: DEFAULT_SOCKET_CONNECTION_SETUP_TIMEOUT,
            socket_connection_setup_timeout_max: DEFAULT_SOCKET_CONNECTION_SETUP_TIMEOUT_MAX,
            connections_max_idle: DEFAULT_ADMIN_CONNECTIONS_MAX_IDLE,
            dns_timeout: ClientDnsTimeout::default(),
            client_dns_lookup: ClientDnsLookup::default(),
            reconnect_backoff: krabka_client_core::DEFAULT_RECONNECT_BACKOFF,
            reconnect_backoff_max: krabka_client_core::DEFAULT_RECONNECT_BACKOFF_MAX,
            send_buffer: Some(krabka_client_core::DEFAULT_SEND_BUFFER),
            receive_buffer: Some(krabka_client_core::DEFAULT_RECEIVE_BUFFER),
            dispatch_queue_capacity: ConnectionDispatchQueueCapacity::default(),
            frame_max: ClientFrameMax::default(),
            security: None,
            metadata_recovery_strategy: MetadataRecoveryStrategy::default(),
            metadata_recovery_rebootstrap_trigger: DEFAULT_METADATA_RECOVERY_REBOOTSTRAP_TRIGGER,
            enable_metrics_push: DEFAULT_ENABLE_METRICS_PUSH,
        }
    }
}

/// The connection options and retry policy of one admin client.
#[derive(Clone, Debug)]
pub(crate) struct ResolvedAdminConfig {
    pub(crate) connection: ConnectionOptions,
    pub(crate) retry: RetryPolicy,
    pub(crate) metadata_recovery_strategy: MetadataRecoveryStrategy,
    pub(crate) metadata_recovery_rebootstrap_trigger: Time,
    pub(crate) enable_metrics_push: bool,
}

impl AdminClientConfig {
    fn validate_transport(&self) -> Result<(), AdminError> {
        for (name, value) in [
            ("reconnect_backoff", self.reconnect_backoff),
            ("reconnect_backoff_max", self.reconnect_backoff_max),
        ] {
            if !value.secs_f64().is_finite() || value < Time::ZERO {
                return Err(AdminError::InvalidConfig(format!(
                    "{name} must be finite and nonnegative"
                )));
            }
        }
        if self.reconnect_backoff_max < self.reconnect_backoff {
            return Err(AdminError::InvalidConfig(
                "reconnect_backoff_max is below reconnect_backoff".into(),
            ));
        }
        for (name, value) in [
            ("send_buffer", self.send_buffer),
            ("receive_buffer", self.receive_buffer),
        ] {
            if let Some(value) = value {
                let bytes = value.bytes_f64();
                if !bytes.is_finite()
                    || bytes < 1.0
                    || bytes.fract() != 0.0
                    || bytes > f64::from(i32::MAX)
                {
                    return Err(AdminError::InvalidConfig(format!(
                        "{name} must contain positive whole int32 bytes"
                    )));
                }
            }
        }
        Ok(())
    }

    /// Check the settings and derive the connection options and the call
    /// retry policy.
    ///
    /// # Errors
    /// Returns [`AdminError::InvalidConfig`] when a timeout or backoff is not
    /// positive, or when `default_api_timeout` is set below
    /// `request_timeout`, as Kafka's `configureDefaultApiTimeoutMs` throws a
    /// `ConfigException`.
    pub(crate) fn resolve(self) -> Result<ResolvedAdminConfig, AdminError> {
        for (name, value) in [
            ("request_timeout", self.request_timeout),
            (
                "socket_connection_setup_timeout",
                self.socket_connection_setup_timeout,
            ),
            (
                "socket_connection_setup_timeout_max",
                self.socket_connection_setup_timeout_max,
            ),
        ] {
            if !value.secs_f64().is_finite() || value <= Time::ZERO {
                return Err(AdminError::InvalidConfig(format!(
                    "{name} must be positive and finite"
                )));
            }
        }
        if let Some(value) = self.default_api_timeout
            && (!value.secs_f64().is_finite() || value <= Time::ZERO)
        {
            return Err(AdminError::InvalidConfig(
                "default_api_timeout must be positive and finite".to_owned(),
            ));
        }
        for (name, value) in [
            ("connections_max_idle", self.connections_max_idle),
            ("retry_backoff", self.retry_backoff),
            ("retry_backoff_max", self.retry_backoff_max),
        ] {
            if !value.secs_f64().is_finite() || value < Time::ZERO {
                return Err(AdminError::InvalidConfig(format!(
                    "{name} must be finite and not negative"
                )));
            }
        }
        self.validate_transport()?;
        if self.socket_connection_setup_timeout_max < self.socket_connection_setup_timeout
            || self.retry_backoff_max < self.retry_backoff
        {
            return Err(AdminError::InvalidConfig(
                "maximum delay is below initial delay".into(),
            ));
        }
        let api_timeout = default_api_timeout(self.request_timeout, self.default_api_timeout)?;
        let client_id = match self.client_id {
            Some(id) if !id.is_empty() => id,
            _ => generate_client_id(),
        };
        let connection = ConnectionOptions {
            client_id,
            dns_timeout: self.dns_timeout,
            client_dns_lookup: self.client_dns_lookup,
            reconnect_backoff: self.reconnect_backoff,
            reconnect_backoff_max: self.reconnect_backoff_max,
            send_buffer: self.send_buffer,
            receive_buffer: self.receive_buffer,
            dispatch_queue_capacity: self.dispatch_queue_capacity,
            frame_max: self.frame_max,
            socket_connection_setup_timeout: self.socket_connection_setup_timeout,
            socket_connection_setup_timeout_max: self.socket_connection_setup_timeout_max,
            connections_max_idle: self.connections_max_idle,
            request_timeout: self.request_timeout,
            security: self.security.map(Box::new),
            ..ConnectionOptions::default()
        };
        connection.validate().map_err(AdminError::InvalidConfig)?;
        Ok(ResolvedAdminConfig {
            connection,
            retry: RetryPolicy {
                timeout: api_timeout.to_std(),
                initial_backoff: self.retry_backoff.to_std(),
                max_backoff: self.retry_backoff_max.to_std(),
                jitter: RETRY_BACKOFF_JITTER,
                max_retries: self.retries,
            },
            metadata_recovery_strategy: self.metadata_recovery_strategy,
            metadata_recovery_rebootstrap_trigger: self.metadata_recovery_rebootstrap_trigger,
            enable_metrics_push: self.enable_metrics_push,
        })
    }
}

/// A new `adminclient-<n>` id.
fn generate_client_id() -> String {
    format!(
        "adminclient-{}",
        ADMIN_CLIENT_ID_SEQUENCE.fetch_add(1, Ordering::Relaxed)
    )
}

/// The call deadline, as Kafka's `configureDefaultApiTimeoutMs` gives it: an
/// explicit value below the request timeout is an error, and the default
/// rises to the request timeout.
fn default_api_timeout(request_timeout: Time, explicit: Option<Time>) -> Result<Time, AdminError> {
    match explicit {
        Some(api_timeout) if api_timeout < request_timeout => Err(AdminError::InvalidConfig(
            "default_api_timeout must be no smaller than request_timeout".to_owned(),
        )),
        Some(api_timeout) => Ok(api_timeout),
        None if DEFAULT_API_TIMEOUT < request_timeout => {
            tracing::warn!(
                request_timeout_ms = request_timeout.millis_i64(),
                "overriding the default of default.api.timeout.ms (60000) with the configured \
                 request timeout"
            );
            Ok(request_timeout)
        }
        None => Ok(DEFAULT_API_TIMEOUT),
    }
}

/// The retry policy of a client built from bare [`ConnectionOptions`]:
/// Kafka's defaults, with the call deadline raised to the request timeout.
pub(crate) fn retry_for_connection_options(options: &ConnectionOptions) -> RetryPolicy {
    let timeout = if options.request_timeout > DEFAULT_API_TIMEOUT {
        options.request_timeout
    } else {
        DEFAULT_API_TIMEOUT
    };
    RetryPolicy {
        timeout: timeout.to_std(),
        initial_backoff: DEFAULT_RETRY_BACKOFF.to_std(),
        max_backoff: DEFAULT_RETRY_BACKOFF_MAX.to_std(),
        jitter: RETRY_BACKOFF_JITTER,
        max_retries: u32::MAX,
    }
}

#[cfg(test)]
mod tests {
    use std::{
        sync::{
            Arc, Mutex,
            atomic::{AtomicUsize, Ordering},
        },
        time::Duration,
    };

    use assert2::{assert, check};
    use bytes::{Buf, BytesMut};
    use krabka_client_core::MockBroker;
    use krabka_protocol::{
        Encode,
        owned::{
            api_versions_request,
            api_versions_response::{ApiVersion, ApiVersionsResponse},
            unregister_broker_request,
            unregister_broker_response::UnregisterBrokerResponse,
        },
    };

    use super::*;
    use crate::AdminClient;

    /// The settings that a test compares: client id prefix or value, request
    /// timeout, connection setup timeouts, idle time, and the retry policy.
    #[derive(Debug, PartialEq)]
    struct Observed {
        client_id: String,
        request_timeout: Time,
        setup_timeouts: (Time, Time),
        connections_max_idle: Time,
        retry: RetryPolicy,
    }

    fn observe(config: AdminClientConfig) -> Result<Observed, String> {
        config
            .resolve()
            .map(|resolved| Observed {
                // A generated id ends with a process-wide sequence number.
                client_id: if resolved.connection.client_id.starts_with("adminclient-") {
                    "adminclient-<n>".to_owned()
                } else {
                    resolved.connection.client_id
                },
                request_timeout: resolved.connection.request_timeout,
                setup_timeouts: (
                    resolved.connection.socket_connection_setup_timeout,
                    resolved.connection.socket_connection_setup_timeout_max,
                ),
                connections_max_idle: resolved.connection.connections_max_idle,
                retry: resolved.retry,
            })
            .map_err(|error| error.to_string())
    }

    fn retry(timeout: Duration) -> RetryPolicy {
        RetryPolicy {
            timeout,
            initial_backoff: Duration::from_millis(100),
            max_backoff: Duration::from_secs(1),
            jitter: 0.2,
            max_retries: u32::MAX,
        }
    }

    /// Kafka's `AdminClientConfig` defaults, `generateClientId`, and
    /// `configureDefaultApiTimeoutMs`.
    #[test]
    fn settings_resolve_as_kafka_admin_client_config() {
        let defaults = || Observed {
            client_id: "adminclient-<n>".into(),
            request_timeout: secs(30),
            setup_timeouts: (secs(10), secs(30)),
            connections_max_idle: krabka_units::minutes(5),
            retry: retry(Duration::from_mins(1)),
        };
        for (name, config, expected) in [
            ("defaults", AdminClientConfig::default(), Ok(defaults())),
            (
                "request timeout 90 s raises the default api timeout",
                AdminClientConfig {
                    request_timeout: secs(90),
                    ..AdminClientConfig::default()
                },
                Ok(Observed {
                    request_timeout: secs(90),
                    retry: retry(Duration::from_secs(90)),
                    ..defaults()
                }),
            ),
            (
                "api timeout below the request timeout is an error",
                AdminClientConfig {
                    request_timeout: secs(90),
                    default_api_timeout: Some(secs(60)),
                    ..AdminClientConfig::default()
                },
                Err(
                    "invalid admin client configuration: default_api_timeout must be no smaller \
                     than request_timeout"
                        .to_owned(),
                ),
            ),
            (
                "api timeout equal to the request timeout",
                AdminClientConfig {
                    default_api_timeout: Some(secs(30)),
                    ..AdminClientConfig::default()
                },
                Ok(Observed {
                    retry: retry(Duration::from_secs(30)),
                    ..defaults()
                }),
            ),
            (
                "explicit client id",
                AdminClientConfig {
                    client_id: Some("tool-a".into()),
                    ..AdminClientConfig::default()
                },
                Ok(Observed {
                    client_id: "tool-a".into(),
                    ..defaults()
                }),
            ),
            (
                "empty client id is generated",
                AdminClientConfig {
                    client_id: Some(String::new()),
                    ..AdminClientConfig::default()
                },
                Ok(defaults()),
            ),
            (
                "retries, backoff and setup timeout",
                AdminClientConfig {
                    retries: 3,
                    retry_backoff: millis(50),
                    retry_backoff_max: secs(2),
                    socket_connection_setup_timeout: secs(5),
                    socket_connection_setup_timeout_max: secs(20),
                    connections_max_idle: secs(60),
                    ..AdminClientConfig::default()
                },
                Ok(Observed {
                    setup_timeouts: (secs(5), secs(20)),
                    connections_max_idle: secs(60),
                    retry: RetryPolicy {
                        initial_backoff: Duration::from_millis(50),
                        max_backoff: Duration::from_secs(2),
                        max_retries: 3,
                        ..retry(Duration::from_mins(1))
                    },
                    ..defaults()
                }),
            ),
            (
                "zero request timeout is an error",
                AdminClientConfig {
                    request_timeout: Time::ZERO,
                    ..AdminClientConfig::default()
                },
                Err(
                    "invalid admin client configuration: request_timeout must be positive and \
                     finite"
                        .to_owned(),
                ),
            ),
            (
                "infinite request timeout is an error",
                AdminClientConfig {
                    request_timeout: Time::from_secs_f64(f64::INFINITY),
                    ..AdminClientConfig::default()
                },
                Err(
                    "invalid admin client configuration: request_timeout must be positive and \
                     finite"
                        .to_owned(),
                ),
            ),
            (
                "NaN api timeout is an error",
                AdminClientConfig {
                    default_api_timeout: Some(Time::from_secs_f64(f64::NAN)),
                    ..AdminClientConfig::default()
                },
                Err(
                    "invalid admin client configuration: default_api_timeout must be positive \
                     and finite"
                        .to_owned(),
                ),
            ),
            (
                "NaN retry backoff is an error",
                AdminClientConfig {
                    retry_backoff: Time::from_secs_f64(f64::NAN),
                    ..AdminClientConfig::default()
                },
                Err(
                    "invalid admin client configuration: retry_backoff must be finite and not \
                     negative"
                        .to_owned(),
                ),
            ),
        ] {
            check!(observe(config) == expected, "{name}");
        }
    }

    #[test]
    fn generated_client_ids_follow_a_process_wide_sequence() {
        let id = || {
            AdminClientConfig::default()
                .resolve()
                .expect("defaults resolve")
                .connection
                .client_id
        };
        let number = |id: String| {
            id.strip_prefix("adminclient-")
                .and_then(|number| number.parse::<u32>().ok())
                .expect("adminclient-<n>")
        };
        let first = number(id());
        let second = number(id());
        assert!(second > first);
        assert!(first >= 1);
    }

    /// A broker that answers every `UnregisterBroker` with
    /// `REQUEST_TIMED_OUT`, and records the client id of each request.
    async fn timing_out_broker(
        requests: Arc<AtomicUsize>,
        client_ids: Arc<Mutex<Vec<String>>>,
    ) -> MockBroker {
        MockBroker::start(move |api_key, version, _, request| {
            let mut header = request;
            let client_id_len = usize::try_from(header.get_i16()).expect("client id length");
            client_ids
                .lock()
                .expect("client ids lock")
                .push(String::from_utf8_lossy(&header[..client_id_len]).into_owned());
            let mut body = BytesMut::new();
            match api_key {
                api_versions_request::API_KEY => ApiVersionsResponse {
                    api_keys: vec![
                        ApiVersion {
                            api_key: api_versions_request::API_KEY,
                            ..Default::default()
                        },
                        ApiVersion {
                            api_key: unregister_broker_request::API_KEY,
                            ..Default::default()
                        },
                    ],
                    ..Default::default()
                }
                .encode(&mut body, 0)
                .unwrap(),
                unregister_broker_request::API_KEY => {
                    requests.fetch_add(1, Ordering::SeqCst);
                    body.extend_from_slice(&[0]);
                    UnregisterBrokerResponse {
                        error_code: 7,
                        ..Default::default()
                    }
                    .encode(&mut body, version)
                    .unwrap();
                }
                _ => return None,
            }
            Some(body.to_vec())
        })
        .await
    }

    /// A client built from `AdminClientConfig` sends its client id in each
    /// request header, stops a call at `default_api_timeout`, and stops after
    /// `retries` retries.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_client_uses_its_client_id_call_deadline_and_retries() {
        for (name, config, expected_requests) in [
            (
                "no retries",
                AdminClientConfig {
                    client_id: Some("tool-a".into()),
                    retries: 0,
                    ..AdminClientConfig::default()
                },
                1..=1,
            ),
            (
                "two retries",
                AdminClientConfig {
                    client_id: Some("tool-a".into()),
                    retries: 2,
                    retry_backoff: millis(1),
                    retry_backoff_max: millis(1),
                    ..AdminClientConfig::default()
                },
                3..=3,
            ),
            (
                "the call deadline stops the retries",
                AdminClientConfig {
                    client_id: Some("tool-a".into()),
                    request_timeout: millis(100),
                    default_api_timeout: Some(millis(400)),
                    retry_backoff: millis(100),
                    retry_backoff_max: millis(100),
                    ..AdminClientConfig::default()
                },
                2..=6,
            ),
        ] {
            let requests = Arc::new(AtomicUsize::new(0));
            let client_ids = Arc::new(Mutex::new(Vec::new()));
            let broker = timing_out_broker(Arc::clone(&requests), Arc::clone(&client_ids)).await;
            let mut admin = AdminClient::connect_with_config(&[broker.addr.to_string()], config)
                .await
                .expect("admin connects");

            let started = tokio::time::Instant::now();
            let result = admin.unregister_broker(1).await;
            let elapsed = started.elapsed();

            broker.stop();
            let code = match result {
                Err(crate::AdminError::Broker { code, .. }) => Some(code),
                _ => None,
            };
            let requests = requests.load(Ordering::SeqCst);
            let client_ids = client_ids.lock().expect("client ids lock").clone();
            check!(code == Some(7), "{name}");
            check!(
                expected_requests.contains(&requests),
                "{name}: {requests} requests"
            );
            check!(elapsed < Duration::from_secs(5), "{name}");
            check!(
                client_ids.iter().all(|id| id == "tool-a") && !client_ids.is_empty(),
                "{name}: {client_ids:?}"
            );
        }
    }
}

#[cfg(test)]
mod transport_configuration_tests {
    use assert2::assert;
    use krabka_client_core::{ClientDnsLookup, ClientFrameMax, ConnectionDispatchQueueCapacity};
    use krabka_units::{
        convert::{ByteSizeExt as _, TimeExt as _},
        kibibytes, mebibytes, millis,
    };

    use super::AdminClientConfig;

    #[test]
    fn admin_resolves_transport_resources_without_losing_retry_policy() {
        let config = AdminClientConfig {
            client_dns_lookup: ClientDnsLookup::ResolveCanonicalBootstrapServersOnly,
            reconnect_backoff: millis(27),
            reconnect_backoff_max: millis(127),
            send_buffer: None,
            receive_buffer: Some(kibibytes(19)),
            dispatch_queue_capacity: ConnectionDispatchQueueCapacity::new(7).expect("capacity"),
            frame_max: ClientFrameMax::try_from(mebibytes(2)).expect("frame"),
            retry_backoff: millis(37),
            ..Default::default()
        };
        let resolved = config.resolve().expect("valid config");
        let options = resolved.connection;
        assert!(
            (
                options.client_dns_lookup,
                options.reconnect_backoff,
                options.reconnect_backoff_max,
                options.send_buffer,
                options.receive_buffer,
                options.dispatch_queue_capacity.get(),
                options.frame_max.size()
            ) == (
                ClientDnsLookup::ResolveCanonicalBootstrapServersOnly,
                millis(27),
                millis(127),
                None,
                Some(kibibytes(19)),
                7,
                mebibytes(2)
            )
        );
        assert!(resolved.retry.initial_backoff == std::time::Duration::from_millis(37));
        let invalid = AdminClientConfig {
            reconnect_backoff: millis(2000),
            ..Default::default()
        };
        assert!(invalid.resolve().is_err());
    }

    #[test]
    fn admin_rejects_invalid_transport_bounds_and_socket_sizes() {
        let invalid_backoff = AdminClientConfig {
            reconnect_backoff: krabka_units::Time::from_secs_f64(f64::NAN),
            ..Default::default()
        };
        assert!(invalid_backoff.resolve().is_err());

        let fractional_socket_buffer = AdminClientConfig {
            send_buffer: Some(krabka_units::ByteSize::from_bytes_f64(0.5)),
            ..Default::default()
        };
        assert!(fractional_socket_buffer.resolve().is_err());

        let inverted_setup_bounds = AdminClientConfig {
            socket_connection_setup_timeout_max: krabka_units::millis(1),
            ..Default::default()
        };
        assert!(inverted_setup_bounds.resolve().is_err());
    }
}