Skip to content

Commit

Permalink
fix: type changes
Browse files Browse the repository at this point in the history
  • Loading branch information
pratikmishra356 committed Feb 21, 2025
1 parent 4cbff15 commit eb9cbf8
Show file tree
Hide file tree
Showing 20 changed files with 223 additions and 288 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion crates/context_aware_config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ edition = "2021"
actix-http = "3.3.1"
actix-web = { workspace = true }
anyhow = { workspace = true }
base64 = { workspace = true }
bigdecimal = { workspace = true }
blake3 = "1.3.3"
cac_client = { path = "../cac_client" }
Expand Down
25 changes: 20 additions & 5 deletions crates/context_aware_config/src/api/context/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
extern crate base64;

use std::{cmp::min, collections::HashSet};

#[cfg(feature = "high-performance-mode")]
Expand Down Expand Up @@ -83,7 +81,7 @@ async fn put_handler(

let put_response = operations::put(
Json(req.into_inner()),
description.clone(),
description,
transaction_conn,
true,
&user,
Expand Down Expand Up @@ -438,7 +436,7 @@ async fn bulk_operations(

let description = if put_req.description.is_none() {
query_description(
ctx_condition_value.clone(),
ctx_condition_value,
transaction_conn,
&schema_name,
)?
Expand Down Expand Up @@ -471,8 +469,25 @@ async fn bulk_operations(
response.push(ContextBulkResponse::Put(put_resp));
}
ContextAction::Replace(put_req) => {
let ctx_condition = put_req.context.to_owned().into_inner();
let ctx_condition_value =
Value::Object(ctx_condition.clone().into());
let description = if put_req.description.is_none() {
query_description(
ctx_condition_value,
transaction_conn,
&schema_name,
)?
} else {
put_req
.description
.clone()
.expect("Description should not be empty")
};

let put_resp = operations::put(
Json(put_req.clone()),
description.clone(),
transaction_conn,
true,
&user,
Expand All @@ -487,7 +502,7 @@ async fn bulk_operations(
err
})?;

all_descriptions.push(put_resp.description.clone());
all_descriptions.push(description);
all_change_reasons.push(put_req.change_reason.clone());
response.push(ContextBulkResponse::Replace(put_resp));
}
Expand Down
13 changes: 1 addition & 12 deletions crates/context_aware_config/src/api/context/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
extern crate base64;

use std::collections::HashMap;
use std::str;

use actix_web::web::Json;
use base64::prelude::*;
use cac_client::utils::json_to_sorted_string;
use chrono::Utc;
use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl, SelectableHelper};
Expand Down Expand Up @@ -161,15 +158,7 @@ pub fn validate_value_with_function(
key: &String,
value: &Value,
) -> superposition::Result<()> {
let base64_decoded = BASE64_STANDARD.decode(function).map_err(|err| {
log::error!("Failed to decode function code: {}", err);
unexpected_error!("Failed to decode function code: {}", err)
})?;
let utf8_decoded = str::from_utf8(&base64_decoded).map_err(|err| {
log::error!("Failed to parse function code in UTF-8: {}", err);
unexpected_error!("Failed to parse function code in UTF-8: {}", err)
})?;
if let Err((err, stdout)) = execute_fn(utf8_decoded, key, value.to_owned()) {
if let Err((err, stdout)) = execute_fn(function, key, value.to_owned()) {
let stdout = stdout.unwrap_or(String::new());
log::error!("function validation failed for {key} with error: {err}");
return Err(validation_error!(
Expand Down
13 changes: 6 additions & 7 deletions crates/context_aware_config/src/api/default_config/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
extern crate base64;

use actix_web::{
delete, get, post, put,
web::{self, Data, Json, Path, Query},
Expand Down Expand Up @@ -30,7 +28,7 @@ use crate::helpers::put_config_in_redis;
use crate::{
api::{
context::helpers::validate_value_with_function,
default_config::types::{DefaultConfigKey, UpdateReqChangeset},
default_config::types::DefaultConfigKey,
functions::helpers::get_published_function_code,
},
helpers::add_config_version,
Expand Down Expand Up @@ -188,7 +186,6 @@ async fn update_default_config(
let schema = req
.schema
.clone()
.map(Value::Object)
.unwrap_or_else(|| existing.schema.clone());

let jschema = JSONSchema::options()
Expand All @@ -210,10 +207,12 @@ async fn update_default_config(
));
}

let function_name = req
let function_name: Option<String> = req
.function_name
.clone()
.map_or_else(|| existing.function_name.clone(), |f| f.to_option());
.map_or(existing.function_name.clone().into(), |val| {
Into::<Option<String>>::into(val)
});

if let Err(e) = validate_and_get_function_code(
&mut conn,
Expand All @@ -231,7 +230,7 @@ async fn update_default_config(
let val = diesel::update(dsl::default_configs)
.filter(dsl::key.eq(key_str.clone()))
.set((
UpdateReqChangeset::from(req),
req,
dsl::last_modified_at.eq(Utc::now().naive_utc()),
dsl::last_modified_by.eq(user.get_email()),
))
Expand Down
32 changes: 5 additions & 27 deletions crates/context_aware_config/src/api/default_config/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use diesel::AsChangeset;
use serde::{Deserialize, Deserializer};
use serde_json::{Map, Value};
use superposition_types::{
api::function::FunctionNameEnum, database::schema::default_configs, RegexEnum,
database::models::cac::deserialize_function_name, database::schema::default_configs,
RegexEnum,
};

#[derive(Debug, Deserialize)]
Expand All @@ -16,36 +17,13 @@ pub struct CreateReq {
pub change_reason: String,
}

#[derive(Debug, Deserialize)]
#[derive(Debug, Deserialize, AsChangeset)]
#[diesel(table_name = default_configs)]
pub struct UpdateReq {
#[serde(default, deserialize_with = "deserialize_option")]
pub value: Option<Value>,
pub schema: Option<Map<String, Value>>,
pub function_name: Option<FunctionNameEnum>,
pub description: Option<String>,
pub change_reason: String,
}

impl From<UpdateReq> for UpdateReqChangeset {
fn from(req: UpdateReq) -> Self {
Self {
value: req.value,
schema: req.schema.map(Value::Object),
function_name: req.function_name.map(|x| x.to_option()),
description: req.description,
change_reason: req.change_reason,
}
}
}

//changeset type for update request type
#[derive(AsChangeset)]
#[diesel(table_name = default_configs)]
pub struct UpdateReqChangeset {
pub value: Option<Value>,
pub schema: Option<Value>,
//function_name is nullable column, so to support null update with changeset
//we had to make it Option<Option<String>>
#[serde(deserialize_with = "deserialize_function_name")]
pub function_name: Option<Option<String>>,
pub description: Option<String>,
pub change_reason: String,
Expand Down
26 changes: 13 additions & 13 deletions crates/context_aware_config/src/api/dimension/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
extern crate base64;

use actix_web::{
delete, get, post, put,
web::{self, Data, Json, Path, Query},
Expand All @@ -14,16 +12,19 @@ use superposition_macros::{bad_argument, db_error, not_found, unexpected_error};
use superposition_types::{
custom_query::PaginationParams,
database::{
models::{cac::Dimension, Workspace},
models::{
cac::{Dimension, Position},
Workspace,
},
schema::dimensions::{self, dsl::*},
types::DimensionWithMandatory,
},
result as superposition, PaginatedResponse, Position, User,
result as superposition, PaginatedResponse, User,
};

use crate::{
api::dimension::{
types::{CreateReq, UpdateReqChangeset},
types::CreateReq,
utils::{get_dimension_usage_context_ids, validate_dimension_position},
},
helpers::{get_workspace, validate_jsonschema},
Expand Down Expand Up @@ -83,7 +84,7 @@ async fn create(

conn.transaction::<_, superposition::AppError, _>(|transaction_conn| {
diesel::update(dimensions::table)
.filter(dimensions::position.ge(dimension_data.position.clone()))
.filter(dimensions::position.ge(dimension_data.position))
.set((
last_modified_at.eq(Utc::now().naive_utc()),
last_modified_by.eq(user.get_email()),
Expand Down Expand Up @@ -115,11 +116,12 @@ async fn create(
diesel::result::DatabaseErrorKind::ForeignKeyViolation,
e,
)) => {
let fun_name = create_req.function_name;
let fun_name = create_req.function_name.clone();
log::error!("{fun_name:?} function not found with error: {e:?}");
Err(bad_argument!(
"Function {} doesn't exists",
fun_name.unwrap_or_default()
Into::<Option<String>>::into(create_req.function_name.clone())
.unwrap_or(String::new())
))
}
Err(e) => {
Expand Down Expand Up @@ -158,17 +160,16 @@ async fn update(
db_error!(err)
})?;

let mut update_req = req.into_inner();
let update_req = req.into_inner();

if let Some(schema_value) = update_req.schema.clone() {
validate_jsonschema(&state.meta_schema, &schema_value)?;
}

let result =
conn.transaction::<_, superposition::AppError, _>(|transaction_conn| {
let mut new_position = existing_position.clone();
if let Some(position_val) = update_req.position.clone() {
new_position = position_val.clone();
let new_position = position_val.clone();
validate_dimension_position(
path.into_inner(),
position_val,
Expand Down Expand Up @@ -213,11 +214,10 @@ async fn update(
.execute(transaction_conn)?
};
}
update_req.position = Some(new_position.clone());
diesel::update(dimensions)
.filter(dsl::dimension.eq(name))
.set((
UpdateReqChangeset::from(update_req),
update_req,
dimensions::last_modified_at.eq(Utc::now().naive_utc()),
dimensions::last_modified_by.eq(user.get_email()),
))
Expand Down
33 changes: 6 additions & 27 deletions crates/context_aware_config/src/api/dimension/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ use diesel::AsChangeset;
use serde::Deserialize;
use serde_json::Value;
use superposition_types::{
api::function::FunctionNameEnum, database::schema::dimensions, Position, RegexEnum,
database::models::cac::{deserialize_function_name, Position},
database::schema::dimensions,
RegexEnum,
};

#[derive(Debug, Deserialize)]
Expand All @@ -16,35 +18,12 @@ pub struct CreateReq {
pub change_reason: String,
}

#[derive(Debug, Deserialize, Clone)]
#[derive(Debug, Deserialize, Clone, AsChangeset)]
#[diesel(table_name = dimensions)]
pub struct UpdateReq {
pub position: Option<Position>,
pub schema: Option<Value>,
pub function_name: Option<FunctionNameEnum>,
pub description: Option<String>,
pub change_reason: String,
}

impl From<UpdateReq> for UpdateReqChangeset {
fn from(req: UpdateReq) -> Self {
Self {
position: req.position.map(|x| x.into()),
schema: req.schema,
function_name: req.function_name.map(|x| x.to_option()),
description: req.description,
change_reason: req.change_reason,
}
}
}

//changeset type for update request type
#[derive(AsChangeset)]
#[diesel(table_name = dimensions)]
pub struct UpdateReqChangeset {
pub position: Option<i32>,
pub schema: Option<Value>,
//function_name is nullable column, so to support null update with changeset
//we had to make it Option<Option<String>>
#[serde(default, deserialize_with = "deserialize_function_name")]
pub function_name: Option<Option<String>>,
pub description: Option<String>,
pub change_reason: String,
Expand Down
4 changes: 2 additions & 2 deletions crates/context_aware_config/src/api/dimension/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ use std::collections::HashMap;
use superposition_macros::{bad_argument, db_error, unexpected_error};
use superposition_types::{
database::{
models::cac::{Context, Dimension},
models::cac::{Context, Dimension, Position},
schema::{contexts::dsl::contexts, dimensions::dsl::*},
},
result as superposition, Cac, Condition, DBConnection, Position,
result as superposition, Cac, Condition, DBConnection,
};

use super::types::DimensionName;
Expand Down
Loading

0 comments on commit eb9cbf8

Please sign in to comment.