kintone 0.6.2

kintone REST API client
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
//! # Middleware System for Kintone Client
//!
//! This module provides a middleware system for the Kintone client that allows
//! for intercepting and modifying requests and responses. Middleware can handle cross-cutting
//! concerns such as retries, logging, authentication, and custom request/response processing.
//!
//! ## Core Concepts
//!
//! The middleware system is built around two fundamental concepts:
//!
//! ### Handler: Request → Response Function
//! A [`Handler`] is essentially a function that transforms an HTTP request into an HTTP response.
//! This is the core abstraction that represents any piece of logic that can process requests.
//!
//! ### Layer: Handler Stacking Mechanism  
//! A [`Layer`] is a mechanism for "stacking" multiple Handlers to create a single, more powerful Handler.
//! Layers allow you to compose functionality by wrapping one Handler with another, creating
//! a chain where each layer can add behavior before and after the inner handler processes the request.
//!
//! ## How Stacking Works
//!
//! When you stack layers like this:
//! ```ignore
//! client_builder
//!     .layer(RetryLayer::new().with_max_attempts(5)) // Layer A
//!     .layer(LoggingLayer::new())                    // Layer B
//!     .build()
//! ```
//!
//! You get a handler stack that looks like:
//! ```ignore
//! RetryLayer(LoggingLayer(BaseHandler))
//! ```
//!
//! Requests flow through: RetryLayer → LoggingLayer → BaseHandler  
//! Responses flow back: BaseHandler → LoggingLayer → RetryLayer
//!
//! ## Built-in Middleware
//!
//! - [`RetryLayer`] - Automatically retries failed requests with exponential backoff
//! - [`LoggingLayer`] - Logs request and response information for debugging
//! - [`BasicAuthLayer`] - Adds HTTP Basic authentication headers to requests

use std::{
    borrow::Borrow,
    io::{Cursor, Read},
    sync::Arc,
};

use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use http::Request;
use log::info;
use serde::de::DeserializeOwned;

use crate::error::ApiError;

/// Represents the body of an HTTP request in the middleware system.
///
/// This abstraction allows for different types of request bodies while maintaining
/// the ability to clone and reuse them for retry operations. The body can be:
/// - Empty (void)
/// - Bytes in memory (cloneable for retries)
/// - A streaming reader (non-cloneable)
///
/// # Examples
///
/// ```ignore
/// use std::fs::File;
/// use std::io::BufReader;
///
/// // Empty body
/// let body = RequestBody::void();
///
/// // JSON body from bytes
/// let json_bytes = serde_json::to_vec(&data)?;
/// let body = RequestBody::from_bytes(json_bytes);
///
/// // Streaming body from file
/// let file = File::open("large_file.txt")?;
/// let body = RequestBody::from_reader(BufReader::new(file));
/// ```
pub struct RequestBody(RequestBodyInner);

impl RequestBody {
    pub fn void() -> Self {
        RequestBody(RequestBodyInner::Void)
    }

    pub fn from_bytes(bytes: Vec<u8>) -> Self {
        RequestBody(RequestBodyInner::Bytes(Arc::from(bytes.into_boxed_slice())))
    }

    pub fn from_reader(reader: impl Read + Sync + Send + 'static) -> Self {
        RequestBody(RequestBodyInner::Reader(Box::new(reader)))
    }

    pub fn try_clone(&self) -> Option<Self> {
        match &self.0 {
            RequestBodyInner::Void => Some(RequestBody(RequestBodyInner::Void)),
            RequestBodyInner::Bytes(p) => Some(RequestBody(RequestBodyInner::Bytes(Arc::clone(p)))),
            RequestBodyInner::Reader(_) => None, // Reader cannot be cloned
        }
    }

    pub fn into_reader(self) -> impl Read {
        self.into_ureq_body().into_reader()
    }

    pub(crate) fn into_ureq_body(self) -> ureq::SendBody<'static> {
        match self.0 {
            RequestBodyInner::Void => ureq::SendBody::none(),
            RequestBodyInner::Bytes(b) => ureq::SendBody::from_owned_reader(Cursor::new(b)),
            RequestBodyInner::Reader(reader) => ureq::SendBody::from_owned_reader(reader),
        }
    }
}

enum RequestBodyInner {
    Void,
    Bytes(Arc<[u8]>),
    Reader(Box<dyn Read + Sync + Send + 'static>),
}

/// Represents the body of an HTTP response in the middleware system.
///
/// This wrapper around the raw response body provides methods for reading
/// the response content, including JSON deserialization and streaming access.
/// The body can only be consumed once due to its streaming nature.
///
/// # Examples
///
/// ```ignore
/// // Read as JSON
/// let data: MyStruct = response_body.read_json()?;
///
/// // Read as raw stream
/// let reader = response_body.into_reader();
/// std::io::copy(&mut reader, &mut output_file)?;
/// ```
pub struct ResponseBody(ureq::Body);

impl ResponseBody {
    const MAX_JSON_SIZE: u64 = 10 * 1024 * 1024;

    pub(crate) fn from_ureq_body(body: ureq::Body) -> Self {
        ResponseBody(body)
    }

    pub fn into_reader(self) -> impl Read + 'static {
        self.0.into_reader()
    }

    pub fn read_json<D: DeserializeOwned>(&mut self) -> Result<D, ApiError> {
        let body = self.0.with_config().limit(Self::MAX_JSON_SIZE).read_to_vec()?;
        serde_json::from_slice(&body).map_err(|e| e.into())
    }
}

//-----------------------------------------------------------------------------

/// Core trait for handling HTTP requests in the middleware system.
///
/// **At its essence, a Handler is a function that transforms an HTTP request into an HTTP response.**
/// This is the fundamental building block of the middleware system. Every Handler takes a request
/// and produces either a successful response or an error.
///
/// Handlers form the foundation of the middleware system, where each middleware layer
/// wraps a handler to add additional functionality while maintaining this core contract
/// of `Request -> Response`.
///
/// # The Function-like Nature
///
/// You can think of a Handler as:
/// ```ignore
/// fn handle(request: Request) -> Result<Response, Error>
/// ```
///
/// This simple concept allows for powerful composition through the middleware system.
pub trait Handler: Send + Sync + 'static {
    fn handle(
        &self,
        req: http::Request<RequestBody>,
    ) -> Result<http::Response<ResponseBody>, ApiError>;
}

/// Trait for middleware layers that can wrap handlers to add functionality.
///
/// **A Layer is a mechanism for "stacking" multiple Handlers to create a single, more powerful Handler.**
/// Think of it as a way to compose functionality by wrapping one Handler with another.
///
/// Each Layer takes an inner Handler and produces a new Handler that adds some behavior
/// around the inner one. This creates a "Russian doll" effect where requests flow through
/// each layer in order, and responses flow back through them in reverse order.
///
/// # The Stacking Concept
///
/// When you have multiple layers, they stack like this:
/// ```ignore
/// Layer3(Layer2(Layer1(BaseHandler)))
/// ```
///
/// The request flows: Layer3 -> Layer2 -> Layer1 -> BaseHandler
/// The response flows: BaseHandler -> Layer1 -> Layer2 -> Layer3
///
/// This allows each layer to:
/// - Modify the request before passing it down
/// - Modify the response after receiving it back
/// - Add cross-cutting concerns (logging, retries, authentication, etc.)
/// - Short-circuit the chain (e.g., return cached responses)
///
/// # Type Parameters
///
/// * `Inner` - The type of handler that this layer wraps
///
/// # Associated Types
///
/// * `Outer` - The type of handler returned after wrapping the inner handler
///
/// # Examples
///
/// ```ignore
/// impl<Inner: Handler> Layer<Inner> for MyMiddleware {
///     type Outer = MyHandler<Inner>;
///
///     fn layer(self, inner: Inner) -> Self::Outer {
///         // Return a new handler that wraps the inner one
///         MyHandler { inner, config: self }
///     }
/// }
/// ```
pub trait Layer<Inner: Handler>: Send + Sync + 'static {
    type Outer: Handler;
    fn layer(self, inner: Inner) -> Self::Outer;
}

//-----------------------------------------------------------------------------

/// Type alias for a function that determines whether a request should be retried.
///
/// This function receives the original request (without body) and the response (or `ApiError`),
/// and returns `true` if the request should be retried. The request body is
/// removed to avoid ownership issues and because retry decisions are typically
/// based on response status rather than request content.
///
/// # Examples
///
/// ```no_run
/// use kintone::middleware::ShouldRetryFn;
/// let should_retry: Box<ShouldRetryFn> = Box::new(|req, resp_or_err| {
///     let Ok(resp) = resp_or_err else {
///         return false;  // Never retry on API errors.
///     };
///     // Retry on server errors (5xx) or specific client errors
///     resp.status().is_server_error() || resp.status() == 429
/// });
/// ```
pub type ShouldRetryFn = dyn Fn(&http::Request<()>, Result<&http::Response<ResponseBody>, &ApiError>) -> bool
    + Send
    + Sync
    + 'static;

/// Middleware layer that automatically retries failed requests with exponential backoff.
///
/// This layer is particularly useful for handling transient errors like database locks
/// (GAIA_DA02 in Kintone) or network timeouts. It implements exponential backoff to
/// avoid overwhelming the server with rapid retry attempts.
///
/// # Retry Logic
///
/// - Requests are retried up to `max_attempts` times
/// - Delay between retries starts at `initial_delay` and doubles after each attempt
/// - Delay is capped at `max_delay` to prevent excessively long waits
/// - Only requests with cloneable bodies can be retried (streaming requests are not retried)
///
/// # Examples
///
/// ```rust
/// use std::time::Duration;
/// use kintone::middleware::RetryLayer;
///
/// // Retry up to 5 times with exponential backoff
/// let retry_layer = RetryLayer::new()
///     .with_max_attempts(5)
///     .with_initial_delay(Duration::from_millis(500))
///     .with_max_delay(Duration::from_secs(30));
/// ```
/// RetryLayer controls automatic retry logic for failed requests.
///
/// Use builder-style methods to configure retry policy.
pub struct RetryLayer {
    max_attempts: usize,
    initial_delay: std::time::Duration,
    max_delay: std::time::Duration,
    should_retry: Box<ShouldRetryFn>,
}

impl RetryLayer {
    const NONRETRYABLE_CODES: &[&str] = &[
        "CB_IL02", // "不正なリクエストです。"
    ];

    pub const DEFAULT_MAX_ATTEMPTS: usize = 5;
    pub const DEFAULT_INITIAL_DELAY: std::time::Duration = std::time::Duration::from_secs(1);
    pub const DEFAULT_MAX_DELAY: std::time::Duration = std::time::Duration::from_secs(8);
    pub const DEFAULT_SHOULD_RETRY_FN: &ShouldRetryFn = &|_, resp_or_err| match resp_or_err {
        Ok(resp) => !resp.status().is_success(),
        Err(err) => {
            if let ApiError::Kintone(kintone_err) = err {
                !Self::NONRETRYABLE_CODES.contains(&kintone_err.code.borrow())
            } else {
                true
            }
        }
    };

    /// Creates a new RetryLayer with default settings.
    pub fn new() -> Self {
        RetryLayer {
            max_attempts: Self::DEFAULT_MAX_ATTEMPTS,
            initial_delay: Self::DEFAULT_INITIAL_DELAY,
            max_delay: Self::DEFAULT_MAX_DELAY,
            should_retry: Box::new(Self::DEFAULT_SHOULD_RETRY_FN),
        }
    }

    /// Sets the maximum number of retry attempts.
    /// `max_attempts` must be ≧ 1.
    /// If `max_attempts` is 1, retries are disabled.
    pub fn with_max_attempts(mut self, max_attempts: usize) -> Self {
        if max_attempts == 0 {
            panic!("max_attempts must be >= 1");
        }
        self.max_attempts = max_attempts;
        self
    }

    /// Sets the initial delay before the first retry.
    pub fn with_initial_delay(mut self, initial_delay: std::time::Duration) -> Self {
        self.initial_delay = initial_delay;
        self
    }

    /// Sets the maximum delay between retries.
    pub fn with_max_delay(mut self, max_delay: std::time::Duration) -> Self {
        self.max_delay = max_delay;
        self
    }

    /// Sets the retry decision function.
    pub fn with_should_retry(mut self, should_retry: Box<ShouldRetryFn>) -> Self {
        self.should_retry = should_retry;
        self
    }
}

impl Default for RetryLayer {
    fn default() -> Self {
        Self::new()
    }
}

impl<Inner: Handler> Layer<Inner> for RetryLayer {
    type Outer = RetryHandler<Inner>;
    fn layer(self, inner: Inner) -> Self::Outer {
        RetryHandler { inner, layer: self }
    }
}

/// Handler implementation that wraps another handler with retry logic.
///
/// This handler implements the actual retry behavior for the [`RetryLayer`].
/// It attempts requests multiple times according to the configured retry policy,
/// with exponential backoff between attempts.
///
/// This is an internal implementation detail and should not be used directly.
pub struct RetryHandler<Inner> {
    inner: Inner,
    layer: RetryLayer,
}

impl<Inner: Handler> Handler for RetryHandler<Inner> {
    fn handle(
        &self,
        req: http::Request<RequestBody>,
    ) -> Result<http::Response<ResponseBody>, ApiError> {
        if self.layer.max_attempts == 1 {
            return self.inner.handle(req);
        }

        let (parts, body) = req.into_parts();

        let mut attempts = 1;
        let mut delay = self.layer.initial_delay;

        loop {
            let Some(body_cloned) = body.try_clone() else {
                // Body cannot be cloned. We cannot retry this request.
                let req = Request::from_parts(parts, body);
                return self.inner.handle(req);
            };
            let req_cloned = http::Request::from_parts(parts.clone(), body_cloned);
            let result = self.inner.handle(req_cloned);

            match result {
                Ok(resp) => {
                    if attempts >= self.layer.max_attempts {
                        return Ok(resp);
                    }
                    let req_nobody = http::Request::from_parts(parts.clone(), ());
                    let retry_ok = (self.layer.should_retry)(&req_nobody, Ok(&resp));
                    if !retry_ok {
                        return Ok(resp);
                    }
                    // do retry
                }
                Err(e) => {
                    if attempts >= self.layer.max_attempts {
                        return Err(e);
                    }
                    let req_nobody = http::Request::from_parts(parts.clone(), ());
                    let retry_ok = (self.layer.should_retry)(&req_nobody, Err(&e));
                    if !retry_ok {
                        return Err(e);
                    }
                    // do retry
                }
            }

            std::thread::sleep(delay);
            delay = std::cmp::min(delay * 2, self.layer.max_delay);
            attempts += 1;
        }
    }
}

//-----------------------------------------------------------------------------

/// Middleware layer that logs HTTP request and response information.
///
/// This layer provides debugging capabilities by logging details about each
/// HTTP request and response.
///
/// - Uses the [`log`](https://docs.rs/log/latest/log/) crate for logging output.
/// - All logs are emitted at the `info` level.
/// - You can use any logger compatible with the `log` crate (e.g., `env_logger`, `tracing`, etc.).
///
/// # Logged Information
///
/// - Request: HTTP method and URL
/// - Request body (if available)
/// - Response: HTTP status code or error details
///
/// # Examples
///
/// ```rust
/// use kintone::middleware::LoggingLayer;
///
/// env_logger::init();
/// let logging_layer = LoggingLayer::new();
/// ```
pub struct LoggingLayer {
    log_target: String,
    enabled: bool,
}

impl LoggingLayer {
    const DEFAULT_LOG_TARGET: &str = "kintone";

    /// Creates a new LoggingLayer with logging enabled by default.
    pub fn new() -> Self {
        LoggingLayer {
            log_target: Self::DEFAULT_LOG_TARGET.to_owned(),
            enabled: true,
        }
    }

    /// Enables or disables logging for this layer. (builder style)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kintone::middleware::LoggingLayer;
    /// let logging_layer = LoggingLayer::new().with_enabled(false);
    /// ```
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Sets the log target for this layer. (builder style)
    ///
    /// See the document of [log][log] crate for log targets.
    ///
    /// [log]: https://docs.rs/log/latest/log/
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kintone::middleware::LoggingLayer;
    /// let logging_layer = LoggingLayer::new().with_log_target("kintone::access_log");
    /// ```
    pub fn with_log_target(mut self, target: impl Into<String>) -> Self {
        self.log_target = target.into();
        self
    }
}

impl Default for LoggingLayer {
    fn default() -> Self {
        LoggingLayer::new()
    }
}

impl<Inner: Handler> Layer<Inner> for LoggingLayer {
    type Outer = LoggingHandler<Inner>;
    fn layer(self, inner: Inner) -> Self::Outer {
        LoggingHandler {
            inner,
            log_target: self.log_target,
            enabled: self.enabled,
        }
    }
}

/// Handler implementation that wraps another handler with logging functionality.
///
/// This handler implements the actual logging behavior for the [`LoggingLayer`].
/// It logs request details before calling the inner handler and logs response
/// details after receiving the response.
///
/// This is an internal implementation detail and should not be used directly.
pub struct LoggingHandler<Inner> {
    inner: Inner,
    log_target: String,
    enabled: bool,
}

impl<Inner: Handler> Handler for LoggingHandler<Inner> {
    fn handle(
        &self,
        req: http::Request<RequestBody>,
    ) -> Result<http::Response<ResponseBody>, ApiError> {
        if !self.enabled {
            return self.inner.handle(req);
        }

        info!(target: &self.log_target, "Request: method={}, url={:?}", req.method(), req.uri());
        if let Some(body) = req.body().try_clone() {
            let mut buf = String::new();
            if body.into_reader().read_to_string(&mut buf).is_ok() {
                info!(target: &self.log_target, "Request body:\n{buf}");
            }
        }
        let result = self.inner.handle(req);
        match &result {
            Ok(resp) => {
                info!(target: &self.log_target, "Response: status={}", resp.status().as_u16());
            }
            Err(e) => info!(target: &self.log_target, "Response: error={e}"),
        }
        result
    }
}

//-----------------------------------------------------------------------------

/// Middleware layer that adds HTTP Basic authentication headers to requests.
///
/// This layer automatically adds the `Authorization` header with Basic authentication
/// credentials to all outgoing requests.
///
/// # Examples
///
/// ```rust
/// use kintone::middleware::BasicAuthLayer;
///
/// // Enable Basic authentication
/// let basic_auth = BasicAuthLayer::new(Some(("username".to_string(), "password".to_string())));
///
/// // Disable Basic authentication
/// let no_auth = BasicAuthLayer::new(None);
/// ```
///
/// Combined with other middleware:
/// ```rust
/// use std::time::Duration;
/// use kintone::client::{Auth, KintoneClientBuilder};
/// use kintone::middleware;
///
/// let client = KintoneClientBuilder::new(
///         "https://your-domain.cybozu.com",
///         Auth::api_token("your-api-token".to_owned())
///     )
///     .layer(middleware::BasicAuthLayer::new(Some(("basicauth_user".to_string(), "basicauth_password".to_string()))))
///     .layer(middleware::RetryLayer::new()
///         .with_max_attempts(5)
///         .with_initial_delay(Duration::from_secs(1))
///         .with_max_delay(Duration::from_secs(8))
///     )
///     .layer(middleware::LoggingLayer::new())
///     .build();
/// ```
pub struct BasicAuthLayer {
    credentials: Option<(String, String)>,
}

impl BasicAuthLayer {
    /// Creates a new Basic authentication layer with optional credentials.
    ///
    /// # Arguments
    ///
    /// * `credentials` - Optional tuple of (username, password) for Basic authentication.
    ///   Pass `None` to disable Basic authentication, or `Some((username, password))` to enable it.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kintone::middleware::BasicAuthLayer;
    ///
    /// // Enable Basic authentication
    /// let basic_auth = BasicAuthLayer::new(Some(("myuser".to_string(), "mypassword".to_string())));
    ///
    /// // Disable Basic authentication
    /// let no_auth = BasicAuthLayer::new(None);
    /// ```
    pub fn new(credentials: Option<(String, String)>) -> Self {
        BasicAuthLayer { credentials }
    }

    /// Creates a new Basic authentication layer with the provided credentials.
    ///
    /// This is a convenience method that automatically wraps the credentials in `Some()`.
    ///
    /// # Arguments
    ///
    /// * `username` - The username for Basic authentication
    /// * `password` - The password for Basic authentication
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kintone::middleware::BasicAuthLayer;
    ///
    /// let basic_auth = BasicAuthLayer::enabled("myuser", "mypassword");
    /// ```
    pub fn enabled(username: impl Into<String>, password: impl Into<String>) -> Self {
        BasicAuthLayer {
            credentials: Some((username.into(), password.into())),
        }
    }

    /// Creates a new Basic authentication layer with authentication disabled.
    ///
    /// This is a convenience method that creates a layer that won't add any
    /// authentication headers to requests.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kintone::middleware::BasicAuthLayer;
    ///
    /// let no_auth = BasicAuthLayer::disabled();
    /// ```
    pub fn disabled() -> Self {
        BasicAuthLayer { credentials: None }
    }

    fn encode_credentials(&self) -> Option<String> {
        self.credentials.as_ref().map(|(username, password)| {
            let credentials = format!("{username}:{password}");
            let encoded = BASE64.encode(credentials.as_bytes());
            format!("Basic {encoded}")
        })
    }
}

impl<Inner: Handler> Layer<Inner> for BasicAuthLayer {
    type Outer = BasicAuthHandler<Inner>;
    fn layer(self, inner: Inner) -> Self::Outer {
        BasicAuthHandler { inner, layer: self }
    }
}

/// Handler implementation that wraps another handler with Basic authentication.
///
/// This handler implements the actual Basic auth behavior for the [`BasicAuthLayer`].
/// It adds the Authorization header to requests before passing them to the inner handler.
///
/// This is an internal implementation detail and should not be used directly.
pub struct BasicAuthHandler<Inner> {
    inner: Inner,
    layer: BasicAuthLayer,
}

impl<Inner: Handler> Handler for BasicAuthHandler<Inner> {
    fn handle(
        &self,
        mut req: http::Request<RequestBody>,
    ) -> Result<http::Response<ResponseBody>, ApiError> {
        if let Some(auth_header_value) = self.layer.encode_credentials() {
            req.headers_mut()
                .insert(http::header::AUTHORIZATION, auth_header_value.parse().unwrap());
        }
        self.inner.handle(req)
    }
}

//-----------------------------------------------------------------------------

/// A no-op middleware layer that provides no additional functionality.
///
/// This layer is used as the base case in the middleware stack. When applied,
/// it simply returns the inner handler unchanged. It's primarily used internally
/// by the [`KintoneClientBuilder`] as the starting point for building middleware stacks.
///
/// [`KintoneClientBuilder`]: crate::client::KintoneClientBuilder
pub struct NoLayer;

impl<Inner: Handler> Layer<Inner> for NoLayer {
    type Outer = Inner;
    fn layer(self, inner: Inner) -> Self::Outer {
        inner
    }
}

/// A stack of two middleware layers that composes them into a single layer.
///
/// This type allows for building chains of middleware by combining pairs of layers.
/// When applied, it first applies the `Tail` layer to the inner handler, then
/// applies the `Head` layer to the result.
///
/// This is an internal implementation detail used by the middleware system to
/// build complex middleware stacks from individual layers.
///
/// # Type Parameters
///
/// * `Head` - The outer layer (applied last)
/// * `Tail` - The inner layer (applied first)
///
/// # Examples
///
/// ```ignore
/// // This creates a stack: LoggingLayer -> RetryLayer -> Handler
/// let stack = Stack::new(LoggingLayer::new(), RetryLayer::new(...));
/// ```
pub struct Stack<Head, Tail>(Head, Tail);

impl<Head, Tail> Stack<Head, Tail> {
    pub fn new(head: Head, tail: Tail) -> Self {
        Stack(head, tail)
    }
}

impl<Inner, Head, Tail> Layer<Inner> for Stack<Head, Tail>
where
    Inner: Handler,
    Head: Layer<Tail::Outer>,
    Tail: Layer<Inner>,
{
    type Outer = Head::Outer;
    fn layer(self, inner: Inner) -> Self::Outer {
        self.0.layer(self.1.layer(inner))
    }
}