1
use crate::db::install_test_pool;
2
use crate::user::User;
3
use sqlx::PgPool;
4
use sqlx::types::Uuid;
5
use supp_macro::local_db_sqlx_test;
6
use tokio::sync::OnceCell;
7

            
8
static USER: OnceCell<User> = OnceCell::const_new();
9

            
10
25
async fn setup() {
11
50
    USER.get_or_init(|| async { User { id: Uuid::new_v4() } })
12
25
        .await;
13
25
}
14

            
15
25
async fn user() -> &'static User {
16
25
    let user = USER.get().unwrap();
17
25
    user.commit()
18
25
        .await
19
25
        .expect("Failed to commit user to database");
20
25
    user
21
25
}
22

            
23
#[local_db_sqlx_test]
24
async fn test_create_and_list_scripts(pool: PgPool) -> Result<(), anyhow::Error> {
25
    let user = user().await;
26
    let bytecode = vec![0x00, 0x61, 0x73, 0x6d];
27

            
28
    let id = user.create_script(bytecode.clone(), None).await?;
29
    assert!(!id.is_nil());
30

            
31
    let scripts = user.list_scripts().await?;
32
    assert_eq!(scripts.len(), 1);
33
    assert_eq!(scripts[0].id, id);
34
    assert_eq!(scripts[0].size, bytecode.len() as i32);
35
    assert!(scripts[0].name.is_none());
36
}
37

            
38
#[local_db_sqlx_test]
39
async fn test_create_script_with_name(pool: PgPool) -> Result<(), anyhow::Error> {
40
    let user = user().await;
41
    let bytecode = vec![0x00, 0x61, 0x73, 0x6d];
42
    let name = "test_script".to_string();
43

            
44
    user.create_script(bytecode, Some(name.clone())).await?;
45

            
46
    let scripts = user.list_scripts().await?;
47
    assert_eq!(scripts.len(), 1);
48
    assert_eq!(scripts[0].name, Some(name));
49
}
50

            
51
#[local_db_sqlx_test]
52
async fn test_get_script(pool: PgPool) -> Result<(), anyhow::Error> {
53
    let user = user().await;
54
    let bytecode = vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
55
    let name = "fetch_test".to_string();
56

            
57
    let id = user
58
        .create_script(bytecode.clone(), Some(name.clone()))
59
        .await?;
60

            
61
    let script = user.get_script(id).await?;
62
    assert_eq!(script.id, id);
63
    assert_eq!(script.bytecode, bytecode);
64
    assert_eq!(script.name, Some(name));
65
}
66

            
67
#[local_db_sqlx_test]
68
async fn test_delete_script(pool: PgPool) -> Result<(), anyhow::Error> {
69
    let user = user().await;
70
    let bytecode = vec![0x00, 0x61, 0x73, 0x6d];
71

            
72
    let id = user
73
        .create_script(bytecode, Some("to_delete".to_string()))
74
        .await?;
75
    assert_eq!(user.list_scripts().await?.len(), 1);
76

            
77
    assert!(user.delete_script(id).await?);
78
    assert!(user.list_scripts().await?.is_empty());
79
    assert!(!user.delete_script(id).await?);
80
}
81

            
82
#[local_db_sqlx_test]
83
async fn test_delete_script_does_not_touch_a_template(pool: PgPool) -> Result<(), anyhow::Error> {
84
    let user = user().await;
85
    let template = user.create_template("(a)".to_string(), None).await?;
86

            
87
    assert!(!user.delete_script(template).await?);
88
    assert!(user.find_template(template).await?.is_some());
89
}
90

            
91
#[local_db_sqlx_test]
92
async fn test_set_script_enabled(pool: PgPool) -> Result<(), anyhow::Error> {
93
    let user = user().await;
94
    let bytecode = vec![0x00, 0x61, 0x73, 0x6d];
95

            
96
    let id = user.create_script(bytecode, None).await?;
97
    assert!(user.get_script(id).await?.enabled.is_none());
98

            
99
    user.set_script_enabled(id, false).await?;
100
    assert_eq!(
101
        user.get_script(id).await?.enabled,
102
        Some("false".to_string())
103
    );
104

            
105
    user.set_script_enabled(id, true).await?;
106
    assert!(user.get_script(id).await?.enabled.is_none());
107
}
108

            
109
#[local_db_sqlx_test]
110
async fn test_update_script_name(pool: PgPool) -> Result<(), anyhow::Error> {
111
    let user = user().await;
112
    let bytecode = vec![0x00, 0x61, 0x73, 0x6d];
113

            
114
    let id = user
115
        .create_script(bytecode, Some("original_name".to_string()))
116
        .await?;
117
    assert_eq!(
118
        user.get_script(id).await?.name,
119
        Some("original_name".to_string())
120
    );
121

            
122
    user.update_script_name(id, Some("new_name".to_string()))
123
        .await?;
124
    assert_eq!(
125
        user.get_script(id).await?.name,
126
        Some("new_name".to_string())
127
    );
128

            
129
    user.update_script_name(id, None).await?;
130
    assert!(user.get_script(id).await?.name.is_none());
131
}
132

            
133
#[local_db_sqlx_test]
134
async fn test_multiple_scripts(pool: PgPool) -> Result<(), anyhow::Error> {
135
    let user = user().await;
136

            
137
    let id1 = user
138
        .create_script(vec![0x01], Some("script1".to_string()))
139
        .await?;
140
    let id2 = user
141
        .create_script(vec![0x02, 0x03], Some("script2".to_string()))
142
        .await?;
143
    let id3 = user.create_script(vec![0x04, 0x05, 0x06], None).await?;
144

            
145
3
    let ids: Vec<Uuid> = user.list_scripts().await?.iter().map(|s| s.id).collect();
146
    assert_eq!(ids.len(), 3);
147
    assert!(ids.contains(&id1) && ids.contains(&id2) && ids.contains(&id3));
148

            
149
    user.delete_script(id2).await?;
150
2
    let ids: Vec<Uuid> = user.list_scripts().await?.iter().map(|s| s.id).collect();
151
    assert_eq!(ids.len(), 2);
152
    assert!(ids.contains(&id1) && !ids.contains(&id2) && ids.contains(&id3));
153
}
154

            
155
#[local_db_sqlx_test]
156
async fn test_template_crud_round_trip(pool: PgPool) -> Result<(), anyhow::Error> {
157
    let user = user().await;
158
    let source = "(set-draft-note \"Groceries\")".to_string();
159

            
160
    let id = user
161
        .create_template(source.clone(), Some("groceries".to_string()))
162
        .await?;
163

            
164
    let detail = user.get_template(id).await?;
165
    assert_eq!(detail.source_text, source);
166
    assert_eq!(detail.name, Some("groceries".to_string()));
167

            
168
    let templates = user.list_templates().await?;
169
    assert_eq!(templates.len(), 1);
170
    assert_eq!(templates[0].id, id);
171

            
172
    let revision = user.get_template(id).await?.revision();
173
    user.update_template(
174
        id,
175
        &revision,
176
        Some("rent".to_string()),
177
        "(set-draft-note \"Rent\")",
178
    )
179
    .await?;
180
    let updated = user.get_template(id).await?;
181
    assert_eq!(updated.source_text, "(set-draft-note \"Rent\")");
182
    assert_eq!(updated.name, Some("rent".to_string()));
183

            
184
1
    assert_eq!(user.find_template(id).await?.map(|t| t.id), Some(id));
185
    assert!(user.delete_template(id).await?);
186
    assert!(!user.delete_template(id).await?);
187
    assert!(user.list_templates().await?.is_empty());
188
    assert!(user.find_template(id).await?.is_none());
189
    assert!(user.get_template(id).await.is_err());
190
}
191

            
192
/// Scripts and templates are isolated by kind: a template never shows up in the
193
/// script listing and vice versa.
194
#[local_db_sqlx_test]
195
async fn test_kind_isolation(pool: PgPool) -> Result<(), anyhow::Error> {
196
    let user = user().await;
197

            
198
    let script_id = user.create_script(vec![0x00, 0x61], None).await?;
199
    let template_id = user
200
        .create_template("(set-draft-note \"x\")".to_string(), None)
201
        .await?;
202

            
203
1
    let script_ids: Vec<Uuid> = user.list_scripts().await?.iter().map(|s| s.id).collect();
204
    assert_eq!(script_ids, vec![script_id]);
205

            
206
1
    let template_ids: Vec<Uuid> = user.list_templates().await?.iter().map(|t| t.id).collect();
207
    assert_eq!(template_ids, vec![template_id]);
208

            
209
    assert!(user.get_script(template_id).await.is_err());
210
    assert!(user.get_template(script_id).await.is_err());
211
}
212

            
213
/// Two artifacts sharing the same canonical `name`/`enabled` tag values both
214
/// link correctly — the canonical-id-propagation fix. Before the fix, the
215
/// second create linked a dangling fresh uuid and the FK insert failed.
216
#[local_db_sqlx_test]
217
async fn test_shared_canonical_tag_values(pool: PgPool) -> Result<(), anyhow::Error> {
218
    let user = user().await;
219

            
220
    let id1 = user
221
        .create_script(vec![0x01], Some("shared".to_string()))
222
        .await?;
223
    let id2 = user
224
        .create_script(vec![0x02], Some("shared".to_string()))
225
        .await?;
226

            
227
    user.set_script_enabled(id1, false).await?;
228
    user.set_script_enabled(id2, false).await?;
229

            
230
    let scripts = user.list_scripts().await?;
231
    assert_eq!(scripts.len(), 2);
232
    for s in &scripts {
233
        assert_eq!(s.name, Some("shared".to_string()));
234
        assert_eq!(s.enabled, Some("false".to_string()));
235
    }
236
1
    assert!(scripts.iter().any(|s| s.id == id1));
237
2
    assert!(scripts.iter().any(|s| s.id == id2));
238
}
239

            
240
/// Deleting one of two artifacts sharing the canonical `kind` tag succeeds
241
/// (artifact-lifecycle delete — parent gone at commit, deferred guard passes).
242
#[local_db_sqlx_test]
243
async fn test_lifecycle_delete_with_shared_kind(pool: PgPool) -> Result<(), anyhow::Error> {
244
    let user = user().await;
245

            
246
    let id1 = user.create_script(vec![0x01], None).await?;
247
    let id2 = user.create_script(vec![0x02], None).await?;
248

            
249
    user.delete_script(id1).await?;
250

            
251
1
    let remaining: Vec<Uuid> = user.list_scripts().await?.iter().map(|s| s.id).collect();
252
    assert_eq!(remaining, vec![id2]);
253
}
254

            
255
/// Resolve the canonical id of the `kind` tag linked to an artifact.
256
6
async fn kind_tag_id(pool: &PgPool, artifact_id: Uuid) -> Uuid {
257
6
    sqlx::query_scalar::<_, Uuid>(
258
6
        "SELECT at.tag_id FROM artifact_tags at \
259
6
         INNER JOIN tags t ON t.id = at.tag_id \
260
6
         WHERE at.artifact_id = $1 AND t.tag_name = 'kind'",
261
6
    )
262
6
    .bind(artifact_id)
263
6
    .fetch_one(pool)
264
6
    .await
265
6
    .expect("kind tag must be linked")
266
6
}
267

            
268
/// The auto-run selector is fail-closed: a source-only template is never
269
/// returned, while an automation is. This is the load-bearing execution guard.
270
#[local_db_sqlx_test]
271
async fn test_template_never_in_autorun(pool: PgPool) -> Result<(), anyhow::Error> {
272
    let user = user().await;
273

            
274
    let script_id = user
275
        .create_script(vec![0x00, 0x61, 0x73, 0x6d], None)
276
        .await?;
277
    user.create_template("(set-draft-note \"x\")".to_string(), None)
278
        .await?;
279

            
280
    let enabled: Vec<Uuid> = sqlx::query_file!("sql/select/artifacts/enabled.sql")
281
        .fetch_all(&pool)
282
        .await?
283
        .into_iter()
284
1
        .map(|r| r.id)
285
        .collect();
286

            
287
    assert_eq!(enabled, vec![script_id]);
288
}
289

            
290
/// The DB rejects a second `kind` tag on one artifact (one-kind invariant).
291
#[local_db_sqlx_test]
292
async fn test_db_rejects_second_kind_tag(pool: PgPool) -> Result<(), anyhow::Error> {
293
    let user = user().await;
294
    let id = user.create_script(vec![0x01], None).await?;
295

            
296
    // Upsert a kind=template tag row, then try to also link it.
297
    let template_tag: Uuid = sqlx::query_scalar(
298
        "INSERT INTO tags (id, tag_name, tag_value) VALUES ($1, 'kind', 'template') \
299
         ON CONFLICT (tag_name, tag_value) DO UPDATE SET tag_value = excluded.tag_value \
300
         RETURNING id",
301
    )
302
    .bind(Uuid::new_v4())
303
    .fetch_one(&pool)
304
    .await?;
305

            
306
    let result = sqlx::query("INSERT INTO artifact_tags (artifact_id, tag_id) VALUES ($1, $2)")
307
        .bind(id)
308
        .bind(template_tag)
309
        .execute(&pool)
310
        .await;
311

            
312
    assert!(result.is_err(), "second kind tag must be rejected");
313
}
314

            
315
/// The DB rejects tagging a source-only artifact as automation (kind<->shape):
316
/// an automation must carry bytecode.
317
#[local_db_sqlx_test]
318
async fn test_db_rejects_kind_shape_mismatch(pool: PgPool) -> Result<(), anyhow::Error> {
319
    let user = user().await;
320
    let id = user
321
        .create_template("(set-draft-note \"x\")".to_string(), None)
322
        .await?;
323

            
324
    let template_kind = kind_tag_id(&pool, id).await;
325

            
326
    // Detach the correct kind=template, then attempt kind=automation.
327
    sqlx::query("DELETE FROM artifact_tags WHERE artifact_id = $1 AND tag_id = $2")
328
        .bind(id)
329
        .bind(template_kind)
330
        .execute(&pool)
331
        .await
332
        .ok();
333

            
334
    let automation_tag: Uuid = sqlx::query_scalar(
335
        "INSERT INTO tags (id, tag_name, tag_value) VALUES ($1, 'kind', 'automation') \
336
         ON CONFLICT (tag_name, tag_value) DO UPDATE SET tag_value = excluded.tag_value \
337
         RETURNING id",
338
    )
339
    .bind(Uuid::new_v4())
340
    .fetch_one(&pool)
341
    .await?;
342

            
343
    let result = sqlx::query("INSERT INTO artifact_tags (artifact_id, tag_id) VALUES ($1, $2)")
344
        .bind(id)
345
        .bind(automation_tag)
346
        .execute(&pool)
347
        .await;
348

            
349
    assert!(
350
        result.is_err(),
351
        "tagging a source-only artifact as automation must be rejected"
352
    );
353
}
354

            
355
/// The DB rejects a generic unlink of a `kind` tag while the artifact survives
356
/// (the deferred DELETE guard distinguishes lifecycle delete from unlink).
357
#[local_db_sqlx_test]
358
async fn test_db_rejects_generic_kind_unlink(pool: PgPool) -> Result<(), anyhow::Error> {
359
    let user = user().await;
360
    let id = user.create_script(vec![0x01], None).await?;
361
    let kind_tag = kind_tag_id(&pool, id).await;
362

            
363
    let result = sqlx::query("DELETE FROM artifact_tags WHERE artifact_id = $1 AND tag_id = $2")
364
        .bind(id)
365
        .bind(kind_tag)
366
        .execute(&pool)
367
        .await;
368

            
369
    assert!(
370
        result.is_err(),
371
        "unlinking a kind tag from a surviving artifact must be rejected"
372
    );
373
}
374

            
375
/// The DB rejects deleting a `kind` tag row that is still referenced
376
/// (the shared-canonical DELETE vector via `delete_tag`).
377
#[local_db_sqlx_test]
378
async fn test_db_rejects_referenced_kind_tag_delete(pool: PgPool) -> Result<(), anyhow::Error> {
379
    let user = user().await;
380
    let id = user.create_script(vec![0x01], None).await?;
381
    let kind_tag = kind_tag_id(&pool, id).await;
382

            
383
    let result = sqlx::query("DELETE FROM tags WHERE id = $1")
384
        .bind(kind_tag)
385
        .execute(&pool)
386
        .await;
387

            
388
    assert!(
389
        result.is_err(),
390
        "deleting a referenced kind tag must be rejected"
391
    );
392
}
393

            
394
/// The DB rejects renaming a linked `kind` tag into a value inconsistent with
395
/// the artifact's shape (the canonical-rename vector via `update_tag`).
396
#[local_db_sqlx_test]
397
async fn test_db_rejects_kind_tag_rename(pool: PgPool) -> Result<(), anyhow::Error> {
398
    let user = user().await;
399
    let id = user.create_script(vec![0x01], None).await?;
400
    let kind_tag = kind_tag_id(&pool, id).await;
401

            
402
    // Flip automation -> template on an artifact that carries bytecode.
403
    let result = sqlx::query("UPDATE tags SET tag_value = 'template' WHERE id = $1")
404
        .bind(kind_tag)
405
        .execute(&pool)
406
        .await;
407

            
408
    assert!(
409
        result.is_err(),
410
        "flipping a linked kind tag to an inconsistent value must be rejected"
411
    );
412
}
413

            
414
/// Renaming a linked `kind` tag to a NON-kind name (so the artifact would end
415
/// up with zero kind tags) is rejected by the exactly-one-kind invariant. This
416
/// is the `update_tag`-orphan vector: a generic tag rename must not strip the
417
/// discriminator off a live artifact.
418
#[local_db_sqlx_test]
419
async fn test_db_rejects_kind_tag_rename_to_non_kind(pool: PgPool) -> Result<(), anyhow::Error> {
420
    let user = user().await;
421
    let id = user.create_script(vec![0x01], None).await?;
422

            
423
    let result = user
424
        .rename_tag(
425
            kind_tag_id(&pool, id).await,
426
            "category".to_string(),
427
            "misc".to_string(),
428
            None,
429
        )
430
        .await;
431

            
432
    assert!(
433
        result.is_err(),
434
        "renaming a linked kind tag to a non-kind must be rejected (would orphan)"
435
    );
436
}
437

            
438
/// A raw `INSERT INTO artifacts` with no kind tag cannot commit — the deferred
439
/// artifacts trigger requires exactly one kind tag at commit.
440
#[local_db_sqlx_test]
441
async fn test_db_rejects_artifact_without_kind(pool: PgPool) -> Result<(), anyhow::Error> {
442
    user().await;
443

            
444
    let result =
445
        sqlx::query("INSERT INTO artifacts (id, bytecode, source_text) VALUES ($1, $2, NULL)")
446
            .bind(Uuid::new_v4())
447
            .bind(vec![0x01u8])
448
            .execute(&pool)
449
            .await;
450

            
451
    assert!(
452
        result.is_err(),
453
        "an artifact with no kind tag must not commit"
454
    );
455
}
456

            
457
/// Moving a `kind` link off one artifact onto another (raw UPDATE of
458
/// `artifact_tags.artifact_id`) is rejected: the old owner would be left
459
/// kindless. Validates the old-owner re-check on UPDATE.
460
#[local_db_sqlx_test]
461
async fn test_db_rejects_kind_link_move(pool: PgPool) -> Result<(), anyhow::Error> {
462
    let user = user().await;
463
    let donor = user.create_script(vec![0x01], None).await?;
464
    let recipient = user.create_script(vec![0x02], None).await?;
465
    let donor_kind_link = kind_tag_id(&pool, donor).await;
466

            
467
    // Repoint the donor's kind link to the recipient — donor is left kindless,
468
    // recipient ends up with two kind tags. Either way: rejected.
469
    let result = sqlx::query(
470
        "UPDATE artifact_tags SET artifact_id = $1 \
471
         WHERE artifact_id = $2 AND tag_id = $3",
472
    )
473
    .bind(recipient)
474
    .bind(donor)
475
    .bind(donor_kind_link)
476
    .execute(&pool)
477
    .await;
478

            
479
    assert!(
480
        result.is_err(),
481
        "moving a kind link off its artifact must be rejected"
482
    );
483
}
484

            
485
#[local_db_sqlx_test]
486
async fn artifact_names_are_stored_trimmed_and_blank_ones_refused(
487
    pool: PgPool,
488
) -> Result<(), anyhow::Error> {
489
    let user = user().await;
490

            
491
    let id = user
492
        .create_script(vec![0x00], Some(" padded ".to_string()))
493
        .await?;
494
    let scripts = user.list_scripts().await?;
495
    assert_eq!(
496
        scripts
497
            .iter()
498
1
            .find(|s| s.id == id)
499
1
            .and_then(|s| s.name.as_deref()),
500
        Some("padded")
501
    );
502
    assert!(
503
        user.create_script(vec![0x00], Some(" \t".to_string()))
504
            .await
505
            .is_err()
506
    );
507
}
508

            
509
#[local_db_sqlx_test]
510
async fn test_update_script_source_stores_source_and_bytecode(
511
    pool: PgPool,
512
) -> Result<(), anyhow::Error> {
513
    let user = user().await;
514
    let id = user.create_script(vec![0x01], None).await?;
515
    assert_eq!(user.get_script(id).await?.source, None);
516

            
517
    user.update_script_source(id, "(+ 1 2)".to_string(), vec![0x02])
518
        .await?;
519
    let detail = user.get_script(id).await?;
520
    assert_eq!(detail.source.as_deref(), Some("(+ 1 2)"));
521
    assert_eq!(detail.bytecode, vec![0x02]);
522
1
    assert!(user.list_scripts().await?.iter().all(|s| s.has_source));
523
}
524

            
525
#[local_db_sqlx_test]
526
async fn test_update_script_source_refuses_a_missing_script(
527
    pool: PgPool,
528
) -> Result<(), anyhow::Error> {
529
    let user = user().await;
530
    let result = user
531
        .update_script_source(Uuid::new_v4(), "x".to_string(), vec![0x01])
532
        .await;
533
    assert!(result.is_err());
534
}
535

            
536
#[local_db_sqlx_test]
537
async fn test_script_updates_refuse_a_template(pool: PgPool) -> Result<(), anyhow::Error> {
538
    let user = user().await;
539
    let id = user.create_template("(a)".to_string(), None).await?;
540

            
541
    assert!(
542
        user.update_script_source(id, "(b)".to_string(), vec![0x01])
543
            .await
544
            .is_err()
545
    );
546
    assert_eq!(user.get_template(id).await?.source_text, "(a)");
547
}