Skip to content

Commit

Permalink
Rename Converter -> Conversion
Browse files Browse the repository at this point in the history
Signed-off-by: Mikail Bagishov <bagishov.mikail@yandex.ru>
  • Loading branch information
MikailBag committed Aug 31, 2022
1 parent c7ed5b2 commit 4113a0b
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 44 deletions.
8 changes: 4 additions & 4 deletions examples/crd_derive_multi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use k8s_openapi::{
use kube::{
api::{Api, Patch, PatchParams},
core::{
conversion::{ConversionHandler, StarConverter},
conversion::{ConversionHandler, StarConversion},
crd::merge_crds,
},
runtime::wait::{await_condition, conditions},
Expand Down Expand Up @@ -120,11 +120,11 @@ mod conversion {

// this function actually implements conversion service
async fn run_conversion_webhook() {
let star_converter = StarConverter::builder()
let star_conversion = StarConversion::builder()
.add_ray(conversion::RayV1)
.add_ray(conversion::RayV2)
.build();
let handler = ConversionHandler::new(star_converter);
let handler = ConversionHandler::new(star_conversion);

let routes = warp::path("convert")
.and(warp::body::json())
Expand Down Expand Up @@ -253,7 +253,7 @@ async fn main() -> anyhow::Result<()> {
// here we use `migrate_resources` utility function to migrate all previously stored objects.
info!("Running storage migration");
let crds: Api<CustomResourceDefinition> = Api::all(client.clone());
crds.migrate_resources(&crd2.name_unchecked());
crds.migrate_resources(&crd2.name_unchecked()).await?;
// and now we can apply CRD again without specifying v1, completely removing it.
info!("Removing v1");
all_crds.remove(0);
Expand Down
32 changes: 16 additions & 16 deletions kube-core/src/conversion.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
//! Contains utilities for implements custom resource conversion webhooks.
//! Abstractions in this module and its submodules may be ordered:
//! - `low_level` submodule contains raw typings, allowing for full control (probably you don't need these unless you are implementing your own apiserver).
//! - `Converter` together with `ConversionHandler` are middle ground: they abstract you from low-level details but not require particular conversion strategy.
//! - `StarConverter` is opinionated strategy, where all conversions are done using intermediate unversioned representation as a middle point.
//! - `Conversion` together with `ConversionHandler` are middle ground: they abstract you from low-level details but not require particular conversion strategy.
//! - `StarConversion` is opinionated strategy, where all conversions are done using intermediate unversioned representation as a middle point.
//! Third option is preferred - this is how Kubernetes implements versioning and convertion for builtin APIs.

use std::sync::Arc;
Expand All @@ -11,22 +11,22 @@ use self::low_level::{ConversionRequest, ConversionResponse, ConversionReview};

/// Defines low-level typings.
pub mod low_level;
/// High-level easy-to-use converter.
/// High-level easy-to-use conversion.
mod star;

pub use star::{StarConverter, StarConverterBuilder, StarRay};
pub use star::{StarConversion, StarConversionBuilder, StarRay};

/// Helper which implements low-level API based on the provided converter.
#[derive(Clone)]
pub struct ConversionHandler {
converter: Arc<dyn Converter + Send + Sync>,
conversion: Arc<dyn Conversion + Send + Sync>,
}

impl ConversionHandler {
/// Creates new `ConversionHandler` which will use given `converter` for operation.
pub fn new<C: Converter + Send + Sync + 'static>(converter: C) -> Self {
/// Creates new `ConversionHandler` which will use given `conversion` for operation.
pub fn new<C: Conversion + Send + Sync + 'static>(conversion: C) -> Self {
ConversionHandler {
converter: Arc::new(converter),
conversion: Arc::new(conversion),
}
}

Expand All @@ -45,7 +45,7 @@ impl ConversionHandler {
let mut converted_objects = Vec::new();
let input_objects = std::mem::take(&mut req.objects);
for (idx, object) in input_objects.into_iter().enumerate() {
match self.converter.convert(object, &req.desired_api_version) {
match self.conversion.convert(object, &req.desired_api_version) {
Ok(c) => converted_objects.push(c),
Err(error) => {
let msg = format!("Conversion of object {} failed: {}", idx, error);
Expand All @@ -57,10 +57,10 @@ impl ConversionHandler {
}
}

/// Converter is entity which supports all `N*(N-1)` possible conversion directions.
/// Conversion is entity which supports all `N*(N-1)` possible conversion directions.
/// This trait does not specify strategy used. You may implement this trait yourself
/// or use [`StarConverter`](StarConverter).
pub trait Converter {
/// or use [`StarConversion`](StarConversion).
pub trait Conversion {
/// Actually performs conversion.
/// # Requirements
/// All metadata fields except labels and annotations must not be mutated.
Expand All @@ -80,11 +80,11 @@ mod tests {

use super::{
low_level::{ConversionRequest, ConversionReview, META_API_VERSION_V1, META_KIND},
ConversionHandler, Converter,
Conversion, ConversionHandler,
};

struct NoopConverter;
impl Converter for NoopConverter {
struct NoopConversion;
impl Conversion for NoopConversion {
fn convert(
&self,
object: serde_json::Value,
Expand All @@ -102,7 +102,7 @@ mod tests {
let obj2 = serde_json::json!({
"bar": 6
});
let handler = ConversionHandler::new(NoopConverter);
let handler = ConversionHandler::new(NoopConversion);

let input = ConversionReview {
types: crate::TypeMeta {
Expand Down
48 changes: 24 additions & 24 deletions kube-core/src/conversion/star.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,25 @@ use serde::{de::DeserializeOwned, Serialize};

use crate::Resource;

use super::Converter;
use super::Conversion;

/// StarConverter is opinionated easy-to-use Converter implementation.
/// StarConversion is opinionated easy-to-use Conversion implementation.
///
/// # Semantics
/// StarConverter assumes both unversioned and all versioned representations are logically equivalent, and each version can be
/// StarConversion assumes both unversioned and all versioned representations are logically equivalent, and each version can be
/// converted to and from unversioned representation without loss of data. If you cannot satisfy this requirement,
/// you may need to implement `Converter` directly instead to minimize data loss.
/// you may need to implement `Conversion` directly instead to minimize data loss.
///
/// It then implements `Converter` contract by converting input object to the unversioned representation at first,
/// It then implements `Conversion` contract by converting input object to the unversioned representation at first,
/// and then converting this representation to the desired version.
pub struct StarConverter {
pub struct StarConversion {
rays: Vec<Box<dyn ErasedStarRay + Send + Sync + 'static>>,
}

impl StarConverter {
impl StarConversion {
/// Creates new builder.
pub fn builder<U>() -> StarConverterBuilder<U> {
StarConverterBuilder {
pub fn builder<U>() -> StarConversionBuilder<U> {
StarConversionBuilder {
marker: PhantomData,
rays: Vec::new(),
}
Expand Down Expand Up @@ -55,7 +55,7 @@ impl StarConverter {
}
}

impl Converter for StarConverter {
impl Conversion for StarConversion {
fn convert(
&self,
object: serde_json::Value,
Expand All @@ -74,14 +74,14 @@ impl Converter for StarConverter {
}
}

/// Simple builder for the `StarConverter`.
/// Simple builder for the `StarConversion`.
/// `I` is type of the IR.
pub struct StarConverterBuilder<U> {
pub struct StarConversionBuilder<U> {
marker: PhantomData<fn(U) -> U>,
rays: Vec<Box<dyn ErasedStarRay + Send + Sync + 'static>>,
}

impl<U: 'static> StarConverterBuilder<U> {
impl<U: 'static> StarConversionBuilder<U> {
/// Registers new ray of the star.
/// # Panics
/// This method panics if another ray was added for the same api version.
Expand Down Expand Up @@ -112,9 +112,9 @@ impl<U: 'static> StarConverterBuilder<U> {
self
}

/// Finalizes construction and returns `StarConverter` instance
pub fn build(self) -> StarConverter {
StarConverter { rays: self.rays }
/// Finalizes construction and returns `StarConversion` instance
pub fn build(self) -> StarConversion {
StarConversion { rays: self.rays }
}
}

Expand All @@ -135,7 +135,7 @@ impl<T: StarRay> ErasedStarRay for ErasedStarRayImpl<T> {
}

fn from_ur(&self, unversioned: Box<dyn Any>) -> Result<serde_json::Value, String> {
// StarConverterBuilder enforces at compile-time that downcast will work.
// StarConversionBuilder enforces at compile-time that downcast will work.
let unversioned = unversioned.downcast().expect("invalid input");
let versioned = self.0.from_unversioned(*unversioned)?;
serde_json::to_value(versioned).map_err(|err| format!("Failed to serialize object: {}", err))
Expand All @@ -146,7 +146,7 @@ impl<T: StarRay> ErasedStarRay for ErasedStarRayImpl<T> {
}
}

/// Helper trait for the `StarConverter`.
/// Helper trait for the `StarConversion`.
/// # Errors
/// While the signature allows returning errors, it is discouraged.
/// Ideally, conversion should always succeed.
Expand All @@ -166,9 +166,9 @@ pub trait StarRay: Send + Sync + 'static {
mod tests {
use serde::{Deserialize, Serialize};

use crate::{conversion::Converter, TypeMeta};
use crate::{conversion::Conversion, TypeMeta};

use super::{StarConverter, StarRay};
use super::{StarConversion, StarRay};

#[derive(Serialize, Deserialize)]
struct V1 {
Expand Down Expand Up @@ -226,8 +226,8 @@ mod tests {
}

#[test]
fn test_star_converter_works() {
let converter = StarConverter::builder()
fn test_star_conversion_works() {
let converter = StarConversion::builder()
.add_ray_with_version(Ray1, "foo/v1")
.add_ray_with_version(Ray2, "foo/v2")
.build();
Expand All @@ -252,8 +252,8 @@ mod tests {

#[test]
#[should_panic]
fn test_star_converter_panics_when_versions_are_duplicated() {
StarConverter::builder()
fn test_star_conversion_panics_when_versions_are_duplicated() {
StarConversion::builder()
.add_ray_with_version(Ray1, "foo/v1")
.add_ray_with_version(Ray2, "foo/v1");
}
Expand Down

0 comments on commit 4113a0b

Please sign in to comment.