Skip to main content

rpc/natives/
tag.rs

1//! Tag-domain natives. Wraps `server::command::tag::{DeleteTag, ListTags}`;
2//! `list-tags` is render-safe, `delete-tag` is not.
3
4use finance::tag::Tag;
5use scripting::runtime::{
6    alloc_entity_via_export, alloc_pair_chain, alloc_string_ref, read_string_arg,
7};
8use server::command::tag::{DeleteTag, ListTags};
9use server::command::{CmdError, CmdResult, FinanceEntity};
10use uuid::Uuid;
11use wasmtime::{AnyRef, ArrayRef, Caller, Linker, Rooted, StructRef, Val};
12
13use crate::host_failure::cmd_failure;
14use crate::natives::args::uuid_arg;
15use crate::natives::native::register_native;
16use crate::session::SessionData;
17
18pub const REGISTERED_COMMANDS: &[&str] = &["delete-tag", "list-tags"];
19
20pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
21    register_readonly(linker)?;
22    register_native(
23        linker,
24        "tag_delete_tag",
25        |caller, (id_arg,): (Option<Rooted<ArrayRef>>,)| {
26            Box::pin(async move {
27                let user_id = caller.data().ctx().user_id;
28                let id = read_string_arg(caller, id_arg)?;
29                run_delete_tag(user_id, id).await
30            })
31        },
32    )?;
33    Ok(())
34}
35
36pub fn register_readonly(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
37    register_native(linker, "tag_list_tags", |caller, ()| {
38        Box::pin(async move {
39            let user_id = caller.data().ctx().user_id;
40            let result = ListTags::new().user_id(user_id).run().await;
41            let tags = list_tag_entries("list-tags", result)?;
42            alloc_tag_chain(caller, tags).await
43        })
44    })
45}
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.
49pub(super) async fn run_delete_tag(user_id: Uuid, id_arg: Option<String>) -> wasmtime::Result<i32> {
50    let tag_id = uuid_arg("delete-tag", "tag-id", id_arg)?;
51    DeleteTag::new()
52        .user_id(user_id)
53        .tag_id(tag_id)
54        .run()
55        .await
56        .map(|_| 1)
57        .map_err(|err| cmd_failure("delete-tag", err))
58}
59
60fn list_tag_entries(
61    name: &str,
62    result: Result<Option<CmdResult>, CmdError>,
63) -> wasmtime::Result<Vec<Tag>> {
64    match result {
65        Ok(Some(CmdResult::Entities(entities))) => Ok(entities
66            .into_iter()
67            .filter_map(|entity| match entity {
68                FinanceEntity::Tag(tag) => Some(tag),
69                _ => None,
70            })
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}
79
80/// An unset description rides as a null string ref.
81async fn alloc_tag_entity(
82    caller: &mut Caller<'_, SessionData>,
83    tag: &Tag,
84) -> wasmtime::Result<Rooted<StructRef>> {
85    let id_ref = alloc_string_ref(caller, tag.id.to_string().as_bytes())?;
86    let name_ref = alloc_string_ref(caller, tag.tag_name.as_bytes())?;
87    let value_ref = alloc_string_ref(caller, tag.tag_value.as_bytes())?;
88    let description_ref = tag
89        .description
90        .as_deref()
91        .map(|s| alloc_string_ref(caller, s.as_bytes()))
92        .transpose()?;
93    let args = [
94        Val::AnyRef(Some(id_ref.to_anyref())),
95        Val::AnyRef(Some(name_ref.to_anyref())),
96        Val::AnyRef(Some(value_ref.to_anyref())),
97        Val::AnyRef(description_ref.map(|r| r.to_anyref())),
98    ];
99    alloc_entity_via_export(caller, "alloc_tag_entity", &args).await
100}
101
102async fn alloc_tag_chain(
103    caller: &mut Caller<'_, SessionData>,
104    tags: Vec<Tag>,
105) -> wasmtime::Result<Option<Rooted<StructRef>>> {
106    let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(tags.len());
107    for tag in &tags {
108        let entity_ref = alloc_tag_entity(caller, tag).await?;
109        anyrefs.push(Some(entity_ref.to_anyref()));
110    }
111    alloc_pair_chain(caller, anyrefs).await
112}