Skip to content

Commit

Permalink
Feat: Delete outdated schema variant endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
vbustamante committed Jul 26, 2024
1 parent 491230a commit 676b53a
Show file tree
Hide file tree
Showing 12 changed files with 74 additions and 239 deletions.
17 changes: 9 additions & 8 deletions app/web/src/store/asset.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof keyedDebouncer> | undefined;

const API_PREFIX = `v2/workspaces/${workspaceId}/change-sets/${selectedChangeSetId}/schema-variants`;

return addStoreHooks(
defineStore(`ws${workspaceId || "NONE"}/cs${changeSetId || "NONE"}/asset`, {
state: () => ({
Expand Down Expand Up @@ -432,7 +437,7 @@ export const useAssetStore = () => {

async LOAD_SCHEMA_VARIANT_LIST() {
return new ApiRequest<SchemaVariant[], Visibility>({
url: `v2/workspaces/${workspaceId}/change-sets/${changeSetId}/schema-variants`,
url: `${API_PREFIX}`,
params: { ...visibility },
onSuccess: (response) => {
this.variantList = response;
Expand All @@ -450,12 +455,8 @@ export const useAssetStore = () => {

return new ApiRequest<SchemaVariant>({
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,
Expand All @@ -473,8 +474,8 @@ export const useAssetStore = () => {
changeSetStore.creatingChangeSet = true;

return new ApiRequest<SchemaVariant>({
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,
Expand Down
23 changes: 10 additions & 13 deletions lib/dal/src/schema/variant.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
//! 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 thiserror::Error;
use url::ParseError;

pub use json::SchemaVariantJson;
pub use json::SchemaVariantMetadataJson;
pub use metadata_view::SchemaVariantMetadataView;
use si_events::{ulid::Ulid, ContentHash};
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::action::prototype::{ActionKind, ActionPrototype};
use crate::attribute::prototype::argument::{
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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?;
Expand All @@ -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?;
Expand Down
15 changes: 13 additions & 2 deletions lib/dal/src/schema/variant/authoring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ use base64::engine::general_purpose;
use base64::Engine;
use chrono::Utc;
use convert_case::{Case, Casing};
use pkg::import::import_schema_variant;
use serde::{Deserialize, Serialize};
use serde_json::error::Category;
use thiserror::Error;

use pkg::import::import_schema_variant;
use si_events::ulid::Ulid;
use si_events::FuncRunId;
use si_layer_cache::LayerDbError;
Expand All @@ -16,7 +18,6 @@ use si_pkg::{
SchemaVariantSpec, SiPkg, SiPkgError, SpecError,
};
use telemetry::prelude::*;
use thiserror::Error;

use crate::action::prototype::ActionPrototypeError;
use crate::attribute::prototype::argument::AttributePrototypeArgumentError;
Expand Down Expand Up @@ -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}")]
Expand Down Expand Up @@ -133,6 +136,10 @@ impl VariantAuthoringClient {
color: impl Into<String>,
) -> VariantAuthoringResult<SchemaVariant> {
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);
Expand Down Expand Up @@ -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?;

Expand Down
7 changes: 5 additions & 2 deletions lib/dal/src/workspace_snapshot/content_address.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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 {
Expand Down
15 changes: 3 additions & 12 deletions lib/sdf-server/src/server/service/v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,7 @@ pub mod variant;
pub fn routes() -> Router<AppState> {
const PREFIX: &str = "/workspaces/:workspace_id/change-sets/:change_set_id";
Router::new()
.nest(
&format!("{PREFIX}/schema-variants"),
crate::server::service::v2::variant::v2_routes(),
)
.nest(
&format!("{PREFIX}/funcs"),
crate::server::service::v2::func::v2_routes(),
)
.nest(
&format!("{PREFIX}/modules"),
crate::server::service::v2::module::v2_routes(),
)
.nest(&format!("{PREFIX}/schema-variants"), variant::v2_routes())
.nest(&format!("{PREFIX}/funcs"), func::v2_routes())
.nest(&format!("{PREFIX}/modules"), module::v2_routes())
}
13 changes: 10 additions & 3 deletions lib/sdf-server/src/server/service/v2/variant.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
use axum::routing::delete;
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
routing::{get, post},
Router,
};
use thiserror::Error;

use dal::{ChangeSetError, SchemaVariantId, WsEventError};
use telemetry::prelude::*;
use thiserror::Error;

use crate::{server::state::AppState, service::ApiError};

pub mod create_unlocked_copy;
mod delete_unlocked_variant;
mod get_variant;
mod list_variants;
Expand Down Expand Up @@ -61,7 +64,11 @@ pub fn v2_routes() -> Router<AppState> {
.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),
)
}
Original file line number Diff line number Diff line change
@@ -1,32 +1,31 @@
use axum::extract::{OriginalUri, Path};
use axum::response::IntoResponse;

use dal::schema::variant::authoring::VariantAuthoringClient;
use dal::{ChangeSet, ChangeSetId, Schema, SchemaVariant, SchemaVariantId, WorkspacePk, WsEvent};

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<CloneVariantRequest>,
Path((_workspace_pk, change_set_id, schema_variant_id)): Path<(
WorkspacePk,
ChangeSetId,
SchemaVariantId,
)>,
) -> SchemaVariantResult<impl IntoResponse> {
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?;

Expand Down
3 changes: 0 additions & 3 deletions lib/sdf-server/src/server/service/v2/variant/get_variant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@ pub async fn get_variant(
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,
Expand Down
20 changes: 8 additions & 12 deletions lib/sdf-server/src/server/service/variant.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::{routing::get, Json, Router};
use axum::{Json, Router};
use thiserror::Error;

use dal::func::summary::FuncSummaryError;
use dal::pkg::PkgError;
use dal::schema::variant::authoring::VariantAuthoringError;
Expand All @@ -10,15 +12,11 @@ use dal::{
WsEventError,
};
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;

Expand All @@ -43,6 +41,7 @@ pub enum SchemaVariantError {
FuncNotFound(FuncId),
#[error("func summary error: {0}")]
FuncSummary(#[from] FuncSummaryError),

#[error("hyper error: {0}")]
Hyper(#[from] hyper::http::Error),
#[error("no new asset was created")]
Expand Down Expand Up @@ -80,7 +79,10 @@ impl IntoResponse for SchemaVariantError {
| SchemaVariantError::NoDefaultSchemaVariantFoundForSchema(_)
| SchemaVariantError::SchemaVariantAssetNotFound(_)
| SchemaVariantError::VariantNotFound(_) => (StatusCode::NOT_FOUND, self.to_string()),
SchemaVariantError::Transactions(TransactionsError::ConflictsOccurred(_)) => {
SchemaVariantError::VariantAuthoring(VariantAuthoringError::DuplicatedSchemaName(
_,
))
| SchemaVariantError::Transactions(TransactionsError::ConflictsOccurred(_)) => {
(StatusCode::CONFLICT, self.to_string())
}
SchemaVariantError::VariantAuthoring(
Expand All @@ -102,17 +104,11 @@ impl IntoResponse for SchemaVariantError {

pub fn routes() -> Router<AppState> {
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",
post(regenerate_variant::regenerate_variant),
)
.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),
)
}
8 changes: 1 addition & 7 deletions lib/sdf-server/src/server/service/variant/create_variant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use axum::{response::IntoResponse, Json};
use serde::{Deserialize, Serialize};

use dal::schema::variant::authoring::VariantAuthoringClient;
use dal::{ChangeSet, Schema, Visibility, WsEvent};
use dal::{ChangeSet, Visibility, WsEvent};

use crate::server::extract::{AccessBuilder, HandlerContext, PosthogClient};
use crate::server::tracking::track;
Expand All @@ -27,12 +27,6 @@ pub async fn create_variant(
) -> SchemaVariantResult<impl IntoResponse> {
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(
Expand Down
Loading

0 comments on commit 676b53a

Please sign in to comment.