1pub mod user {
2 use crate::attempt::{Attempt, Tries};
3 use crate::db::DBError;
4 use crate::error::ServerError;
5 use crate::tag::{artifact, lock};
6 use crate::user::User;
7 use finance::tag::Tag;
8
9 use sqlx::types::Uuid;
10 use std::convert::identity;
11
12 pub(crate) const KIND_AUTOMATION: &str = "automation";
13 const KIND_TEMPLATE: &str = "template";
14
15 pub struct ScriptInfo {
16 pub id: Uuid,
17 pub name: Option<String>,
18 pub size: i32,
19 pub has_source: bool,
21 pub enabled: Option<String>,
22 }
23
24 pub struct ScriptDetail {
25 pub id: Uuid,
26 pub name: Option<String>,
27 pub bytecode: Vec<u8>,
28 pub source: Option<String>,
29 pub enabled: Option<String>,
30 }
31
32 #[derive(Debug, Clone, PartialEq, Eq)]
33 pub struct TemplateInfo {
34 pub id: Uuid,
35 pub name: Option<String>,
36 pub size: i32,
37 pub enabled: Option<String>,
38 }
39
40 pub struct TemplateDetail {
41 pub id: Uuid,
42 pub name: Option<String>,
43 pub source_text: String,
44 pub enabled: Option<String>,
45 }
46
47 fn artifact_tag(name: &str, value: &str) -> Tag {
48 Tag {
49 id: Uuid::new_v4(),
50 tag_name: name.to_string(),
51 tag_value: value.to_string(),
52 description: None,
53 }
54 }
55
56 fn clean_name(name: Option<String>) -> Option<String> {
58 name.filter(|name| !name.trim().is_empty())
59 }
60
61 fn new_artifact_tags(kind: &str, name: Option<String>) -> Vec<Tag> {
62 let name = name.map(|name| artifact_tag("name", &name));
63 std::iter::once(artifact_tag("kind", kind))
64 .chain(name)
65 .collect()
66 }
67
68 fn disabled_tag(enabled: bool) -> Option<Tag> {
69 (!enabled).then(|| artifact_tag("enabled", "false"))
70 }
71
72 fn found(rows: u64) -> Result<(), ServerError> {
73 match rows {
74 0 => Err(db_err(sqlx::Error::RowNotFound)),
75 _ => Ok(()),
76 }
77 }
78
79 fn db_err(err: sqlx::Error) -> ServerError {
80 tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
81 ServerError::DB(DBError::Sqlx(err))
82 }
83
84 impl User {
85 pub async fn list_scripts(&self) -> Result<Vec<ScriptInfo>, ServerError> {
86 let mut conn = self.get_connection().await?;
87
88 let rows = sqlx::query_file!("sql/select/artifacts/by_kind.sql", KIND_AUTOMATION)
89 .fetch_all(&mut *conn)
90 .await
91 .map_err(db_err)?;
92
93 Ok(rows
94 .into_iter()
95 .map(|r| ScriptInfo {
96 id: r.id,
97 name: r.artifact_name,
98 size: r.size.unwrap_or(0),
99 has_source: r.has_source,
100 enabled: r.enabled,
101 })
102 .collect())
103 }
104
105 pub async fn get_script(&self, id: Uuid) -> Result<ScriptDetail, ServerError> {
106 let mut conn = self.get_connection().await?;
107
108 let row = sqlx::query_file!("sql/select/artifacts/by_id.sql", &id, KIND_AUTOMATION)
109 .fetch_one(&mut *conn)
110 .await
111 .map_err(db_err)?;
112
113 Ok(ScriptDetail {
114 id: row.id,
115 name: row.artifact_name,
116 bytecode: row.bytecode.unwrap_or_default(),
117 source: row.source_text,
118 enabled: row.enabled,
119 })
120 }
121
122 #[cfg(any(test, feature = "test-utils"))]
124 pub async fn create_script(
125 &self,
126 bytecode: Vec<u8>,
127 name: Option<String>,
128 ) -> Result<Uuid, ServerError> {
129 self.insert_script(bytecode, None, name, true).await
130 }
131
132 pub async fn create_script_from_source(
134 &self,
135 source: String,
136 bytecode: Vec<u8>,
137 name: Option<String>,
138 enabled: bool,
139 ) -> Result<Uuid, ServerError> {
140 self.insert_script(bytecode, Some(source), name, enabled)
141 .await
142 }
143
144 async fn insert_script(
145 &self,
146 bytecode: Vec<u8>,
147 source: Option<String>,
148 name: Option<String>,
149 enabled: bool,
150 ) -> Result<Uuid, ServerError> {
151 let mut tags = new_artifact_tags(KIND_AUTOMATION, name);
152 tags.extend(disabled_tag(enabled));
153 let tags: Vec<&Tag> = tags.iter().collect();
154 let mut conn = self.get_connection().await?;
155 let mut tx = lock::begin(&mut conn).await.map_err(db_err)?;
156 artifact::lock_new(&mut tx, &tags).await?;
157
158 let id = Uuid::new_v4();
159 sqlx::query_file!(
160 "sql/insert/artifacts/artifact.sql",
161 &id,
162 Some(&bytecode[..]),
163 source.as_deref()
164 )
165 .execute(&mut *tx)
166 .await
167 .map_err(db_err)?;
168
169 artifact::link(&mut tx, id, &tags).await?;
170 tx.commit().await.map_err(db_err)?;
171 Ok(id)
172 }
173
174 pub async fn update_script_source(
179 &self,
180 id: Uuid,
181 source: String,
182 bytecode: Vec<u8>,
183 ) -> Result<(), ServerError> {
184 let mut conn = self.get_connection().await?;
185 let done = sqlx::query_file!(
186 "sql/update/artifacts/script.sql",
187 &id,
188 &source,
189 &bytecode,
190 KIND_AUTOMATION
191 )
192 .execute(&mut *conn)
193 .await
194 .map_err(db_err)?;
195 found(done.rows_affected())
196 }
197
198 pub async fn update_script(
205 &self,
206 id: Uuid,
207 revision: &str,
208 name: Option<String>,
209 enabled: bool,
210 code: (&str, &[u8]),
211 ) -> Result<(), ServerError> {
212 let name = clean_name(name).map(|name| artifact_tag("name", &name));
213 let enabled = disabled_tag(enabled);
214 let mut conn = self.get_connection().await?;
215 let mut tries = Tries::default();
216 while tries
217 .step(Attempt::of(
218 artifact::update_script(
219 &mut conn,
220 id,
221 revision,
222 (name.as_ref(), enabled.as_ref()),
223 code,
224 )
225 .await,
226 ServerError::is_retryable,
227 identity,
228 ))?
229 .is_none()
230 {}
231 Ok(())
232 }
233
234 pub async fn delete_script(&self, id: Uuid) -> Result<bool, ServerError> {
236 let mut conn = self.get_connection().await?;
237 let found = sqlx::query_file!("sql/select/artifacts/by_id.sql", &id, KIND_AUTOMATION)
238 .fetch_optional(&mut *conn)
239 .await
240 .map_err(db_err)?;
241 drop(conn);
242 match found {
243 Some(_) => self.delete_artifact(id).await,
244 None => Ok(false),
245 }
246 }
247
248 pub async fn set_script_enabled(&self, id: Uuid, enabled: bool) -> Result<(), ServerError> {
249 self.set_artifact_enabled(id, enabled).await
250 }
251
252 pub async fn update_script_name(
253 &self,
254 id: Uuid,
255 name: Option<String>,
256 ) -> Result<(), ServerError> {
257 self.update_artifact_name(id, name).await
258 }
259
260 pub async fn list_templates(&self) -> Result<Vec<TemplateInfo>, ServerError> {
261 let mut conn = self.get_connection().await?;
262
263 let rows = sqlx::query_file!("sql/select/artifacts/by_kind.sql", KIND_TEMPLATE)
264 .fetch_all(&mut *conn)
265 .await
266 .map_err(db_err)?;
267
268 Ok(rows
269 .into_iter()
270 .map(|r| TemplateInfo {
271 id: r.id,
272 name: r.artifact_name,
273 size: r.size.unwrap_or(0),
274 enabled: r.enabled,
275 })
276 .collect())
277 }
278
279 pub async fn get_template(&self, id: Uuid) -> Result<TemplateDetail, ServerError> {
280 self.find_template(id)
281 .await?
282 .ok_or(ServerError::DB(DBError::Sqlx(sqlx::Error::RowNotFound)))
283 }
284
285 pub async fn find_template(&self, id: Uuid) -> Result<Option<TemplateDetail>, ServerError> {
286 let mut conn = self.get_connection().await?;
287
288 let row = sqlx::query_file!("sql/select/artifacts/by_id.sql", &id, KIND_TEMPLATE)
289 .fetch_optional(&mut *conn)
290 .await
291 .map_err(db_err)?;
292
293 Ok(row.map(|row| TemplateDetail {
294 id: row.id,
295 name: row.artifact_name,
296 source_text: row.source_text.unwrap_or_default(),
297 enabled: row.enabled,
298 }))
299 }
300
301 pub async fn create_template(
302 &self,
303 source: String,
304 name: Option<String>,
305 ) -> Result<Uuid, ServerError> {
306 let tags = new_artifact_tags(KIND_TEMPLATE, clean_name(name));
307 let tags: Vec<&Tag> = tags.iter().collect();
308 let mut conn = self.get_connection().await?;
309 let mut tx = lock::begin(&mut conn).await.map_err(db_err)?;
310 artifact::lock_new(&mut tx, &tags).await?;
311
312 let id = Uuid::new_v4();
313 sqlx::query_file!(
314 "sql/insert/artifacts/artifact.sql",
315 &id,
316 None::<&[u8]>,
317 Some(source.as_str())
318 )
319 .execute(&mut *tx)
320 .await
321 .map_err(db_err)?;
322
323 artifact::link(&mut tx, id, &tags).await?;
324 tx.commit().await.map_err(db_err)?;
325 Ok(id)
326 }
327
328 pub async fn update_template(
335 &self,
336 id: Uuid,
337 revision: &str,
338 name: Option<String>,
339 source: &str,
340 ) -> Result<(), ServerError> {
341 let name = clean_name(name).map(|name| artifact_tag("name", &name));
342 let mut conn = self.get_connection().await?;
343 let mut tries = Tries::default();
344 while tries
345 .step(Attempt::of(
346 artifact::update_template(&mut conn, id, revision, name.as_ref(), source).await,
347 ServerError::is_retryable,
348 identity,
349 ))?
350 .is_none()
351 {}
352 Ok(())
353 }
354
355 pub async fn delete_template(&self, id: Uuid) -> Result<bool, ServerError> {
357 match self.find_template(id).await? {
358 Some(_) => self.delete_artifact(id).await,
359 None => Ok(false),
360 }
361 }
362
363 async fn delete_artifact(&self, id: Uuid) -> Result<bool, ServerError> {
366 let mut conn = self.get_connection().await?;
367 let mut tries = Tries::default();
368 loop {
369 let attempt = Attempt::of(
370 artifact::delete(&mut conn, id).await,
371 ServerError::is_retryable,
372 identity,
373 );
374 if let Some(existed) = tries.step(attempt)? {
375 return Ok(existed);
376 }
377 }
378 }
379
380 async fn set_artifact_enabled(&self, id: Uuid, enabled: bool) -> Result<(), ServerError> {
381 let tag = disabled_tag(enabled);
382 self.replace_artifact_tag(id, "enabled", tag.as_ref()).await
383 }
384
385 async fn update_artifact_name(
386 &self,
387 id: Uuid,
388 name: Option<String>,
389 ) -> Result<(), ServerError> {
390 let tag = name.map(|name| artifact_tag("name", &name));
391 self.replace_artifact_tag(id, "name", tag.as_ref()).await
392 }
393
394 async fn replace_artifact_tag(
395 &self,
396 id: Uuid,
397 name: &str,
398 tag: Option<&Tag>,
399 ) -> Result<(), ServerError> {
400 let mut conn = self.get_connection().await?;
401 let mut tries = Tries::default();
402 while tries
403 .step(Attempt::of(
404 artifact::replace(&mut conn, id, name, tag).await,
405 ServerError::is_retryable,
406 identity,
407 ))?
408 .is_none()
409 {}
410 Ok(())
411 }
412 }
413}
414
415#[cfg(test)]
416mod artifact_mgmt_tests;