1
pub 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
        /// False for a script uploaded as bytecode only.
20
        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
49252
    fn artifact_tag(name: &str, value: &str) -> Tag {
48
49252
        Tag {
49
49252
            id: Uuid::new_v4(),
50
49252
            tag_name: name.to_string(),
51
49252
            tag_value: value.to_string(),
52
49252
            description: None,
53
49252
        }
54
49252
    }
55

            
56
    /// A blank name is no name.
57
19291
    fn clean_name(name: Option<String>) -> Option<String> {
58
19291
        name.filter(|name| !name.trim().is_empty())
59
19291
    }
60

            
61
24545
    fn new_artifact_tags(kind: &str, name: Option<String>) -> Vec<Tag> {
62
24545
        let name = name.map(|name| artifact_tag("name", &name));
63
24545
        std::iter::once(artifact_tag("kind", kind))
64
24545
            .chain(name)
65
24545
            .collect()
66
24545
    }
67

            
68
15901
    fn disabled_tag(enabled: bool) -> Option<Tag> {
69
15901
        (!enabled).then(|| artifact_tag("enabled", "false"))
70
15901
    }
71

            
72
183
    fn found(rows: u64) -> Result<(), ServerError> {
73
183
        match rows {
74
2
            0 => Err(db_err(sqlx::Error::RowNotFound)),
75
181
            _ => Ok(()),
76
        }
77
183
    }
78

            
79
1264
    fn db_err(err: sqlx::Error) -> ServerError {
80
1264
        tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
81
1264
        ServerError::DB(DBError::Sqlx(err))
82
1264
    }
83

            
84
    impl User {
85
4695
        pub async fn list_scripts(&self) -> Result<Vec<ScriptInfo>, ServerError> {
86
2903
            let mut conn = self.get_connection().await?;
87

            
88
2743
            let rows = sqlx::query_file!("sql/select/artifacts/by_kind.sql", KIND_AUTOMATION)
89
2743
                .fetch_all(&mut *conn)
90
2743
                .await
91
2743
                .map_err(db_err)?;
92

            
93
2743
            Ok(rows
94
2743
                .into_iter()
95
                .map(|r| ScriptInfo {
96
2430
                    id: r.id,
97
2430
                    name: r.artifact_name,
98
2430
                    size: r.size.unwrap_or(0),
99
2430
                    has_source: r.has_source,
100
2430
                    enabled: r.enabled,
101
2430
                })
102
                .collect())
103
2903
        }
104

            
105
14246
        pub async fn get_script(&self, id: Uuid) -> Result<ScriptDetail, ServerError> {
106
14246
            let mut conn = self.get_connection().await?;
107

            
108
14246
            let row = sqlx::query_file!("sql/select/artifacts/by_id.sql", &id, KIND_AUTOMATION)
109
14246
                .fetch_one(&mut *conn)
110
14246
                .await
111
14246
                .map_err(db_err)?;
112

            
113
12984
            Ok(ScriptDetail {
114
12984
                id: row.id,
115
12984
                name: row.artifact_name,
116
12984
                bytecode: row.bytecode.unwrap_or_default(),
117
12984
                source: row.source_text,
118
12984
                enabled: row.enabled,
119
12984
            })
120
14246
        }
121

            
122
        /// A script stored as bytecode alone, the shape a pre-source script has.
123
        #[cfg(any(test, feature = "test-utils"))]
124
3822
        pub async fn create_script(
125
3822
            &self,
126
3822
            bytecode: Vec<u8>,
127
3822
            name: Option<String>,
128
3822
        ) -> Result<Uuid, ServerError> {
129
63
            self.insert_script(bytecode, None, name, true).await
130
63
        }
131

            
132
        /// Store a script with the `bytecode` compiled from its `source`.
133
7746
        pub async fn create_script_from_source(
134
7746
            &self,
135
7746
            source: String,
136
7746
            bytecode: Vec<u8>,
137
7746
            name: Option<String>,
138
7746
            enabled: bool,
139
7746
        ) -> Result<Uuid, ServerError> {
140
4501
            self.insert_script(bytecode, Some(source), name, enabled)
141
4501
                .await
142
4501
        }
143

            
144
11568
        async fn insert_script(
145
11568
            &self,
146
11568
            bytecode: Vec<u8>,
147
11568
            source: Option<String>,
148
11568
            name: Option<String>,
149
11568
            enabled: bool,
150
11568
        ) -> Result<Uuid, ServerError> {
151
6472
            let mut tags = new_artifact_tags(KIND_AUTOMATION, name);
152
6472
            tags.extend(disabled_tag(enabled));
153
6472
            let tags: Vec<&Tag> = tags.iter().collect();
154
6472
            let mut conn = self.get_connection().await?;
155
6472
            let mut tx = lock::begin(&mut conn).await.map_err(db_err)?;
156
6472
            artifact::lock_new(&mut tx, &tags).await?;
157

            
158
6472
            let id = Uuid::new_v4();
159
6472
            sqlx::query_file!(
160
                "sql/insert/artifacts/artifact.sql",
161
                &id,
162
6472
                Some(&bytecode[..]),
163
                source.as_deref()
164
            )
165
6472
            .execute(&mut *tx)
166
6472
            .await
167
6472
            .map_err(db_err)?;
168

            
169
6472
            artifact::link(&mut tx, id, &tags).await?;
170
6471
            tx.commit().await.map_err(db_err)?;
171
6471
            Ok(id)
172
6472
        }
173

            
174
        /// Replace a script's source and its bytecode in one statement.
175
        ///
176
        /// # Errors
177
        /// A missing script, or a failing write.
178
183
        pub async fn update_script_source(
179
183
            &self,
180
183
            id: Uuid,
181
183
            source: String,
182
183
            bytecode: Vec<u8>,
183
183
        ) -> Result<(), ServerError> {
184
163
            let mut conn = self.get_connection().await?;
185
163
            let done = sqlx::query_file!(
186
                "sql/update/artifacts/script.sql",
187
                &id,
188
                &source,
189
                &bytecode,
190
                KIND_AUTOMATION
191
            )
192
163
            .execute(&mut *conn)
193
163
            .await
194
163
            .map_err(db_err)?;
195
163
            found(done.rows_affected())
196
163
        }
197

            
198
        /// Replace the script's name, enabled state, source and bytecode in one
199
        /// transaction under the name and enabled keys, refusing with
200
        /// [`ServerError::StaleScript`] when it no longer matches `revision`.
201
        ///
202
        /// # Errors
203
        /// A missing script, a stale revision, or a failing write.
204
3787
        pub async fn update_script(
205
3787
            &self,
206
3787
            id: Uuid,
207
3787
            revision: &str,
208
3787
            name: Option<String>,
209
3787
            enabled: bool,
210
3787
            code: (&str, &[u8]),
211
3787
        ) -> Result<(), ServerError> {
212
2254
            let name = clean_name(name).map(|name| artifact_tag("name", &name));
213
2254
            let enabled = disabled_tag(enabled);
214
2254
            let mut conn = self.get_connection().await?;
215
2254
            let mut tries = Tries::default();
216
2254
            while tries
217
2254
                .step(Attempt::of(
218
2254
                    artifact::update_script(
219
2254
                        &mut conn,
220
2254
                        id,
221
2254
                        revision,
222
2254
                        (name.as_ref(), enabled.as_ref()),
223
2254
                        code,
224
2254
                    )
225
2254
                    .await,
226
2254
                    ServerError::is_retryable,
227
2254
                    identity,
228
327
                ))?
229
                .is_none()
230
            {}
231
1927
            Ok(())
232
2254
        }
233

            
234
        /// Whether the script existed.
235
1996
        pub async fn delete_script(&self, id: Uuid) -> Result<bool, ServerError> {
236
1140
            let mut conn = self.get_connection().await?;
237
980
            let found = sqlx::query_file!("sql/select/artifacts/by_id.sql", &id, KIND_AUTOMATION)
238
980
                .fetch_optional(&mut *conn)
239
980
                .await
240
980
                .map_err(db_err)?;
241
980
            drop(conn);
242
980
            match found {
243
494
                Some(_) => self.delete_artifact(id).await,
244
486
                None => Ok(false),
245
            }
246
1140
        }
247

            
248
546
        pub async fn set_script_enabled(&self, id: Uuid, enabled: bool) -> Result<(), ServerError> {
249
9
            self.set_artifact_enabled(id, enabled).await
250
9
        }
251

            
252
5
        pub async fn update_script_name(
253
5
            &self,
254
5
            id: Uuid,
255
5
            name: Option<String>,
256
5
        ) -> Result<(), ServerError> {
257
5
            self.update_artifact_name(id, name).await
258
5
        }
259

            
260
5405
        pub async fn list_templates(&self) -> Result<Vec<TemplateInfo>, ServerError> {
261
1943
            let mut conn = self.get_connection().await?;
262

            
263
1783
            let rows = sqlx::query_file!("sql/select/artifacts/by_kind.sql", KIND_TEMPLATE)
264
1783
                .fetch_all(&mut *conn)
265
1783
                .await
266
1783
                .map_err(db_err)?;
267

            
268
1783
            Ok(rows
269
1783
                .into_iter()
270
                .map(|r| TemplateInfo {
271
1141
                    id: r.id,
272
1141
                    name: r.artifact_name,
273
1141
                    size: r.size.unwrap_or(0),
274
1141
                    enabled: r.enabled,
275
1141
                })
276
                .collect())
277
1943
        }
278

            
279
197
        pub async fn get_template(&self, id: Uuid) -> Result<TemplateDetail, ServerError> {
280
18
            self.find_template(id)
281
18
                .await?
282
18
                .ok_or(ServerError::DB(DBError::Sqlx(sqlx::Error::RowNotFound)))
283
18
        }
284

            
285
15327
        pub async fn find_template(&self, id: Uuid) -> Result<Option<TemplateDetail>, ServerError> {
286
7585
            let mut conn = self.get_connection().await?;
287

            
288
7585
            let row = sqlx::query_file!("sql/select/artifacts/by_id.sql", &id, KIND_TEMPLATE)
289
7585
                .fetch_optional(&mut *conn)
290
7585
                .await
291
7585
                .map_err(db_err)?;
292

            
293
7585
            Ok(row.map(|row| TemplateDetail {
294
6613
                id: row.id,
295
6613
                name: row.artifact_name,
296
6613
                source_text: row.source_text.unwrap_or_default(),
297
6613
                enabled: row.enabled,
298
6613
            }))
299
7585
        }
300

            
301
12977
        pub async fn create_template(
302
12977
            &self,
303
12977
            source: String,
304
12977
            name: Option<String>,
305
12977
        ) -> Result<Uuid, ServerError> {
306
6608
            let tags = new_artifact_tags(KIND_TEMPLATE, clean_name(name));
307
6608
            let tags: Vec<&Tag> = tags.iter().collect();
308
6608
            let mut conn = self.get_connection().await?;
309
6608
            let mut tx = lock::begin(&mut conn).await.map_err(db_err)?;
310
6608
            artifact::lock_new(&mut tx, &tags).await?;
311

            
312
6608
            let id = Uuid::new_v4();
313
6608
            sqlx::query_file!(
314
                "sql/insert/artifacts/artifact.sql",
315
                &id,
316
                None::<&[u8]>,
317
6608
                Some(source.as_str())
318
            )
319
6608
            .execute(&mut *tx)
320
6608
            .await
321
6608
            .map_err(db_err)?;
322

            
323
6608
            artifact::link(&mut tx, id, &tags).await?;
324
6608
            tx.commit().await.map_err(db_err)?;
325
6608
            Ok(id)
326
6608
        }
327

            
328
        /// Replace the template's name and source in one transaction under the
329
        /// name keys, refusing with [`ServerError::StaleTemplate`] when it no
330
        /// longer matches `revision`.
331
        ///
332
        /// # Errors
333
        /// A missing template, a stale revision, or a failing write.
334
2527
        pub async fn update_template(
335
2527
            &self,
336
2527
            id: Uuid,
337
2527
            revision: &str,
338
2527
            name: Option<String>,
339
2527
            source: &str,
340
2527
        ) -> Result<(), ServerError> {
341
975
            let name = clean_name(name).map(|name| artifact_tag("name", &name));
342
975
            let mut conn = self.get_connection().await?;
343
975
            let mut tries = Tries::default();
344
975
            while tries
345
975
                .step(Attempt::of(
346
975
                    artifact::update_template(&mut conn, id, revision, name.as_ref(), source).await,
347
975
                    ServerError::is_retryable,
348
975
                    identity,
349
165
                ))?
350
                .is_none()
351
            {}
352
810
            Ok(())
353
975
        }
354

            
355
        /// Whether the template existed.
356
1265
        pub async fn delete_template(&self, id: Uuid) -> Result<bool, ServerError> {
357
648
            match self.find_template(id).await? {
358
484
                Some(_) => self.delete_artifact(id).await,
359
164
                None => Ok(false),
360
            }
361
648
        }
362

            
363
        /// Lifecycle delete: detach links and drop the row in ONE transaction so
364
        /// the deferred kind-tag DELETE guard sees the parent gone at commit.
365
1814
        async fn delete_artifact(&self, id: Uuid) -> Result<bool, ServerError> {
366
978
            let mut conn = self.get_connection().await?;
367
978
            let mut tries = Tries::default();
368
            loop {
369
980
                let attempt = Attempt::of(
370
980
                    artifact::delete(&mut conn, id).await,
371
980
                    ServerError::is_retryable,
372
980
                    identity,
373
                );
374
980
                if let Some(existed) = tries.step(attempt)? {
375
977
                    return Ok(existed);
376
2
                }
377
            }
378
978
        }
379

            
380
546
        async fn set_artifact_enabled(&self, id: Uuid, enabled: bool) -> Result<(), ServerError> {
381
9
            let tag = disabled_tag(enabled);
382
9
            self.replace_artifact_tag(id, "enabled", tag.as_ref()).await
383
9
        }
384

            
385
5
        async fn update_artifact_name(
386
5
            &self,
387
5
            id: Uuid,
388
5
            name: Option<String>,
389
5
        ) -> Result<(), ServerError> {
390
5
            let tag = name.map(|name| artifact_tag("name", &name));
391
5
            self.replace_artifact_tag(id, "name", tag.as_ref()).await
392
5
        }
393

            
394
551
        async fn replace_artifact_tag(
395
551
            &self,
396
551
            id: Uuid,
397
551
            name: &str,
398
551
            tag: Option<&Tag>,
399
551
        ) -> Result<(), ServerError> {
400
14
            let mut conn = self.get_connection().await?;
401
14
            let mut tries = Tries::default();
402
17
            while tries
403
17
                .step(Attempt::of(
404
17
                    artifact::replace(&mut conn, id, name, tag).await,
405
17
                    ServerError::is_retryable,
406
17
                    identity,
407
1
                ))?
408
                .is_none()
409
3
            {}
410
13
            Ok(())
411
14
        }
412
    }
413
}
414

            
415
#[cfg(test)]
416
mod artifact_mgmt_tests;