Lines
90.91 %
Functions
88.89 %
Branches
100 %
//! `script-edit` submit: syntax, compile check, then the one `EditScript`
//! command under the script's key locks.
use forms::{FormValues, SCRIPT_EDIT};
use server::command::script::EditScript;
use server::command::{CmdError, CmdResult};
use server::script_state::STALE_SCRIPT;
use server::user::User;
use uuid::Uuid;
use super::Failure;
use super::script_create::{compiled, enabled, named};
use super::transaction_rows::error_at;
const CTX: &str = "submit-form";
/// Validate `script-edit` values and apply the name, the source and the state.
pub(super) async fn edit_script(user_id: Uuid, values: &FormValues) -> Result<Uuid, Failure> {
refuse_bytecode_only_without_source(user_id, values).await?;
let errors = values.check(&SCRIPT_EDIT);
if !errors.is_empty() {
return Err(errors.into());
}
let text = |key| values.text(key).unwrap_or_default();
let script_id = Uuid::parse_str(text("id").trim())
.map_err(|_| error_at("id".to_string(), "unknown script"))?;
let (source, bytecode) = compiled(values)?;
let mut command = EditScript::new()
.user_id(user_id)
.script_id(script_id)
.source(source)
.bytecode(bytecode)
.enabled(enabled(values))
.revision(text("revision").trim().to_string());
if let Some(name) = named(values) {
command = command.name(name);
match command.run().await {
Ok(Some(CmdResult::Uuid(id))) => Ok(id),
Ok(other) => Err(Failure::Internal(wasmtime::Error::msg(format!(
"{CTX}: unexpected edit result {other:?}"
)))),
Err(err) => Err(edit_failure(err)),
/// A script stored without source cannot be saved with an empty one.
async fn refuse_bytecode_only_without_source(
user_id: Uuid,
values: &FormValues,
) -> Result<(), Failure> {
let empty = values
.text("source")
.is_none_or(|text| text.trim().is_empty());
let id = values
.text("id")
.and_then(|id| Uuid::parse_str(id.trim()).ok());
let Some(id) = id.filter(|_| empty) else {
return Ok(());
};
let user = User { id: user_id };
match user.get_script(id).await {
Ok(stored) if stored.source.is_none() => Err(error_at(
"source".to_string(),
"this script was uploaded as bytecode and has no source; supply its source to save it",
)
.into()),
_ => Ok(()),
/// The stale revision is a field error and an unknown script one at `id`; the
/// rest as elsewhere.
fn edit_failure(err: CmdError) -> Failure {
match err {
CmdError::Args(message) if message == STALE_SCRIPT => {
error_at("revision".to_string(), message).into()
err if err.is_missing_row() => error_at("id".to_string(), "unknown script").into(),
other => Failure::from_command(CTX, other),