1use sqlx::types::Uuid;
5use supp_macro::command;
6
7use super::{CmdError, CmdResult};
8use crate::error::ServerError;
9use crate::script_run::{RunError, run_on_account};
10use crate::script_state::STALE_SCRIPT;
11use crate::user::User;
12
13command! {
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}
32
33command! {
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 other => other.map(|()| Some(CmdResult::Uuid(script_id))).map_err(Into::into),
56 }
57 }
58}
59
60command! {
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}
73
74command! {
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}