Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Project Neokubism #594

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 6 additions & 9 deletions kube-core/src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,8 @@ use std::borrow::Cow;
/// and is generally produced from list/watch/delete collection queries on an [`Resource`](super::Resource).
///
/// This is almost equivalent to [`k8s_openapi::List<T>`](k8s_openapi::List), but iterable.
#[derive(Deserialize, Debug)]
pub struct ObjectList<T>
where
T: Clone,
{
#[derive(Clone, Deserialize, Debug)]
pub struct ObjectList<T> {
// NB: kind and apiVersion can be set here, but no need for it atm
/// ListMeta - only really used for its `resourceVersion`
///
Expand All @@ -32,7 +29,7 @@ where
pub items: Vec<T>,
}

impl<T: Clone> ObjectList<T> {
impl<T> ObjectList<T> {
/// `iter` returns an Iterator over the elements of this ObjectList
///
/// # Example
Expand Down Expand Up @@ -75,7 +72,7 @@ impl<T: Clone> ObjectList<T> {
}
}

impl<T: Clone> IntoIterator for ObjectList<T> {
impl<T> IntoIterator for ObjectList<T> {
type IntoIter = ::std::vec::IntoIter<Self::Item>;
type Item = T;

Expand All @@ -84,7 +81,7 @@ impl<T: Clone> IntoIterator for ObjectList<T> {
}
}

impl<'a, T: Clone> IntoIterator for &'a ObjectList<T> {
impl<'a, T> IntoIterator for &'a ObjectList<T> {
type IntoIter = ::std::slice::Iter<'a, T>;
type Item = &'a T;

Expand All @@ -93,7 +90,7 @@ impl<'a, T: Clone> IntoIterator for &'a ObjectList<T> {
}
}

impl<'a, T: Clone> IntoIterator for &'a mut ObjectList<T> {
impl<'a, T> IntoIterator for &'a mut ObjectList<T> {
type IntoIter = ::std::slice::IterMut<'a, T>;
type Item = &'a mut T;

Expand Down
2 changes: 1 addition & 1 deletion kube-core/src/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub trait Resource {
/// as type of this information.
///
/// See [`DynamicObject`](crate::dynamic::DynamicObject) for a valid implementation of non-k8s-openapi resources.
type DynamicType: Send + Sync + 'static;
type DynamicType: Clone + Send + Sync + 'static;

/// Returns kind of this object
fn kind(dt: &Self::DynamicType) -> Cow<'_, str>;
Expand Down
2 changes: 2 additions & 0 deletions kube/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ tame-oauth = { version = "0.4.7", features = ["gcp"], optional = true }
pin-project = { version = "1.0.4", optional = true }
rand = { version = "0.8.3", optional = true }
tracing = { version = "0.1.25", features = ["log"], optional = true }
snafu = "0.6.10"
form_urlencoded = "1.0.1"

[dependencies.k8s-openapi]
version = "0.12.0"
Expand Down
122 changes: 85 additions & 37 deletions kube/src/api/core_methods.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
use either::Either;
use futures::Stream;
use futures::{Stream, TryStreamExt};
use serde::{de::DeserializeOwned, Serialize};
use std::fmt::Debug;
use std::{fmt::Debug, time::Duration};

use crate::{api::Api, Result};
use kube_core::{object::ObjectList, params::*, response::Status, WatchEvent};
use crate::{
api::Api,
client::verb::{self, Create, Delete, DeleteCollection, Get, List, Query, Replace, Watch},
Result,
};
use kube_core::{object::ObjectList, params::*, response::Status, Resource, WatchEvent};

/// PUSH/PUT/POST/GET abstractions
impl<K> Api<K>
where
K: Clone + DeserializeOwned + Debug,
K: Clone + DeserializeOwned + Debug + Resource,
{
/// Get a named resource
///
Expand All @@ -25,9 +29,14 @@ where
/// }
/// ```
pub async fn get(&self, name: &str) -> Result<K> {
let mut req = self.request.get(name)?;
req.extensions_mut().insert("get");
self.client.request::<K>(req).await
Ok(self
.client
.call(Get {
name,
scope: &self.scope,
dyn_type: &self.dyn_type,
})
.await?)
}

/// Get a list of resources
Expand All @@ -49,9 +58,16 @@ where
/// }
/// ```
pub async fn list(&self, lp: &ListParams) -> Result<ObjectList<K>> {
let mut req = self.request.list(lp)?;
req.extensions_mut().insert("list");
self.client.request::<ObjectList<K>>(req).await
Ok(self
.client
.call(List {
scope: &self.scope,
dyn_type: &self.dyn_type,
query: &Query::from_list_params(lp),
limit: lp.limit,
continue_token: lp.continue_token.as_deref(),
})
.await?)
}

/// Create a resource
Expand All @@ -74,10 +90,14 @@ where
where
K: Serialize,
{
let bytes = serde_json::to_vec(&data)?;
let mut req = self.request.create(pp, bytes)?;
req.extensions_mut().insert("create");
self.client.request::<K>(req).await
Ok(self
.client
.call(Create::<K, _> {
object: &data,
scope: &self.scope,
dyn_type: &self.dyn_type,
})
.await?)
}

/// Delete a named resource
Expand All @@ -103,9 +123,15 @@ where
/// }
/// ```
pub async fn delete(&self, name: &str, dp: &DeleteParams) -> Result<Either<K, Status>> {
let mut req = self.request.delete(name, dp)?;
req.extensions_mut().insert("delete");
self.client.request_status::<K>(req).await
Ok(self
.client
.call(Delete::<K, _> {
name,
scope: &self.scope,
dyn_type: &self.dyn_type,
})
.await?)
.map(Either::Left)
}

/// Delete a collection of resources
Expand Down Expand Up @@ -140,9 +166,14 @@ where
dp: &DeleteParams,
lp: &ListParams,
) -> Result<Either<ObjectList<K>, Status>> {
let mut req = self.request.delete_collection(dp, lp)?;
req.extensions_mut().insert("delete_collection");
self.client.request_status::<ObjectList<K>>(req).await
Ok(self
.client
.call(DeleteCollection::<K, _> {
scope: &self.scope,
dyn_type: &self.dyn_type,
})
.await?)
.map(Either::Left)
}

/// Patch a subset of a resource's properties
Expand Down Expand Up @@ -174,15 +205,20 @@ where
/// ```
/// [`Patch`]: super::Patch
/// [`PatchParams`]: super::PatchParams
pub async fn patch<P: Serialize + Debug>(
&self,
name: &str,
pp: &PatchParams,
patch: &Patch<P>,
) -> Result<K> {
let mut req = self.request.patch(name, pp, patch)?;
req.extensions_mut().insert("patch");
self.client.request::<K>(req).await
pub async fn patch(&self, name: &str, pp: &PatchParams, patch: &Patch<K>) -> Result<K>
where
K: Serialize,
Patch<K>: Serialize,
{
Ok(self
.client
.call(verb::Patch::<K, _> {
name,
scope: &self.scope,
dyn_type: &self.dyn_type,
patch,
})
.await?)
}

/// Replace a resource entirely with a new one
Expand Down Expand Up @@ -233,10 +269,14 @@ where
where
K: Serialize,
{
let bytes = serde_json::to_vec(&data)?;
let mut req = self.request.replace(name, pp, bytes)?;
req.extensions_mut().insert("replace");
self.client.request::<K>(req).await
Ok(self
.client
.call(Replace::<K, _> {
scope: &self.scope,
dyn_type: &self.dyn_type,
object: data,
})
.await?)
}

/// Watch a list of resources
Expand Down Expand Up @@ -281,8 +321,16 @@ where
lp: &ListParams,
version: &str,
) -> Result<impl Stream<Item = Result<WatchEvent<K>>>> {
let mut req = self.request.watch(lp, version)?;
req.extensions_mut().insert("watch");
self.client.request_events::<K>(req).await
Ok(self
.client
.call(Watch::<K, _> {
scope: &self.scope,
dyn_type: &self.dyn_type,
query: &Query::from_list_params(lp),
version,
timeout: lp.timeout.map(|timeout| Duration::from_secs(timeout.into())),
})
.await?
.err_into())
}
}
60 changes: 26 additions & 34 deletions kube/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ mod core_methods;
mod subresource;
#[cfg(feature = "ws")]
#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
pub use subresource::{AttachParams, Attach, Execute};
pub use subresource::{EvictParams, Evict, LogParams, Log, ScaleSpec, ScaleStatus};
pub use subresource::{Attach, AttachParams, Execute};
pub use subresource::{Evict, EvictParams, Log, LogParams, ScaleSpec, ScaleStatus};

// Re-exports from kube-core
#[cfg(feature = "admission")]
Expand All @@ -29,17 +29,22 @@ pub use params::{
DeleteParams, ListParams, Patch, PatchParams, PostParams, Preconditions, PropagationPolicy,
};

use crate::Client;
use crate::{
client::scope::{ClusterScope, DynamicScope, NamespaceScope},
Client,
};
/// The generic Api abstraction
///
/// This abstracts over a [`Request`] and a type `K` so that
/// we get automatic serialization/deserialization on the api calls
/// implemented by the dynamic [`Resource`].
#[cfg_attr(docsrs, doc(cfg(feature = "client")))]
#[derive(Clone)]
pub struct Api<K> {
pub struct Api<K: Resource> {
/// The request builder object with its resource dependent url
pub(crate) request: Request,
pub(crate) scope: DynamicScope,
pub(crate) dyn_type: K::DynamicType,
/// The client to use (from this library)
pub(crate) client: Client,
/// Note: Using `iter::Empty` over `PhantomData`, because we never actually keep any
Expand All @@ -55,10 +60,12 @@ impl<K: Resource> Api<K> {
/// Cluster level resources, or resources viewed across all namespaces
///
/// This function accepts `K::DynamicType` so it can be used with dynamic resources.
pub fn all_with(client: Client, dyntype: &K::DynamicType) -> Self {
let url = K::url_path(dyntype, None);
pub fn all_with(client: Client, dyn_type: &K::DynamicType) -> Self {
let url = K::url_path(dyn_type, None);
Self {
client,
scope: DynamicScope::Cluster(ClusterScope),
dyn_type: dyn_type.clone(),
request: Request::new(url),
phantom: std::iter::empty(),
}
Expand All @@ -67,10 +74,14 @@ impl<K: Resource> Api<K> {
/// Namespaced resource within a given namespace
///
/// This function accepts `K::DynamicType` so it can be used with dynamic resources.
pub fn namespaced_with(client: Client, ns: &str, dyntype: &K::DynamicType) -> Self {
let url = K::url_path(dyntype, Some(ns));
pub fn namespaced_with(client: Client, ns: &str, dyn_type: &K::DynamicType) -> Self {
let url = K::url_path(dyn_type, Some(ns));
Self {
client,
scope: DynamicScope::Namespace(NamespaceScope {
namespace: ns.to_string(),
}),
dyn_type: dyn_type.clone(),
request: Request::new(url),
phantom: std::iter::empty(),
}
Expand All @@ -82,13 +93,9 @@ impl<K: Resource> Api<K> {
///
/// Unless configured explicitly, the default namespace is either "default"
/// out of cluster, or the service account's namespace in cluster.
pub fn default_namespaced_with(client: Client, dyntype: &K::DynamicType) -> Self {
let url = K::url_path(dyntype, Some(client.default_ns()));
Self {
client,
request: Request::new(url),
phantom: std::iter::empty(),
}
pub fn default_namespaced_with(client: Client, dyn_type: &K::DynamicType) -> Self {
let ns = client.default_ns().to_string();
Self::namespaced_with(client, &ns, dyn_type)
}

/// Consume self and return the [`Client`]
Expand All @@ -112,39 +119,24 @@ where
{
/// Cluster level resources, or resources viewed across all namespaces
pub fn all(client: Client) -> Self {
let url = K::url_path(&Default::default(), None);
Self {
client,
request: Request::new(url),
phantom: std::iter::empty(),
}
Self::all_with(client, &K::DynamicType::default())
}

/// Namespaced resource within a given namespace
pub fn namespaced(client: Client, ns: &str) -> Self {
let url = K::url_path(&Default::default(), Some(ns));
Self {
client,
request: Request::new(url),
phantom: std::iter::empty(),
}
Self::namespaced_with(client, ns, &K::DynamicType::default())
}

/// Namespaced resource within the default namespace
///
/// Unless configured explicitly, the default namespace is either "default"
/// out of cluster, or the service account's namespace in cluster.
pub fn default_namespaced(client: Client) -> Self {
let url = K::url_path(&Default::default(), Some(client.default_ns()));
Self {
client,
request: Request::new(url),
phantom: std::iter::empty(),
}
Self::default_namespaced_with(client, &K::DynamicType::default())
}
}

impl<K> From<Api<K>> for Client {
impl<K: Resource> From<Api<K>> for Client {
fn from(api: Api<K>) -> Self {
api.client
}
Expand Down
Loading