kube-client 4.0.0

Kubernetes 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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! API client for interacting with the Kubernetes API
//!
//! The [`Client`] uses standard kube error handling.
//!
//! This client can be used on its own or in conjunction with the [`Api`][crate::api::Api]
//! type for more structured interaction with the kubernetes API.
//!
//! The [`Client`] can also be used with [`Discovery`](crate::Discovery) to dynamically
//! retrieve the resources served by the kubernetes API.
use either::{Either, Left, Right};
use futures::{AsyncBufRead, StreamExt, TryStream, TryStreamExt, future::BoxFuture};
use http::{self, Request, Response};
use http_body_util::BodyExt;
#[cfg(feature = "ws")]
use hyper_util::rt::TokioIo;
use jiff::Timestamp;
use k8s_openapi::apimachinery::pkg::apis::meta::v1 as k8s_meta_v1;
use kube_core::{discovery::v2::ACCEPT_AGGREGATED_DISCOVERY_V2, response::Status};
use serde::de::DeserializeOwned;
use serde_json::{self, Value};
#[cfg(feature = "ws")]
use tokio_tungstenite::{WebSocketStream, tungstenite as ws};
use tokio_util::{
    codec::{FramedRead, LinesCodec, LinesCodecError},
    io::StreamReader,
};
use tower::{BoxError, Service, ServiceExt as _, buffer::Buffer};
use tower_http::ServiceExt as _;

pub use self::body::Body;
use crate::{Config, Error, Result, api::WatchEvent, config::Kubeconfig};

mod auth;
mod body;
mod builder;
pub use kube_core::discovery::v2::{
    APIGroupDiscovery, APIGroupDiscoveryList, APIResourceDiscovery, APISubresourceDiscovery,
    APIVersionDiscovery, GroupVersionKind as DiscoveryGroupVersionKind,
};
#[cfg_attr(docsrs, doc(cfg(feature = "unstable-client")))]
#[cfg(feature = "unstable-client")]
mod client_ext;
#[cfg_attr(docsrs, doc(cfg(feature = "unstable-client")))]
#[cfg(feature = "unstable-client")]
pub use client_ext::scope;
mod config_ext;
pub use auth::Error as AuthError;
pub use config_ext::ConfigExt;
pub mod middleware;
pub mod retry;

#[cfg(any(feature = "rustls-tls", feature = "openssl-tls"))]
mod tls;

#[cfg(feature = "openssl-tls")]
pub use tls::openssl_tls::Error as OpensslTlsError;
#[cfg(feature = "rustls-tls")]
pub use tls::rustls_tls::Error as RustlsTlsError;
#[cfg(feature = "ws")]
mod upgrade;

#[cfg(feature = "oauth")]
#[cfg_attr(docsrs, doc(cfg(feature = "oauth")))]
pub use auth::OAuthError;

#[cfg(feature = "oidc")]
#[cfg_attr(docsrs, doc(cfg(feature = "oidc")))]
pub use auth::oidc_errors;

#[cfg(feature = "ws")]
pub use upgrade::UpgradeConnectionError;

#[cfg(feature = "kubelet-debug")]
#[cfg_attr(docsrs, doc(cfg(feature = "kubelet-debug")))]
mod kubelet_debug;

pub use builder::{ClientBuilder, DynBody};

/// Client for connecting with a Kubernetes cluster.
///
/// The easiest way to instantiate the client is either by
/// inferring the configuration from the environment using
/// [`Client::try_default`] or with an existing [`Config`]
/// using [`Client::try_from`].
#[cfg_attr(docsrs, doc(cfg(feature = "client")))]
#[derive(Clone)]
pub struct Client {
    // - `Buffer` for cheap clone
    // - `BoxFuture` for dynamic response future type
    inner: Buffer<Request<Body>, BoxFuture<'static, Result<Response<Body>, BoxError>>>,
    default_ns: String,
    valid_until: Option<Timestamp>,
}

/// Represents a WebSocket connection.
/// Value returned by [`Client::connect`].
#[cfg(feature = "ws")]
#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
pub struct Connection {
    stream: WebSocketStream<TokioIo<hyper::upgrade::Upgraded>>,
    protocol: upgrade::StreamProtocol,
}

#[cfg(feature = "ws")]
#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
impl Connection {
    /// Return true if the stream supports graceful close signaling.
    pub fn supports_stream_close(&self) -> bool {
        self.protocol.supports_stream_close()
    }

    /// Transform into the raw WebSocketStream.
    pub fn into_stream(self) -> WebSocketStream<TokioIo<hyper::upgrade::Upgraded>> {
        self.stream
    }
}

/// Constructors and low-level api interfaces.
///
/// Most users only need [`Client::try_default`] or [`Client::new`] from this block.
///
/// The many various lower level interfaces here are for more advanced use-cases with specific requirements.
impl Client {
    /// Create a [`Client`] using a custom `Service` stack.
    ///
    /// [`ConfigExt`](crate::client::ConfigExt) provides extensions for
    /// building a custom stack.
    ///
    /// To create with the default stack with a [`Config`], use
    /// [`Client::try_from`].
    ///
    /// To create with the default stack with an inferred [`Config`], use
    /// [`Client::try_default`].
    ///
    /// # Example
    ///
    /// ```rust
    /// # async fn doc() -> Result<(), Box<dyn std::error::Error>> {
    /// use kube::{client::ConfigExt, Client, Config};
    /// use tower::{BoxError, ServiceBuilder};
    /// use hyper_util::rt::TokioExecutor;
    ///
    /// let config = Config::infer().await?;
    /// let service = ServiceBuilder::new()
    ///     .layer(config.base_uri_layer())
    ///     .option_layer(config.auth_layer()?)
    ///     .map_err(BoxError::from)
    ///     .service(hyper_util::client::legacy::Client::builder(TokioExecutor::new()).build_http());
    /// let client = Client::new(service, config.default_namespace);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new<S, B, T>(service: S, default_namespace: T) -> Self
    where
        S: Service<Request<Body>, Response = Response<B>> + Send + 'static,
        S::Future: Send + 'static,
        S::Error: Into<BoxError>,
        B: http_body::Body<Data = bytes::Bytes> + Send + 'static,
        B::Error: Into<BoxError>,
        T: Into<String>,
    {
        // Transform response body to `crate::client::Body` and use type erased error to avoid type parameters.
        let service = service
            .map_response_body(Body::wrap_body)
            .map_err(Into::into)
            .boxed();
        Self {
            inner: Buffer::new(service, 1024),
            default_ns: default_namespace.into(),
            valid_until: None,
        }
    }

    /// Sets an expiration timestamp to the client, which has to be checked by the user using [`Client::valid_until`] function.
    pub fn with_valid_until(self, valid_until: Option<Timestamp>) -> Self {
        Client { valid_until, ..self }
    }

    /// Get the expiration timestamp of the client, if it has been set.
    pub fn valid_until(&self) -> &Option<Timestamp> {
        &self.valid_until
    }

    /// Create and initialize a [`Client`] using the inferred configuration.
    ///
    /// Will use [`Config::infer`] which attempts to load the local kubeconfig first,
    /// and then if that fails, trying the in-cluster environment variables.
    ///
    /// Will fail if neither configuration could be loaded.
    ///
    /// ```rust
    /// # async fn doc() -> Result<(), Box<dyn std::error::Error>> {
    /// # use kube::Client;
    /// let client = Client::try_default().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// If you already have a [`Config`] then use [`Client::try_from`](Self::try_from)
    /// instead.
    pub async fn try_default() -> Result<Self> {
        Self::try_from(Config::infer().await.map_err(Error::InferConfig)?)
    }

    /// Get the default namespace for the client
    ///
    /// The namespace is either configured on `context` in the kubeconfig,
    /// falls back to `default` when running locally,
    /// or uses the service account's namespace when deployed in-cluster.
    pub fn default_namespace(&self) -> &str {
        &self.default_ns
    }

    /// Perform a raw HTTP request against the API and return the raw response back.
    /// This method can be used to get raw access to the API which may be used to, for example,
    /// create a proxy server or application-level gateway between localhost and the API server.
    pub async fn send(&self, request: Request<Body>) -> Result<Response<Body>> {
        let mut svc = self.inner.clone();
        let res = svc
            .ready()
            .await
            .map_err(Error::Service)?
            .call(request)
            .await
            .map_err(|err| {
                // Error decorating request
                err.downcast::<Error>()
                    .map(|e| *e)
                    // Error requesting
                    .or_else(|err| err.downcast::<hyper::Error>().map(|err| Error::HyperError(*err)))
                    // Error from another middleware
                    .unwrap_or_else(Error::Service)
            })?;
        Ok(res)
    }

    /// Make WebSocket connection.
    #[cfg(feature = "ws")]
    #[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
    pub async fn connect(&self, request: Request<Vec<u8>>) -> Result<Connection> {
        use http::header::HeaderValue;
        let (mut parts, body) = request.into_parts();
        parts
            .headers
            .insert(http::header::CONNECTION, HeaderValue::from_static("Upgrade"));
        parts
            .headers
            .insert(http::header::UPGRADE, HeaderValue::from_static("websocket"));
        parts.headers.insert(
            http::header::SEC_WEBSOCKET_VERSION,
            HeaderValue::from_static("13"),
        );
        let key = tokio_tungstenite::tungstenite::handshake::client::generate_key();
        parts.headers.insert(
            http::header::SEC_WEBSOCKET_KEY,
            key.parse().expect("valid header value"),
        );
        upgrade::StreamProtocol::add_to_headers(&mut parts.headers)?;

        let res = self.send(Request::from_parts(parts, Body::from(body))).await?;
        let protocol = upgrade::verify_response(&res, &key).map_err(Error::UpgradeConnection)?;
        match hyper::upgrade::on(res).await {
            Ok(upgraded) => Ok(Connection {
                stream: WebSocketStream::from_raw_socket(
                    TokioIo::new(upgraded),
                    ws::protocol::Role::Client,
                    None,
                )
                .await,
                protocol,
            }),

            Err(e) => Err(Error::UpgradeConnection(
                UpgradeConnectionError::GetPendingUpgrade(e),
            )),
        }
    }

    /// Perform a raw HTTP request against the API and deserialize the response
    /// as JSON to some known type.
    pub async fn request<T>(&self, request: Request<Vec<u8>>) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let text = self.request_text(request).await?;

        serde_json::from_str(&text).map_err(|e| {
            tracing::warn!("{}, {:?}", text, e);
            Error::SerdeError(e)
        })
    }

    /// Perform a raw HTTP request against the API and get back the response
    /// as a string
    pub async fn request_text(&self, request: Request<Vec<u8>>) -> Result<String> {
        let res = self.send(request.map(Body::from)).await?;
        let res = handle_api_errors(res).await?;
        let body_bytes = res.into_body().collect().await?.to_bytes();
        let text = String::from_utf8(body_bytes.to_vec()).map_err(Error::FromUtf8)?;
        Ok(text)
    }

    /// Perform a raw HTTP request against the API and stream the response body.
    ///
    /// The response can be processed using [`AsyncReadExt`](futures::AsyncReadExt)
    /// and [`AsyncBufReadExt`](futures::AsyncBufReadExt).
    pub async fn request_stream(&self, request: Request<Vec<u8>>) -> Result<impl AsyncBufRead + use<>> {
        let res = self.send(request.map(Body::from)).await?;
        let res = handle_api_errors(res).await?;
        // Map the error, since we want to convert this into an `AsyncBufReader` using
        // `into_async_read` which specifies `std::io::Error` as the stream's error type.
        let body = res.into_body().into_data_stream().map_err(std::io::Error::other);
        Ok(body.into_async_read())
    }

    /// Perform a raw HTTP request against the API and get back either an object
    /// deserialized as JSON or a [`Status`] Object.
    pub async fn request_status<T>(&self, request: Request<Vec<u8>>) -> Result<Either<T, Status>>
    where
        T: DeserializeOwned,
    {
        let text = self.request_text(request).await?;
        // It needs to be JSON:
        let v: Value = serde_json::from_str(&text).map_err(Error::SerdeError)?;
        if v["kind"] == "Status" {
            tracing::trace!("Status from {}", text);
            Ok(Right(serde_json::from_str::<Status>(&text).map_err(|e| {
                tracing::warn!("{}, {:?}", text, e);
                Error::SerdeError(e)
            })?))
        } else {
            Ok(Left(serde_json::from_str::<T>(&text).map_err(|e| {
                tracing::warn!("{}, {:?}", text, e);
                Error::SerdeError(e)
            })?))
        }
    }

    /// Perform a raw request and get back a stream of [`WatchEvent`] objects
    pub async fn request_events<T>(
        &self,
        request: Request<Vec<u8>>,
    ) -> Result<impl TryStream<Item = Result<WatchEvent<T>>> + use<T>>
    where
        T: Clone + DeserializeOwned,
    {
        let res = self.send(request.map(Body::from)).await?;
        // trace!("Streaming from {} -> {}", res.url(), res.status().as_str());
        tracing::trace!("headers: {:?}", res.headers());

        let frames = FramedRead::new(
            StreamReader::new(res.into_body().into_data_stream().map_err(|e| {
                // Unexpected EOF from chunked decoder.
                // Tends to happen when watching for 300+s. This will be ignored.
                if e.to_string().contains("unexpected EOF during chunk") {
                    return std::io::Error::new(std::io::ErrorKind::UnexpectedEof, e);
                }
                std::io::Error::other(e)
            })),
            LinesCodec::new(),
        );

        Ok(frames.filter_map(|res| async {
            match res {
                Ok(line) => match serde_json::from_str::<WatchEvent<T>>(&line) {
                    Ok(event) => Some(Ok(event)),
                    Err(e) => {
                        // Ignore EOF error that can happen for incomplete line from `decode_eof`.
                        if e.is_eof() {
                            return None;
                        }

                        // Got general error response
                        if let Ok(status) = serde_json::from_str::<Status>(&line) {
                            return Some(Err(Error::Api(status.boxed())));
                        }
                        // Parsing error
                        Some(Err(Error::SerdeError(e)))
                    }
                },

                Err(LinesCodecError::Io(e)) => match e.kind() {
                    // Client timeout
                    std::io::ErrorKind::TimedOut => {
                        tracing::warn!("timeout in poll: {}", e); // our client timeout
                        None
                    }
                    // Unexpected EOF from chunked decoder.
                    // Tends to happen after 300+s of watching.
                    std::io::ErrorKind::UnexpectedEof => {
                        tracing::warn!("eof in poll: {}", e);
                        None
                    }
                    _ => Some(Err(Error::ReadEvents(e))),
                },

                // Reached the maximum line length without finding a newline.
                // This should never happen because we're using the default `usize::MAX`.
                Err(LinesCodecError::MaxLineLengthExceeded) => {
                    Some(Err(Error::LinesCodecMaxLineLengthExceeded))
                }
            }
        }))
    }
}

/// Low level discovery methods using `k8s_openapi` types.
///
/// Consider using the [`discovery`](crate::discovery) module for
/// easier-to-use variants of this functionality.
/// The following methods might be deprecated to avoid confusion between similarly named types within `discovery`.
impl Client {
    /// Returns apiserver version.
    pub async fn apiserver_version(&self) -> Result<k8s_openapi::apimachinery::pkg::version::Info> {
        self.request(Request::get("/version").body(vec![]).map_err(Error::HttpError)?)
            .await
    }

    /// Lists api groups that apiserver serves.
    pub async fn list_api_groups(&self) -> Result<k8s_meta_v1::APIGroupList> {
        self.request(Request::get("/apis").body(vec![]).map_err(Error::HttpError)?)
            .await
    }

    /// Lists resources served in given API group.
    ///
    /// ### Example usage:
    /// ```rust
    /// # async fn scope(client: kube::Client) -> Result<(), Box<dyn std::error::Error>> {
    /// let apigroups = client.list_api_groups().await?;
    /// for g in apigroups.groups {
    ///     let ver = g
    ///         .preferred_version
    ///         .as_ref()
    ///         .or_else(|| g.versions.first())
    ///         .expect("preferred or versions exists");
    ///     let apis = client.list_api_group_resources(&ver.group_version).await?;
    ///     dbg!(apis);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_api_group_resources(&self, apiversion: &str) -> Result<k8s_meta_v1::APIResourceList> {
        let url = format!("/apis/{apiversion}");
        self.request(Request::get(url).body(vec![]).map_err(Error::HttpError)?)
            .await
    }

    /// Lists versions of `core` a.k.a. `""` legacy API group.
    pub async fn list_core_api_versions(&self) -> Result<k8s_meta_v1::APIVersions> {
        self.request(Request::get("/api").body(vec![]).map_err(Error::HttpError)?)
            .await
    }

    /// Lists resources served in particular `core` group version.
    pub async fn list_core_api_resources(&self, version: &str) -> Result<k8s_meta_v1::APIResourceList> {
        let url = format!("/api/{version}");
        self.request(Request::get(url).body(vec![]).map_err(Error::HttpError)?)
            .await
    }
}

/// Aggregated Discovery API methods
///
/// These methods use the Aggregated Discovery API (available since Kubernetes 1.26, stable in 1.30)
/// to fetch all API resources in a single request, reducing the number of API calls compared to
/// the traditional discovery methods.
impl Client {
    /// Returns aggregated discovery for all API groups served at /apis.
    ///
    /// This uses the Aggregated Discovery API to fetch all non-core API groups
    /// and their resources in a single request.
    ///
    /// Requires Kubernetes 1.26+ (beta) or 1.30+ (stable).
    ///
    /// ### Example usage:
    /// ```rust,no_run
    /// # async fn scope(client: kube::Client) -> Result<(), Box<dyn std::error::Error>> {
    /// let discovery = client.list_api_groups_aggregated().await?;
    /// for group in discovery.items {
    ///     let name = group.metadata.as_ref().and_then(|m| m.name.as_ref());
    ///     println!("Group: {:?}", name);
    ///     for version in group.versions {
    ///         println!("  Version: {:?}", version.version);
    ///         for resource in version.resources {
    ///             println!("    Resource: {:?}", resource.resource);
    ///         }
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_api_groups_aggregated(&self) -> Result<APIGroupDiscoveryList> {
        self.request(
            Request::get("/apis")
                .header(http::header::ACCEPT, ACCEPT_AGGREGATED_DISCOVERY_V2)
                .body(vec![])
                .map_err(Error::HttpError)?,
        )
        .await
    }

    /// Returns aggregated discovery for core API group served at /api.
    ///
    /// This uses the Aggregated Discovery API to fetch the core API group
    /// and all its resources in a single request.
    ///
    /// Requires Kubernetes 1.26+ (beta) or 1.30+ (stable).
    ///
    /// ### Example usage:
    /// ```rust,no_run
    /// # async fn scope(client: kube::Client) -> Result<(), Box<dyn std::error::Error>> {
    /// let discovery = client.list_core_api_versions_aggregated().await?;
    /// for group in discovery.items {
    ///     for version in group.versions {
    ///         println!("Core version: {:?}", version.version);
    ///         for resource in version.resources {
    ///             println!("  Resource: {:?} (scope: {:?})", resource.resource, resource.scope);
    ///         }
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_core_api_versions_aggregated(&self) -> Result<APIGroupDiscoveryList> {
        self.request(
            Request::get("/api")
                .header(http::header::ACCEPT, ACCEPT_AGGREGATED_DISCOVERY_V2)
                .body(vec![])
                .map_err(Error::HttpError)?,
        )
        .await
    }
}

/// Kubernetes returned error handling
///
/// Either kube returned an explicit ApiError struct,
/// or it someohow returned something we couldn't parse as one.
///
/// In either case, present an ApiError upstream.
/// The latter is probably a bug if encountered.
async fn handle_api_errors(res: Response<Body>) -> Result<Response<Body>> {
    let status = res.status();
    if status.is_client_error() || status.is_server_error() {
        // trace!("Status = {:?} for {}", status, res.url());
        let body_bytes = res.into_body().collect().await?.to_bytes();
        let text = String::from_utf8(body_bytes.to_vec()).map_err(Error::FromUtf8)?;
        // Print better debug when things do fail
        // trace!("Parsing error: {}", text);
        if let Ok(status) = serde_json::from_str::<Status>(&text) {
            tracing::debug!("Unsuccessful: {status:?}");
            Err(Error::Api(status.boxed()))
        } else {
            tracing::warn!("Unsuccessful data error parse: {text}");
            let status = Status::failure(&text, "Failed to parse error data").with_code(status.as_u16());
            tracing::debug!("Unsuccessful: {status:?} (reconstruct)");
            Err(Error::Api(status.boxed()))
        }
    } else {
        Ok(res)
    }
}

impl TryFrom<Config> for Client {
    type Error = Error;

    /// Builds a default [`Client`] from a [`Config`].
    ///
    /// See [`ClientBuilder`] or [`Client::new`] if more customization is required
    fn try_from(config: Config) -> Result<Self> {
        Ok(ClientBuilder::try_from(config)?.build())
    }
}

impl TryFrom<Kubeconfig> for Client {
    type Error = Error;

    fn try_from(kubeconfig: Kubeconfig) -> Result<Self> {
        let config = Config::try_from(kubeconfig)?;
        Ok(ClientBuilder::try_from(config)?.build())
    }
}

#[cfg(test)]
mod tests {
    use std::pin::pin;

    use crate::{
        Api, Client,
        client::Body,
        config::{AuthInfo, Cluster, Context, Kubeconfig, NamedAuthInfo, NamedCluster, NamedContext},
    };

    use http::{Request, Response};
    use k8s_openapi::api::core::v1::Pod;
    use kube_core::metadata::PartialObjectMeta;
    use tower_test::mock;

    #[tokio::test]
    async fn test_default_ns() {
        let (mock_service, _) = mock::pair::<Request<Body>, Response<Body>>();
        let client = Client::new(mock_service, "test-namespace");
        assert_eq!(client.default_namespace(), "test-namespace");
    }

    #[tokio::test]
    async fn test_try_from_kubeconfig() {
        let config = Kubeconfig {
            current_context: Some("test-context".to_string()),
            auth_infos: vec![NamedAuthInfo {
                name: "test-user".to_string(),
                auth_info: Some(AuthInfo::default()), // <-- empty but valid
                ..Default::default()
            }],
            contexts: vec![NamedContext {
                name: "test-context".to_string(),
                context: Some(Context {
                    cluster: "test-cluster".to_string(),
                    user: Some("test-user".to_string()),
                    namespace: Some("test-namespace".to_string()),
                    ..Default::default()
                }),
                ..Default::default()
            }],
            clusters: vec![NamedCluster {
                name: "test-cluster".to_string(),
                cluster: Some(Cluster {
                    server: Some("http://localhost:8080".to_string()),
                    ..Default::default()
                }),
                ..Default::default()
            }],
            ..Default::default()
        };
        let client = Client::try_from(config).expect("Failed to create client from kubeconfig");
        assert_eq!(client.default_namespace(), "test-namespace");
    }

    #[tokio::test]
    async fn test_mock() {
        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
        let spawned = tokio::spawn(async move {
            // Receive a request for pod and respond with some data
            let mut handle = pin!(handle);
            let (request, send) = handle.next_request().await.expect("service not called");
            assert_eq!(request.method(), http::Method::GET);
            assert_eq!(request.uri().to_string(), "/api/v1/namespaces/default/pods/test");
            let pod: Pod = serde_json::from_value(serde_json::json!({
                "apiVersion": "v1",
                "kind": "Pod",
                "metadata": {
                    "name": "test",
                    "annotations": { "kube-rs": "test" },
                },
                "spec": {
                    "containers": [{ "name": "test", "image": "test-image" }],
                }
            }))
            .unwrap();
            send.send_response(Response::new(Body::from(serde_json::to_vec(&pod).unwrap())));
        });

        let pods: Api<Pod> = Api::default_namespaced(Client::new(mock_service, "default"));
        let pod = pods.get("test").await.unwrap();
        assert_eq!(pod.metadata.annotations.unwrap().get("kube-rs").unwrap(), "test");
        spawned.await.unwrap();
    }

    #[tokio::test]
    async fn test_partial_object_meta_get_uses_metadata_header() {
        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
        let spawned = tokio::spawn(async move {
            let mut handle = pin!(handle);
            let (request, send) = handle.next_request().await.expect("service not called");
            // Verify the metadata-only Accept header is set
            assert_eq!(
                request.headers().get(http::header::ACCEPT).unwrap(),
                "application/json;as=PartialObjectMetadata;g=meta.k8s.io;v=v1"
            );
            let pod_meta: PartialObjectMeta<Pod> =
                serde_json::from_value(serde_json::json!({
                    "apiVersion": "meta.k8s.io/v1",
                    "kind": "PartialObjectMetadata",
                    "metadata": {
                        "name": "test",
                    },
                }))
                .unwrap();
            send.send_response(Response::new(Body::from(
                serde_json::to_vec(&pod_meta).unwrap(),
            )));
        });

        let pods: Api<PartialObjectMeta<Pod>> =
            Api::default_namespaced(Client::new(mock_service, "default"));
        let pod = pods.get("test").await.unwrap();
        assert_eq!(pod.metadata.name, Some("test".to_string()));
        spawned.await.unwrap();
    }

    #[tokio::test]
    async fn test_partial_object_meta_list_uses_metadata_header() {
        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
        let spawned = tokio::spawn(async move {
            let mut handle = pin!(handle);
            let (request, send) = handle.next_request().await.expect("service not called");
            assert_eq!(
                request.headers().get(http::header::ACCEPT).unwrap(),
                "application/json;as=PartialObjectMetadataList;g=meta.k8s.io;v=v1"
            );
            send.send_response(Response::new(Body::from(
                serde_json::to_vec(&serde_json::json!({
                    "apiVersion": "meta.k8s.io/v1",
                    "kind": "PartialObjectMetadataList",
                    "metadata": { "resourceVersion": "1" },
                    "items": [],
                }))
                .unwrap(),
            )));
        });

        let pods: Api<PartialObjectMeta<Pod>> =
            Api::default_namespaced(Client::new(mock_service, "default"));
        let list = pods.list(&Default::default()).await.unwrap();
        assert_eq!(list.items.len(), 0);
        spawned.await.unwrap();
    }

    #[tokio::test]
    async fn test_partial_object_meta_patch_uses_metadata_header() {
        use kube_core::params::{Patch, PatchParams};

        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
        let spawned = tokio::spawn(async move {
            let mut handle = pin!(handle);
            let (request, send) = handle.next_request().await.expect("service not called");
            assert_eq!(request.method(), http::Method::PATCH);
            assert_eq!(
                request.headers().get(http::header::ACCEPT).unwrap(),
                "application/json;as=PartialObjectMetadata;g=meta.k8s.io;v=v1"
            );
            send.send_response(Response::new(Body::from(
                serde_json::to_vec(&serde_json::json!({
                    "apiVersion": "meta.k8s.io/v1",
                    "kind": "PartialObjectMetadata",
                    "metadata": { "name": "test" },
                }))
                .unwrap(),
            )));
        });

        let pods: Api<PartialObjectMeta<Pod>> =
            Api::default_namespaced(Client::new(mock_service, "default"));
        let patch = Patch::Merge(serde_json::json!({ "metadata": { "labels": { "a": "b" } } }));
        let pod = pods.patch("test", &PatchParams::default(), &patch).await.unwrap();
        assert_eq!(pod.metadata.name, Some("test".to_string()));
        spawned.await.unwrap();
    }

    #[tokio::test]
    async fn test_partial_object_meta_watch_uses_metadata_header() {
        let (mock_service, handle) = mock::pair::<Request<Body>, Response<Body>>();
        let spawned = tokio::spawn(async move {
            let mut handle = pin!(handle);
            let (request, send) = handle.next_request().await.expect("service not called");
            assert_eq!(
                request.headers().get(http::header::ACCEPT).unwrap(),
                "application/json;as=PartialObjectMetadata;g=meta.k8s.io;v=v1"
            );
            // Send an empty response to close the stream
            send.send_response(Response::new(Body::from(vec![])));
        });

        let pods: Api<PartialObjectMeta<Pod>> =
            Api::default_namespaced(Client::new(mock_service, "default"));
        let _ = pods.watch(&Default::default(), "0").await;
        spawned.await.unwrap();
    }
}