diff --git a/app/web/src/store/asset.store.ts b/app/web/src/store/asset.store.ts index c24943ba9d..8dfdf88c76 100644 --- a/app/web/src/store/asset.store.ts +++ b/app/web/src/store/asset.store.ts @@ -86,11 +86,16 @@ export const useAssetStore = () => { const workspaceStore = useWorkspacesStore(); const workspaceId = workspaceStore.selectedWorkspacePk; + const changeSetsStore = useChangeSetsStore(); + const selectedChangeSetId = changeSetsStore.selectedChangeSet?.id; + const funcStore = useFuncStore(); const moduleStore = useModuleStore(); let assetSaveDebouncer: ReturnType | undefined; + const API_PREFIX = `v2/workspaces/${workspaceId}/change-sets/${selectedChangeSetId}/schema-variants`; + return addStoreHooks( defineStore(`ws${workspaceId || "NONE"}/cs${changeSetId || "NONE"}/asset`, { state: () => ({ @@ -432,7 +437,7 @@ export const useAssetStore = () => { async LOAD_SCHEMA_VARIANT_LIST() { return new ApiRequest({ - url: `v2/workspaces/${workspaceId}/change-sets/${changeSetId}/schema-variants`, + url: `${API_PREFIX}`, params: { ...visibility }, onSuccess: (response) => { this.variantList = response; @@ -450,12 +455,8 @@ export const useAssetStore = () => { return new ApiRequest({ method: "post", - url: "/variant/create_unlocked_copy", + url: `${API_PREFIX}/${id}`, keyRequestStatusBy: id, - params: { - ...visibility, - id, - }, onSuccess: (variant) => { const savedAssetIdx = this.variantList.findIndex( (a) => a.schemaVariantId === variant.schemaVariantId, @@ -473,8 +474,8 @@ export const useAssetStore = () => { changeSetStore.creatingChangeSet = true; return new ApiRequest({ - method: "post", - url: `v2/workspaces/${workspaceId}/change-sets/${changeSetId}/schema-variants/${id}/delete_unlocked_variant`, + method: "delete", + url: `${API_PREFIX}/${id}`, keyRequestStatusBy: id, params: { // ...visibility, diff --git a/lib/dal/src/schema/variant.rs b/lib/dal/src/schema/variant.rs index 0a1f9f32ec..4b6e7e020f 100644 --- a/lib/dal/src/schema/variant.rs +++ b/lib/dal/src/schema/variant.rs @@ -1,18 +1,33 @@ //! This module contains [`SchemaVariant`](SchemaVariant), which is the "class" of a [`Component`](crate::Component). +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::Arc; + use chrono::Utc; use petgraph::{Direction, Incoming, Outgoing}; use serde::{Deserialize, Serialize}; -use si_events::{ulid::Ulid, ContentHash}; +use thiserror::Error; +use url::ParseError; + +pub use json::SchemaVariantJson; +pub use json::SchemaVariantMetadataJson; +pub use metadata_view::SchemaVariantMetadataView; +use si_events::{ContentHash, ulid::Ulid}; use si_frontend_types as frontend_types; use si_layer_cache::LayerDbError; use si_pkg::SpecError; -use std::collections::{HashMap, HashSet, VecDeque}; -use std::sync::Arc; use telemetry::prelude::*; -use thiserror::Error; -use url::ParseError; +pub use value_from::ValueFrom; +use crate::{ + ActionPrototypeId, AttributePrototype, + AttributePrototypeId, + ChangeSetId, ComponentId, ComponentType, DalContext, Func, + FuncId, HelperError, implement_add_edge_to, InputSocket, OutputSocket, OutputSocketId, pk, + Prop, PropId, PropKind, Schema, schema::variant::leaves::{LeafInput, LeafInputLocation, LeafKind}, SchemaError, SchemaId, Timestamp, + TransactionsError, WsEvent, WsEventResult, WsPayload, +}; +use crate::{AttributeValue, Component, ComponentError, FuncBackendResponseType, InputSocketId}; use crate::action::prototype::{ActionKind, ActionPrototype}; use crate::attribute::prototype::argument::{ AttributePrototypeArgument, AttributePrototypeArgumentError, @@ -20,9 +35,9 @@ use crate::attribute::prototype::argument::{ use crate::attribute::prototype::AttributePrototypeError; use crate::attribute::value::{AttributeValueError, ValueIsFor}; use crate::change_set::ChangeSetError; +use crate::func::{FuncError, FuncKind}; use crate::func::argument::{FuncArgument, FuncArgumentError}; use crate::func::intrinsics::IntrinsicFunc; -use crate::func::{FuncError, FuncKind}; use crate::layer_db_types::{ ContentTypeError, InputSocketContent, OutputSocketContent, SchemaVariantContent, SchemaVariantContentV2, @@ -39,15 +54,6 @@ use crate::workspace_snapshot::edge_weight::{ use crate::workspace_snapshot::graph::NodeIndex; use crate::workspace_snapshot::node_weight::{NodeWeight, NodeWeightError, PropNodeWeight}; use crate::workspace_snapshot::WorkspaceSnapshotError; -use crate::{ - implement_add_edge_to, pk, - schema::variant::leaves::{LeafInput, LeafInputLocation, LeafKind}, - ActionPrototypeId, AttributePrototype, AttributePrototypeId, ChangeSetId, ComponentId, - ComponentType, DalContext, Func, FuncId, HelperError, InputSocket, OutputSocket, - OutputSocketId, Prop, PropId, PropKind, Schema, SchemaError, SchemaId, Timestamp, - TransactionsError, WsEvent, WsEventResult, WsPayload, -}; -use crate::{AttributeValue, Component, ComponentError, FuncBackendResponseType, InputSocketId}; use self::root_prop::RootPropChild; @@ -58,11 +64,6 @@ mod metadata_view; pub mod root_prop; mod value_from; -pub use json::SchemaVariantJson; -pub use json::SchemaVariantMetadataJson; -pub use metadata_view::SchemaVariantMetadataView; -pub use value_from::ValueFrom; - // FIXME(nick,theo): colors should be required for all schema variants. // There should be no default in the backend as there should always be a color. pub const DEFAULT_SCHEMA_VARIANT_COLOR: &str = "#00b0bc"; @@ -334,7 +335,7 @@ impl WsEvent { change_set_id: ctx.change_set_id(), }), ) - .await + .await } #[allow(clippy::too_many_arguments)] @@ -366,7 +367,7 @@ impl WsEvent { change_set_id: ctx.change_set_id(), }), ) - .await + .await } pub async fn schema_variant_cloned( @@ -380,7 +381,7 @@ impl WsEvent { change_set_id: ctx.change_set_id(), }), ) - .await + .await } pub async fn schema_variant_update_finished( @@ -396,7 +397,7 @@ impl WsEvent { change_set_id: ctx.change_set_id(), }), ) - .await + .await } } @@ -553,7 +554,6 @@ impl SchemaVariant { } let schema = variant.schema(ctx).await?; - dbg!(&schema); // Firstly we want to delete the asset func let asset_func = variant.get_asset_func(ctx).await?; @@ -562,10 +562,7 @@ impl SchemaVariant { let workspace_snapshot = ctx.workspace_snapshot()?; if let Some(default_schema_variant_id) = schema.get_default_schema_variant_id(ctx).await? { - dbg!(&default_schema_variant_id); if variant.id == default_schema_variant_id { - dbg!("Deletion of the schema"); - dbg!(&schema); workspace_snapshot .remove_node_by_id(ctx.vector_clock_id()?, schema.id()) .await?; @@ -586,7 +583,7 @@ impl SchemaVariant { sv.is_locked = true; Ok(()) }) - .await + .await } /// Returns all [`PropIds`](Prop) for a given [`SchemaVariantId`](SchemaVariant). @@ -787,9 +784,9 @@ impl SchemaVariant { Ok(Self::is_default_by_id(ctx, id).await? && Self::is_locked_by_id(ctx, id).await? && Module::find_for_member_id(ctx, id) - .await - .map_err(|e| SchemaVariantError::Module(e.to_string()))? - .is_none()) + .await + .map_err(|e| SchemaVariantError::Module(e.to_string()))? + .is_none()) } pub async fn get_latest_for_schema( @@ -1023,7 +1020,7 @@ impl SchemaVariant { attribute_prototype.id(), EdgeWeightKind::Prototype(None), ) - .await?; + .await?; } // Push all children onto the work queue. @@ -1174,7 +1171,7 @@ impl SchemaVariant { func_id, EdgeWeightKind::AuthenticationPrototype, ) - .await?; + .await?; Ok(()) } @@ -1344,7 +1341,7 @@ impl SchemaVariant { schema_variant_id, &PropPath::new(["root", leaf_map_prop_name, leaf_item_prop_name]), ) - .await?) + .await?) } pub async fn upsert_leaf_function( @@ -1382,8 +1379,8 @@ impl SchemaVariant { for existing_arg in existing_args.drain(..) { if !inputs.iter().any( |&LeafInput { - func_argument_id, .. - }| func_argument_id == existing_arg.id, + func_argument_id, .. + }| func_argument_id == existing_arg.id, ) { FuncArgument::remove(ctx, existing_arg.id).await?; } @@ -1398,7 +1395,7 @@ impl SchemaVariant { existing_proto_id, schema_variant_id, ) - .await?; + .await?; existing_proto_id } None => { @@ -1415,8 +1412,8 @@ impl SchemaVariant { component_id, leaf_kind, ) - .await - .map_err(Box::new)?; + .await + .map_err(Box::new)?; let new_attribute_value = AttributeValue::new( ctx, @@ -1425,8 +1422,8 @@ impl SchemaVariant { Some(parent_attribute_value_id), key.clone(), ) - .await - .map_err(Box::new)?; + .await + .map_err(Box::new)?; new_attribute_value_ids.push(new_attribute_value.id); } if !new_attribute_value_ids.is_empty() { @@ -1478,7 +1475,7 @@ impl SchemaVariant { attribute_prototype_id, input.func_argument_id, ) - .await?; + .await?; new_apa.set_value_from_prop_id(ctx, input_prop_id).await?; } } @@ -1486,8 +1483,8 @@ impl SchemaVariant { for (apa_id, func_arg_id) in apa_func_arg_ids { if !inputs.iter().any( |&LeafInput { - func_argument_id, .. - }| { func_argument_id == func_arg_id }, + func_argument_id, .. + }| { func_argument_id == func_arg_id }, ) { AttributePrototypeArgument::remove(ctx, *apa_id).await?; } diff --git a/lib/dal/src/schema/variant/authoring.rs b/lib/dal/src/schema/variant/authoring.rs index b645e7b577..8a50fb0c65 100644 --- a/lib/dal/src/schema/variant/authoring.rs +++ b/lib/dal/src/schema/variant/authoring.rs @@ -1,41 +1,42 @@ use std::collections::HashMap; use std::fmt::Debug; -use base64::engine::general_purpose; use base64::Engine; +use base64::engine::general_purpose; use chrono::Utc; use convert_case::{Case, Casing}; -use pkg::import::import_schema_variant; use serde::{Deserialize, Serialize}; use serde_json::error::Category; -use si_events::ulid::Ulid; +use thiserror::Error; + +use pkg::import::import_schema_variant; use si_events::FuncRunId; +use si_events::ulid::Ulid; use si_layer_cache::LayerDbError; use si_pkg::{ FuncSpec, FuncSpecBackendKind, FuncSpecBackendResponseType, FuncSpecData, MergeSkip, PkgSpec, SchemaVariantSpec, SiPkg, SiPkgError, SpecError, }; use telemetry::prelude::*; -use thiserror::Error; +use crate::{ + Component, ComponentError, ComponentType, DalContext, Func, FuncBackendKind, FuncBackendResponseType, + FuncError, FuncId, HistoryEventError, pkg, Schema, SchemaError, SchemaId, + SchemaVariant, SchemaVariantError, SchemaVariantId, +}; use crate::action::prototype::ActionPrototypeError; use crate::attribute::prototype::argument::AttributePrototypeArgumentError; use crate::attribute::prototype::AttributePrototypeError; use crate::func::authoring::FuncAuthoringError; use crate::func::intrinsics::IntrinsicFunc; use crate::func::runner::{FuncRunner, FuncRunnerError}; +use crate::pkg::{import_pkg_from_pkg, ImportOptions, PkgError}; use crate::pkg::export::PkgExporter; use crate::pkg::import::import_only_new_funcs; -use crate::pkg::{import_pkg_from_pkg, ImportOptions, PkgError}; use crate::prop::PropError; use crate::schema::variant::{SchemaVariantJson, SchemaVariantMetadataJson}; use crate::socket::input::InputSocketError; use crate::socket::output::OutputSocketError; -use crate::{ - pkg, Component, ComponentError, ComponentType, DalContext, Func, FuncBackendKind, - FuncBackendResponseType, FuncError, FuncId, HistoryEventError, Schema, SchemaError, SchemaId, - SchemaVariant, SchemaVariantError, SchemaVariantId, -}; #[allow(missing_docs)] #[remain::sorted] @@ -51,6 +52,8 @@ pub enum VariantAuthoringError { AttributePrototypeArgument(#[from] AttributePrototypeArgumentError), #[error("component error: {0}")] Component(#[from] ComponentError), + #[error("there already exists a Schema with the name {0}")] + DuplicatedSchemaName(String), #[error("empty value within func run value (FuncId {0} and FuncRunId {1})")] EmptyValueWithinFuncRunValue(FuncId, FuncRunId), #[error("func error: {0}")] @@ -133,6 +136,10 @@ impl VariantAuthoringClient { color: impl Into, ) -> VariantAuthoringResult { let name = name.into(); + if Schema::is_name_taken(ctx, &name).await? { + return Err(VariantAuthoringError::DuplicatedSchemaName(name)) + }; + let variant_version = SchemaVariant::generate_version_string(); let code_base64 = general_purpose::STANDARD_NO_PAD.encode(DEFAULT_ASSET_CODE); @@ -204,6 +211,10 @@ impl VariantAuthoringClient { schema_variant_id: SchemaVariantId, schema_name: String, ) -> VariantAuthoringResult<(SchemaVariant, Schema)> { + if Schema::is_name_taken(ctx, &schema_name).await? { + return Err(VariantAuthoringError::DuplicatedSchemaName(schema_name)) + }; + let variant = SchemaVariant::get_by_id_or_error(ctx, schema_variant_id).await?; let schema = variant.schema(ctx).await?; diff --git a/lib/dal/src/workspace_snapshot/content_address.rs b/lib/dal/src/workspace_snapshot/content_address.rs index 3e9c82c928..bdd113eb9b 100644 --- a/lib/dal/src/workspace_snapshot/content_address.rs +++ b/lib/dal/src/workspace_snapshot/content_address.rs @@ -1,7 +1,8 @@ use serde::{Deserialize, Serialize}; -use si_events::ContentHash; use strum::EnumDiscriminants; +use si_events::ContentHash; + #[remain::sorted] #[derive( EnumDiscriminants, Debug, Serialize, Deserialize, Copy, Clone, PartialEq, Eq, strum::Display, @@ -30,7 +31,9 @@ pub enum ContentAddress { Secret(ContentHash), StaticArgumentValue(ContentHash), ValidationOutput(ContentHash), - ValidationPrototype(ContentHash), // TODO(victor): Remove this after module index gets new data + // With validations moving to the props and not having prototypes anymore, this is unused + // TODO(victor): remove this as soon as it does not break graph (de)serialization + ValidationPrototype(ContentHash), } impl ContentAddress { diff --git a/lib/sdf-server/src/server/service/v2.rs b/lib/sdf-server/src/server/service/v2.rs index 589d05e5da..494585516e 100644 --- a/lib/sdf-server/src/server/service/v2.rs +++ b/lib/sdf-server/src/server/service/v2.rs @@ -11,14 +11,14 @@ pub fn routes() -> Router { Router::new() .nest( &format!("{PREFIX}/schema-variants"), - crate::server::service::v2::variant::v2_routes(), + variant::v2_routes(), ) .nest( &format!("{PREFIX}/funcs"), - crate::server::service::v2::func::v2_routes(), + func::v2_routes(), ) .nest( &format!("{PREFIX}/modules"), - crate::server::service::v2::module::v2_routes(), + module::v2_routes(), ) } diff --git a/lib/sdf-server/src/server/service/v2/variant.rs b/lib/sdf-server/src/server/service/v2/variant.rs index 115d549efa..08e6085eb3 100644 --- a/lib/sdf-server/src/server/service/v2/variant.rs +++ b/lib/sdf-server/src/server/service/v2/variant.rs @@ -1,18 +1,21 @@ use axum::{ http::StatusCode, response::{IntoResponse, Response}, - routing::{get, post}, Router, + routing::{get, post}, }; +use axum::routing::delete; +use thiserror::Error; + use dal::{ChangeSetError, SchemaVariantId, WsEventError}; use telemetry::prelude::*; -use thiserror::Error; use crate::{server::state::AppState, service::ApiError}; mod delete_unlocked_variant; mod get_variant; mod list_variants; +pub mod create_unlocked_copy; #[remain::sorted] #[derive(Debug, Error)] @@ -61,7 +64,11 @@ pub fn v2_routes() -> Router { .route("/", get(list_variants::list_variants)) .route("/:schema_variant_id", get(get_variant::get_variant)) .route( - "/:schema_variant_id/delete_unlocked_variant", - post(delete_unlocked_variant::delete_unlocked_variant), + "/:schema_variant_id", + post(create_unlocked_copy::create_unlocked_copy), + ) + .route( + "/:schema_variant_id", + delete(delete_unlocked_variant::delete_unlocked_variant), ) } diff --git a/lib/sdf-server/src/server/service/variant/create_unlocked_copy.rs b/lib/sdf-server/src/server/service/v2/variant/create_unlocked_copy.rs similarity index 80% rename from lib/sdf-server/src/server/service/variant/create_unlocked_copy.rs rename to lib/sdf-server/src/server/service/v2/variant/create_unlocked_copy.rs index 772c439415..ab13e2d97c 100644 --- a/lib/sdf-server/src/server/service/variant/create_unlocked_copy.rs +++ b/lib/sdf-server/src/server/service/v2/variant/create_unlocked_copy.rs @@ -1,32 +1,29 @@ +use axum::extract::{OriginalUri, Path}; +use axum::response::IntoResponse; + +use dal::{ChangeSet, ChangeSetId, Schema, SchemaVariant, SchemaVariantId, WorkspacePk, WsEvent}; +use dal::schema::variant::authoring::VariantAuthoringClient; + use crate::server::extract::{AccessBuilder, HandlerContext, PosthogClient}; use crate::server::tracking::track; use crate::service::variant::{SchemaVariantError, SchemaVariantResult}; -use axum::extract::OriginalUri; -use axum::{response::IntoResponse, Json}; -use dal::schema::variant::authoring::VariantAuthoringClient; -use dal::{ChangeSet, Schema, SchemaVariant, SchemaVariantId, Visibility, WsEvent}; -use serde::{Deserialize, Serialize}; - -#[derive(Deserialize, Serialize, Debug)] -#[serde(rename_all = "camelCase")] -pub struct CloneVariantRequest { - pub id: SchemaVariantId, - #[serde(flatten)] - pub visibility: Visibility, -} pub async fn create_unlocked_copy( HandlerContext(builder): HandlerContext, AccessBuilder(request_ctx): AccessBuilder, PosthogClient(posthog_client): PosthogClient, OriginalUri(original_uri): OriginalUri, - Json(request): Json, + Path((_workspace_pk, change_set_id, schema_variant_id)): Path<( + WorkspacePk, + ChangeSetId, + SchemaVariantId, + )>, ) -> SchemaVariantResult { - let mut ctx = builder.build(request_ctx.build(request.visibility)).await?; + let mut ctx = builder.build(request_ctx.build(change_set_id.into())).await?; let force_change_set_id = ChangeSet::force_new(&mut ctx).await?; - let original_variant = SchemaVariant::get_by_id_or_error(&ctx, request.id).await?; + let original_variant = SchemaVariant::get_by_id_or_error(&ctx, schema_variant_id).await?; let schema = original_variant.schema(&ctx).await?; diff --git a/lib/sdf-server/src/server/service/v2/variant/get_variant.rs b/lib/sdf-server/src/server/service/v2/variant/get_variant.rs index 33d1c5dcb7..50b643f22b 100644 --- a/lib/sdf-server/src/server/service/v2/variant/get_variant.rs +++ b/lib/sdf-server/src/server/service/v2/variant/get_variant.rs @@ -32,10 +32,7 @@ pub async fn get_variant( let schema_variant = SchemaVariant::get_by_id_or_error(&ctx, schema_variant_id).await?; let schema_id = SchemaVariant::schema_id_for_schema_variant_id(&ctx, schema_variant_id).await?; let schema_variant = schema_variant.into_frontend_type(&ctx, schema_id).await?; - - // Ported from `lib/sdf-server/src/server/service/variant/get_variant.rs`, so changes may be - // desired here... - + track( &posthog_client, &ctx, diff --git a/lib/sdf-server/src/server/service/variant.rs b/lib/sdf-server/src/server/service/variant.rs index e02b85d4b2..9d1353ba8a 100644 --- a/lib/sdf-server/src/server/service/variant.rs +++ b/lib/sdf-server/src/server/service/variant.rs @@ -1,24 +1,22 @@ +use axum::{Json, Router}; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use axum::routing::post; -use axum::{routing::get, Json, Router}; -use dal::func::summary::FuncSummaryError; -use dal::pkg::PkgError; -use dal::schema::variant::authoring::VariantAuthoringError; +use thiserror::Error; + use dal::{ ChangeSetError, FuncError, FuncId, SchemaError, SchemaId, SchemaVariantId, TransactionsError, WsEventError, }; +use dal::func::summary::FuncSummaryError; +use dal::pkg::PkgError; +use dal::schema::variant::authoring::VariantAuthoringError; use si_pkg::{SiPkgError, SpecError}; -use thiserror::Error; use crate::server::state::AppState; pub mod clone_variant; -mod create_unlocked_copy; pub mod create_variant; -pub mod get_variant; -pub mod list_variants; pub mod regenerate_variant; pub mod save_variant; @@ -80,6 +78,9 @@ impl IntoResponse for SchemaVariantError { | SchemaVariantError::NoDefaultSchemaVariantFoundForSchema(_) | SchemaVariantError::SchemaVariantAssetNotFound(_) | SchemaVariantError::VariantNotFound(_) => (StatusCode::NOT_FOUND, self.to_string()), + SchemaVariantError::VariantAuthoring( + VariantAuthoringError::DuplicatedSchemaName(_), + ) | SchemaVariantError::Transactions(TransactionsError::ConflictsOccurred(_)) => { (StatusCode::CONFLICT, self.to_string()) } @@ -102,8 +103,6 @@ impl IntoResponse for SchemaVariantError { pub fn routes() -> Router { Router::new() - .route("/list_variants", get(list_variants::list_variants)) - .route("/get_variant", get(get_variant::get_variant)) .route("/create_variant", post(create_variant::create_variant)) .route( "/regenerate_variant", @@ -111,8 +110,4 @@ pub fn routes() -> Router { ) .route("/clone_variant", post(clone_variant::clone_variant)) .route("/save_variant", post(save_variant::save_variant)) - .route( - "/create_unlocked_copy", - post(create_unlocked_copy::create_unlocked_copy), - ) } diff --git a/lib/sdf-server/src/server/service/variant/create_variant.rs b/lib/sdf-server/src/server/service/variant/create_variant.rs index 621e66516c..6cbb00e185 100644 --- a/lib/sdf-server/src/server/service/variant/create_variant.rs +++ b/lib/sdf-server/src/server/service/variant/create_variant.rs @@ -1,9 +1,9 @@ +use axum::{Json, response::IntoResponse}; use axum::extract::OriginalUri; -use axum::{response::IntoResponse, Json}; use serde::{Deserialize, Serialize}; +use dal::{ChangeSet, Visibility, WsEvent}; use dal::schema::variant::authoring::VariantAuthoringClient; -use dal::{ChangeSet, Schema, Visibility, WsEvent}; use crate::server::extract::{AccessBuilder, HandlerContext, PosthogClient}; use crate::server::tracking::track; @@ -27,12 +27,6 @@ pub async fn create_variant( ) -> SchemaVariantResult { let mut ctx = builder.build(request_ctx.build(request.visibility)).await?; - if Schema::is_name_taken(&ctx, &request.name).await? { - return Ok(axum::response::Response::builder() - .status(409) - .body("schema name already taken".to_string())?); - } - let force_change_set_id = ChangeSet::force_new(&mut ctx).await?; let created_schema_variant = VariantAuthoringClient::create_schema_and_variant( diff --git a/lib/sdf-server/src/server/service/variant/get_variant.rs b/lib/sdf-server/src/server/service/variant/get_variant.rs deleted file mode 100644 index a8a0b313eb..0000000000 --- a/lib/sdf-server/src/server/service/variant/get_variant.rs +++ /dev/null @@ -1,116 +0,0 @@ -use axum::extract::OriginalUri; -use axum::{extract::Query, Json}; -use dal::func::authoring::FuncAuthoringClient; -use dal::func::summary::FuncSummary; -use dal::{ - ComponentType, Func, Schema, SchemaId, SchemaVariant, SchemaVariantId, Timestamp, Visibility, -}; -use serde::{Deserialize, Serialize}; - -use crate::server::extract::{AccessBuilder, HandlerContext, PosthogClient}; -use crate::server::tracking::track; -use crate::service::variant::{SchemaVariantError, SchemaVariantResult}; - -#[derive(Deserialize, Serialize, Debug)] -#[serde(rename_all = "camelCase")] -pub struct GetVariantRequest { - pub id: SchemaId, - #[serde(flatten)] - pub visibility: Visibility, -} - -#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct GetVariantResponse { - pub id: SchemaId, - pub default_schema_variant_id: SchemaVariantId, - pub schema_name: String, - pub name: String, - pub display_name: String, - pub category: String, - pub color: String, - pub link: Option, - pub description: Option, - pub code: String, - pub component_type: ComponentType, - pub funcs: Vec, - pub types: String, - pub has_components: bool, - pub is_locked: bool, - #[serde(flatten)] - pub timestamp: Timestamp, -} - -pub async fn get_variant( - HandlerContext(builder): HandlerContext, - AccessBuilder(request_ctx): AccessBuilder, - PosthogClient(posthog_client): PosthogClient, - OriginalUri(original_uri): OriginalUri, - Query(request): Query, -) -> SchemaVariantResult> { - let ctx = builder.build(request_ctx.build(request.visibility)).await?; - - let schema = Schema::get_by_id(&ctx, request.id).await?; - let default_schema_variant_id = schema.get_default_schema_variant_id(&ctx).await?.ok_or( - SchemaVariantError::NoDefaultSchemaVariantFoundForSchema(schema.id()), - )?; - let variant = SchemaVariant::get_by_id_or_error(&ctx, default_schema_variant_id).await?; - - // Collect the funcs for all schema variants corresponding to the schema. We want this because - // while asset editing generally corresponds to the current default schema variant id, you are - // unable to access functions that belong to components using older schema variants on the - // diagram unless you collect all functions for all schema variants. Function access is - // important because it provides not only the ability to edit a function, but also its bindings. - let funcs = FuncSummary::list_for_schema_id(&ctx, schema.id()).await?; - - let mut response: GetVariantResponse = GetVariantResponse { - id: request.id, - default_schema_variant_id, - schema_name: schema.name().into(), - name: variant.version().into(), - display_name: variant.display_name().to_string(), - category: variant.category().into(), - color: variant.get_color(&ctx).await?, - link: variant.link(), - description: variant.description(), - component_type: variant.component_type(), - timestamp: variant.timestamp(), - // Will be set elsewhere - code: "".to_string(), - funcs, - types: "".to_string(), - has_components: false, - is_locked: variant.is_locked(), - }; - - if let Some(authoring_func) = variant.asset_func_id() { - let asset_func = Func::get_by_id_or_error(&ctx, authoring_func).await?; - - response.code = asset_func - .code_plaintext()? - .ok_or(SchemaVariantError::FuncIsEmpty(asset_func.id))?; - - response.types = FuncAuthoringClient::compile_return_types( - asset_func.backend_response_type, - asset_func.backend_kind, - ) - .to_string(); - } - - track( - &posthog_client, - &ctx, - &original_uri, - "get_variant", - serde_json::json!({ - "variant_version": variant.version(), - "variant_category": variant.category(), - "variant_display_name": variant.display_name(), - "variant_id": variant.id(), - "schema_id": schema.id(), - "variant_component_type": variant.component_type(), - }), - ); - - Ok(Json(response)) -} diff --git a/lib/sdf-server/src/server/service/variant/list_variants.rs b/lib/sdf-server/src/server/service/variant/list_variants.rs deleted file mode 100644 index 00c83d182e..0000000000 --- a/lib/sdf-server/src/server/service/variant/list_variants.rs +++ /dev/null @@ -1,45 +0,0 @@ -use crate::server::extract::{AccessBuilder, HandlerContext, PosthogClient}; -use crate::server::tracking::track; -use crate::service::variant::SchemaVariantResult; -use axum::extract::OriginalUri; -use axum::{extract::Query, Json}; -use dal::schema::variant::SchemaVariantMetadataView; -use dal::Visibility; -use serde::{Deserialize, Serialize}; - -#[derive(Deserialize, Serialize, Debug)] -#[serde(rename_all = "camelCase")] -pub struct ListVariantsRequest { - #[serde(flatten)] - pub visibility: Visibility, -} - -#[derive(Deserialize, Serialize, Debug)] -#[serde(rename_all = "camelCase")] -pub struct ListVariantsResponse { - pub variants: Vec, -} - -pub async fn list_variants( - HandlerContext(builder): HandlerContext, - AccessBuilder(request_ctx): AccessBuilder, - PosthogClient(posthog_client): PosthogClient, - OriginalUri(original_uri): OriginalUri, - Query(request): Query, -) -> SchemaVariantResult> { - let ctx = builder.build(request_ctx.build(request.visibility)).await?; - - let schema_variant_metadata_views = SchemaVariantMetadataView::list(&ctx).await?; - - track( - &posthog_client, - &ctx, - &original_uri, - "list_variant_def", - serde_json::json!({}), - ); - - Ok(Json(ListVariantsResponse { - variants: schema_variant_metadata_views, - })) -}