Skip to content

Commit

Permalink
feat: Use Common db model types in frontend (#291)
Browse files Browse the repository at this point in the history
  • Loading branch information
ayushjain17 authored Dec 17, 2024
1 parent 626b1e3 commit f4301d8
Show file tree
Hide file tree
Showing 47 changed files with 506 additions and 678 deletions.
1 change: 1 addition & 0 deletions 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 @@ -33,7 +33,6 @@ superposition_macros = { path = "../superposition_macros" }
superposition_types = { path = "../superposition_types", features = [
"result",
"diesel_derives",
"server",
] }
uuid = { workspace = true }

Expand Down
21 changes: 12 additions & 9 deletions crates/context_aware_config/src/api/audit_log/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use actix_web::{get, web::Query, HttpResponse, Scope};
use actix_web::{
get,
web::{Json, Query},
Scope,
};
use chrono::{Duration, Utc};
use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl};
use serde_json::json;
use service_utils::service::types::DbConnection;
use superposition_types::{
cac::{models::EventLog, schema::event_log::dsl as event_log},
result as superposition,
result as superposition, PaginatedResponse,
};

use crate::api::audit_log::types::AuditQueryFilters;
Expand All @@ -18,7 +21,7 @@ pub fn endpoints() -> Scope {
async fn get_audit_logs(
filters: Query<AuditQueryFilters>,
db_conn: DbConnection,
) -> superposition::Result<HttpResponse> {
) -> superposition::Result<Json<PaginatedResponse<EventLog>>> {
let DbConnection(mut conn) = db_conn;

let query_builder = |filters: &AuditQueryFilters| {
Expand Down Expand Up @@ -57,9 +60,9 @@ async fn get_audit_logs(

let total_pages = (log_count as f64 / limit as f64).ceil() as i64;

Ok(HttpResponse::Ok().json(json!({
"total_items": log_count,
"total_pages": total_pages,
"data": logs
})))
Ok(Json(PaginatedResponse {
total_items: log_count,
total_pages,
data: logs,
}))
}
5 changes: 3 additions & 2 deletions crates/context_aware_config/src/api/dimension/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ use superposition_macros::{bad_argument, db_error, not_found, unexpected_error};
use superposition_types::{
cac::{
models::Dimension,
schema::{dimensions, dimensions::dsl::*},
schema::dimensions::{self, dsl::*},
types::DimensionWithMandatory,
},
custom_query::PaginationParams,
result as superposition, PaginatedResponse, TenantConfig, User,
Expand All @@ -28,7 +29,7 @@ use crate::{
helpers::validate_jsonschema,
};

use super::types::{DeleteReq, DimensionName, DimensionWithMandatory, UpdateReq};
use super::types::{DeleteReq, DimensionName, UpdateReq};

pub fn endpoints() -> Scope {
Scope::new("")
Expand Down
34 changes: 2 additions & 32 deletions crates/context_aware_config/src/api/dimension/types.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use chrono::{DateTime, NaiveDateTime, Utc};
use derive_more::{AsRef, Deref, DerefMut, Into};
use serde::{Deserialize, Deserializer, Serialize};
use serde::{Deserialize, Deserializer};
use serde_json::Value;
use superposition_types::{cac::models::Dimension, RegexEnum};
use superposition_types::RegexEnum;

#[derive(Debug, Deserialize)]
pub struct CreateReq {
Expand Down Expand Up @@ -88,35 +87,6 @@ impl TryFrom<String> for DimensionName {
}
}

#[derive(Debug, Serialize, Deserialize)]
pub struct DimensionWithMandatory {
pub dimension: String,
pub position: i32,
pub created_at: DateTime<Utc>,
pub created_by: String,
pub schema: Value,
pub function_name: Option<String>,
pub last_modified_at: NaiveDateTime,
pub last_modified_by: String,
pub mandatory: bool,
}

impl DimensionWithMandatory {
pub fn new(value: Dimension, mandatory: bool) -> Self {
DimensionWithMandatory {
dimension: value.dimension,
position: value.position,
created_at: value.created_at,
created_by: value.created_by,
schema: value.schema,
function_name: value.function_name,
last_modified_at: value.last_modified_at,
last_modified_by: value.last_modified_by,
mandatory,
}
}
}

#[derive(Debug, Deserialize, AsRef, Deref, DerefMut, Into)]
#[serde(try_from = "String")]
pub struct DeleteReq(String);
Expand Down
18 changes: 10 additions & 8 deletions crates/context_aware_config/src/api/type_templates/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ use jsonschema::JSONSchema;
use serde_json::Value;
use service_utils::service::types::DbConnection;
use superposition_macros::{bad_argument, db_error};
use superposition_types::cac::models::TypeTemplates;
use superposition_types::{
cac::schema::type_templates::{self, dsl},
cac::{
models::TypeTemplate,
schema::type_templates::{self, dsl},
},
custom_query::PaginationParams,
result as superposition, PaginatedResponse, User,
};
Expand Down Expand Up @@ -49,7 +51,7 @@ async fn create_type(
type_templates::created_by.eq(user.email.clone()),
type_templates::last_modified_by.eq(user.email.clone()),
))
.get_result::<TypeTemplates>(&mut conn)
.get_result::<TypeTemplate>(&mut conn)
.map_err(|err| {
log::error!("failed to insert custom type with error: {}", err);
db_error!(err)
Expand Down Expand Up @@ -86,7 +88,7 @@ async fn update_type(
type_templates::last_modified_at.eq(timestamp),
type_templates::last_modified_by.eq(user.email),
))
.get_result::<TypeTemplates>(&mut conn)
.get_result::<TypeTemplate>(&mut conn)
.map_err(|err| {
log::error!("failed to insert custom type with error: {}", err);
db_error!(err)
Expand All @@ -111,19 +113,19 @@ async fn delete_type(
.execute(&mut conn)?;
let deleted_type =
diesel::delete(dsl::type_templates.filter(dsl::type_name.eq(type_name)))
.get_result::<TypeTemplates>(&mut conn)?;
.get_result::<TypeTemplate>(&mut conn)?;
Ok(HttpResponse::Ok().json(deleted_type))
}

#[get("")]
async fn list_types(
db_conn: DbConnection,
filters: Query<PaginationParams>,
) -> superposition::Result<Json<PaginatedResponse<TypeTemplates>>> {
) -> superposition::Result<Json<PaginatedResponse<TypeTemplate>>> {
let DbConnection(mut conn) = db_conn;

if let Some(true) = filters.all {
let result: Vec<TypeTemplates> =
let result: Vec<TypeTemplate> =
type_templates::dsl::type_templates.get_results(&mut conn)?;
return Ok(Json(PaginatedResponse {
total_pages: 1,
Expand All @@ -144,7 +146,7 @@ async fn list_types(
let offset = (page - 1) * limit;
builder = builder.offset(offset);
}
let custom_types: Vec<TypeTemplates> = builder.load(&mut conn)?;
let custom_types: Vec<TypeTemplate> = builder.load(&mut conn)?;
let total_pages = (n_types as f64 / limit as f64).ceil() as i64;
Ok(Json(PaginatedResponse {
total_pages,
Expand Down
4 changes: 3 additions & 1 deletion crates/experimentation_client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ once_cell = { workspace = true }
reqwest = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
superposition_types = { path = "../superposition_types" }
superposition_types = { path = "../superposition_types", features = [
"experimentation",
] }
tokio = { version = "1.29.1", features = ["full"] }

[lib]
Expand Down
17 changes: 9 additions & 8 deletions crates/experimentation_client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@ use std::{
use chrono::{DateTime, TimeZone, Utc};
use derive_more::{Deref, DerefMut};
use serde_json::Value;
use superposition_types::Overridden;
use superposition_types::{
experimentation::models::{ExperimentStatusType, VariantType},
Overridden, PaginatedResponse,
};
use tokio::{
sync::RwLock,
time::{self, Duration},
};
pub use types::{Config, Experiment, Experiments, Variants};
use types::{ExperimentStore, ListExperimentsResponse, Variant, VariantType};
use types::{ExperimentStore, Variant};
use utils::MapError;

#[derive(Clone, Debug)]
Expand All @@ -32,7 +35,7 @@ pub struct Client {

impl Client {
pub fn new(config: Config) -> Self {
Client {
Self {
client_config: Arc::new(config),
experiments: Arc::new(RwLock::new(HashMap::new())),
http_client: reqwest::Client::new(),
Expand Down Expand Up @@ -64,9 +67,7 @@ impl Client {
let mut exp_store = self.experiments.write().await;
for (exp_id, experiment) in experiments.into_iter() {
match experiment.status {
types::ExperimentStatusType::Concluded => {
exp_store.remove(&exp_id)
}
ExperimentStatusType::CONCLUDED => exp_store.remove(&exp_id),
_ => exp_store.insert(exp_id, experiment),
};
}
Expand Down Expand Up @@ -213,7 +214,7 @@ impl Client {
) -> Result<Option<Variant>, String> {
if toss < 0 {
for variant in applicable_variants.iter() {
if variant.variant_type == VariantType::Experimental {
if variant.variant_type == VariantType::EXPERIMENTAL {
return Ok(Some(variant.clone()));
}
}
Expand Down Expand Up @@ -255,7 +256,7 @@ async fn get_experiments(
.send()
.await
.map_err_to_string()?
.json::<ListExperimentsResponse>()
.json::<PaginatedResponse<Experiment>>()
.await
.map_err_to_string()?;

Expand Down
27 changes: 4 additions & 23 deletions crates/experimentation_client/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use superposition_types::{Exp, Overridden, Overrides};
use superposition_types::{
experimentation::models::{ExperimentStatusType, VariantType},
Exp, Overridden, Overrides,
};

#[derive(Clone, Debug)]
pub struct Config {
Expand All @@ -11,21 +14,6 @@ pub struct Config {
pub poll_frequency: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub(crate) enum ExperimentStatusType {
Created,
InProgress,
Concluded,
}

#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub(crate) enum VariantType {
Control,
Experimental,
}

#[repr(C)]
#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct Variant {
Expand Down Expand Up @@ -56,10 +44,3 @@ pub struct Experiment {
pub type Experiments = Vec<Experiment>;

pub(crate) type ExperimentStore = HashMap<String, Experiment>;

#[derive(Serialize, Deserialize, Default)]
pub(crate) struct ListExperimentsResponse {
pub(crate) total_items: i64,
pub(crate) total_pages: i64,
pub(crate) data: Experiments,
}
46 changes: 25 additions & 21 deletions crates/experimentation_platform/src/api/experiments/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use superposition_types::{
},
result::{self as superposition},
webhook::{WebhookConfig, WebhookEvent},
Condition, Exp, Overrides, SortBy, TenantConfig, User,
Condition, Exp, Overrides, PaginatedResponse, SortBy, TenantConfig, User,
};

use super::{
Expand All @@ -44,7 +44,7 @@ use super::{
ApplicableVariantsQuery, AuditQueryFilters, ConcludeExperimentRequest,
ContextAction, ContextBulkResponse, ContextMoveReq, ContextPutReq,
ExperimentCreateRequest, ExperimentCreateResponse, ExperimentListFilters,
ExperimentResponse, ExperimentsResponse, OverrideKeysUpdateRequest, RampRequest,
ExperimentResponse, OverrideKeysUpdateRequest, RampRequest,
},
};
use crate::api::experiments::{helpers::construct_header_map, types::ExperimentSortOn};
Expand Down Expand Up @@ -534,11 +534,13 @@ async fn list_experiments(

if let Some(true) = pagination_params.all {
let result = experiments::experiments.get_results::<Experiment>(&mut conn)?;
return Ok(HttpResponse::Ok().json(ExperimentsResponse {
total_pages: 1,
total_items: result.len() as i64,
data: result.into_iter().map(ExperimentResponse::from).collect(),
}));
return Ok(
HttpResponse::Ok().json(PaginatedResponse::<ExperimentResponse> {
total_pages: 1,
total_items: result.len() as i64,
data: result.into_iter().map(ExperimentResponse::from).collect(),
}),
);
}

let max_event_timestamp: Option<NaiveDateTime> = event_log::event_log
Expand Down Expand Up @@ -615,14 +617,16 @@ async fn list_experiments(
let query = base_query.limit(limit).offset(offset);
let experiment_list = query.load::<Experiment>(&mut conn)?;
let total_pages = (number_of_experiments as f64 / limit as f64).ceil() as i64;
Ok(HttpResponse::Ok().json(ExperimentsResponse {
total_pages,
total_items: number_of_experiments,
data: experiment_list
.into_iter()
.map(ExperimentResponse::from)
.collect(),
}))
Ok(
HttpResponse::Ok().json(PaginatedResponse::<ExperimentResponse> {
total_pages,
total_items: number_of_experiments,
data: experiment_list
.into_iter()
.map(ExperimentResponse::from)
.collect(),
}),
)
}

#[get("/{id}")]
Expand Down Expand Up @@ -962,7 +966,7 @@ async fn update_overrides(
async fn get_audit_logs(
filters: Query<AuditQueryFilters>,
db_conn: DbConnection,
) -> superposition::Result<HttpResponse> {
) -> superposition::Result<Json<PaginatedResponse<EventLog>>> {
let DbConnection(mut conn) = db_conn;

let query_builder = |filters: &AuditQueryFilters| {
Expand Down Expand Up @@ -1001,9 +1005,9 @@ async fn get_audit_logs(

let total_pages = (log_count as f64 / limit as f64).ceil() as i64;

Ok(HttpResponse::Ok().json(json!({
"total_items": log_count,
"total_pages": total_pages,
"data": logs
})))
Ok(Json(PaginatedResponse {
total_items: log_count,
total_pages: total_pages,
data: logs,
}))
}
Loading

0 comments on commit f4301d8

Please sign in to comment.