1
//! Tag-domain natives. Wraps `server::command::tag::{DeleteTag, ListTags}`;
2
//! `list-tags` is render-safe, `delete-tag` is not.
3

            
4
use finance::tag::Tag;
5
use scripting::runtime::{
6
    alloc_entity_via_export, alloc_pair_chain, alloc_string_ref, read_string_arg,
7
};
8
use server::command::tag::{DeleteTag, ListTags};
9
use server::command::{CmdError, CmdResult, FinanceEntity};
10
use uuid::Uuid;
11
use wasmtime::{AnyRef, ArrayRef, Caller, Linker, Rooted, StructRef, Val};
12

            
13
use crate::host_failure::cmd_failure;
14
use crate::natives::args::uuid_arg;
15
use crate::natives::native::register_native;
16
use crate::session::SessionData;
17

            
18
pub const REGISTERED_COMMANDS: &[&str] = &["delete-tag", "list-tags"];
19

            
20
230199
pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
21
230199
    register_readonly(linker)?;
22
230199
    register_native(
23
230199
        linker,
24
230199
        "tag_delete_tag",
25
644
        |caller, (id_arg,): (Option<Rooted<ArrayRef>>,)| {
26
644
            Box::pin(async move {
27
644
                let user_id = caller.data().ctx().user_id;
28
644
                let id = read_string_arg(caller, id_arg)?;
29
644
                run_delete_tag(user_id, id).await
30
644
            })
31
644
        },
32
    )?;
33
230199
    Ok(())
34
230199
}
35

            
36
236810
pub fn register_readonly(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
37
236810
    register_native(linker, "tag_list_tags", |caller, ()| {
38
967
        Box::pin(async move {
39
967
            let user_id = caller.data().ctx().user_id;
40
967
            let result = ListTags::new().user_id(user_id).run().await;
41
967
            let tags = list_tag_entries("list-tags", result)?;
42
967
            alloc_tag_chain(caller, tags).await
43
967
        })
44
967
    })
45
236810
}
46

            
47
/// Removes the tag and every link to it, whatever uses it; an id the user does
48
/// not hold is `not-found`. Returns `t` on success.
49
644
pub(super) async fn run_delete_tag(user_id: Uuid, id_arg: Option<String>) -> wasmtime::Result<i32> {
50
644
    let tag_id = uuid_arg("delete-tag", "tag-id", id_arg)?;
51
643
    DeleteTag::new()
52
643
        .user_id(user_id)
53
643
        .tag_id(tag_id)
54
643
        .run()
55
643
        .await
56
        .map(|_| 1)
57
161
        .map_err(|err| cmd_failure("delete-tag", err))
58
644
}
59

            
60
967
fn list_tag_entries(
61
967
    name: &str,
62
967
    result: Result<Option<CmdResult>, CmdError>,
63
967
) -> wasmtime::Result<Vec<Tag>> {
64
967
    match result {
65
967
        Ok(Some(CmdResult::Entities(entities))) => Ok(entities
66
967
            .into_iter()
67
487
            .filter_map(|entity| match entity {
68
487
                FinanceEntity::Tag(tag) => Some(tag),
69
                _ => None,
70
487
            })
71
            .collect()),
72
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
73
            "{name}: expected Entities, got {other:?}"
74
        ))),
75
        Ok(None) => Ok(Vec::new()),
76
        Err(err) => Err(cmd_failure(name, err)),
77
    }
78
967
}
79

            
80
/// An unset description rides as a null string ref.
81
487
async fn alloc_tag_entity(
82
487
    caller: &mut Caller<'_, SessionData>,
83
487
    tag: &Tag,
84
487
) -> wasmtime::Result<Rooted<StructRef>> {
85
487
    let id_ref = alloc_string_ref(caller, tag.id.to_string().as_bytes())?;
86
487
    let name_ref = alloc_string_ref(caller, tag.tag_name.as_bytes())?;
87
487
    let value_ref = alloc_string_ref(caller, tag.tag_value.as_bytes())?;
88
487
    let description_ref = tag
89
487
        .description
90
487
        .as_deref()
91
161
        .map(|s| alloc_string_ref(caller, s.as_bytes()))
92
        .transpose()?;
93
    let args = [
94
487
        Val::AnyRef(Some(id_ref.to_anyref())),
95
487
        Val::AnyRef(Some(name_ref.to_anyref())),
96
487
        Val::AnyRef(Some(value_ref.to_anyref())),
97
487
        Val::AnyRef(description_ref.map(|r| r.to_anyref())),
98
    ];
99
487
    alloc_entity_via_export(caller, "alloc_tag_entity", &args).await
100
487
}
101

            
102
967
async fn alloc_tag_chain(
103
967
    caller: &mut Caller<'_, SessionData>,
104
967
    tags: Vec<Tag>,
105
967
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
106
967
    let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(tags.len());
107
967
    for tag in &tags {
108
487
        let entity_ref = alloc_tag_entity(caller, tag).await?;
109
487
        anyrefs.push(Some(entity_ref.to_anyref()));
110
    }
111
967
    alloc_pair_chain(caller, anyrefs).await
112
967
}