1
//! The `script-create` form submit: an optional name, the source and the state.
2

            
3
use forms::{FormValues, SCRIPT_CREATE};
4
use server::command::CmdResult;
5
use server::command::script::CreateScript;
6
use uuid::Uuid;
7

            
8
use super::Failure;
9
use super::transaction_rows::error_at;
10
use crate::script::{ScriptError, compile_script};
11

            
12
const CTX: &str = "script-create";
13

            
14
/// The source with its bytecode, else a field error at `source` when it does
15
/// not compile.
16
5461
pub(super) fn compiled(values: &FormValues) -> Result<(String, Vec<u8>), Failure> {
17
5461
    let source = values.text("source").unwrap_or_default();
18
5461
    match compile_script(source) {
19
4339
        Ok(bytecode) => Ok((source.to_string(), bytecode)),
20
1122
        Err(ScriptError::Compile(message)) => Err(error_at("source".to_string(), message).into()),
21
        Err(other) => Err(Failure::Internal(wasmtime::Error::msg(format!(
22
            "{CTX}: {other}"
23
        )))),
24
    }
25
5461
}
26

            
27
/// The name, unless it is absent or blank.
28
4339
pub(super) fn named(values: &FormValues) -> Option<String> {
29
4339
    values
30
4339
        .text("name")
31
4339
        .map(str::trim)
32
4335
        .filter(|name| !name.is_empty())
33
4339
        .map(str::to_string)
34
4339
}
35

            
36
/// An absent state keeps the script on.
37
4339
pub(super) fn enabled(values: &FormValues) -> bool {
38
4339
    values.text("enabled") != Some("false")
39
4339
}
40

            
41
/// `script-create` submit: the id of the new script.
42
2893
pub(super) async fn create_script(user_id: Uuid, values: &FormValues) -> Result<Uuid, Failure> {
43
2893
    let errors = values.check(&SCRIPT_CREATE);
44
2893
    if !errors.is_empty() {
45
        return Err(errors.into());
46
2893
    }
47
2893
    let (source, bytecode) = compiled(values)?;
48
2252
    let mut command = CreateScript::new()
49
2252
        .user_id(user_id)
50
2252
        .source(source)
51
2252
        .bytecode(bytecode)
52
2252
        .enabled(enabled(values));
53
2252
    if let Some(name) = named(values) {
54
2248
        command = command.name(name);
55
4
    }
56
2252
    match command
57
2252
        .run()
58
2252
        .await
59
        .map_err(|err| Failure::from_command(CTX, err))?
60
    {
61
2252
        Some(CmdResult::Uuid(id)) => Ok(id),
62
        other => Err(Failure::Internal(wasmtime::Error::msg(format!(
63
            "{CTX}: unexpected create result {other:?}"
64
        )))),
65
    }
66
2893
}