1
//! Script rows as the script forms and natives edit them. The caller compiles
2
//! the source; the commands store source and bytecode together.
3

            
4
use sqlx::types::Uuid;
5
use supp_macro::command;
6

            
7
use super::{CmdError, CmdResult};
8
use crate::error::ServerError;
9
use crate::script_run::{RunError, run_on_account};
10
use crate::script_state::STALE_SCRIPT;
11
use crate::user::User;
12

            
13
command! {
14
    CreateScript {
15
        #[required]
16
        user_id: Uuid,
17
        #[required]
18
        source: String,
19
        #[required]
20
        bytecode: Vec<u8>,
21
        #[required]
22
        enabled: bool,
23
        #[optional]
24
        name: String,
25
    } => {
26
        let id = User { id: user_id }
27
            .create_script_from_source(source, bytecode, name, enabled)
28
            .await?;
29
        Ok(Some(CmdResult::Uuid(id)))
30
    }
31
29652
}
32

            
33
command! {
34
    EditScript {
35
        #[required]
36
        user_id: Uuid,
37
        #[required]
38
        script_id: Uuid,
39
        #[required]
40
        source: String,
41
        #[required]
42
        bytecode: Vec<u8>,
43
        #[required]
44
        enabled: bool,
45
        #[optional]
46
        name: String,
47
        #[required]
48
        revision: String,
49
    } => {
50
        let updated = User { id: user_id }
51
            .update_script(script_id, &revision, name, enabled, (&source, &bytecode))
52
            .await;
53
        match updated {
54
            Err(ServerError::StaleScript) => Err(CmdError::Args(STALE_SCRIPT.to_string())),
55
1927
            other => other.map(|()| Some(CmdResult::Uuid(script_id))).map_err(Into::into),
56
        }
57
    }
58
32007
}
59

            
60
command! {
61
    DeleteScript {
62
        #[required]
63
        user_id: Uuid,
64
        #[required]
65
        script_id: Uuid,
66
    } => {
67
        match (User { id: user_id }).delete_script(script_id).await? {
68
            true => Ok(Some(CmdResult::Bool(true))),
69
            false => Err(CmdError::NotFound(format!("no script {script_id}"))),
70
        }
71
    }
72
6535
}
73

            
74
command! {
75
    RunScriptOnAccount {
76
        #[required]
77
        user_id: Uuid,
78
        #[required]
79
        script_id: Uuid,
80
        #[required]
81
        account_id: Uuid,
82
    } => {
83
        match run_on_account(&User { id: user_id }, script_id, account_id).await {
84
            Ok(run) => Ok(Some(CmdResult::ScriptRun(run))),
85
            Err(err @ RunError::Refused { .. }) => Err(CmdError::Refused(err.to_string())),
86
            Err(err @ RunError::ScriptNotFound) => Err(CmdError::NotFound(err.to_string())),
87
            Err(RunError::Failed { source: err, .. } | RunError::Server(err)) => Err(err.into()),
88
        }
89
    }
90
9054
}