Skip to main content

rpc/natives/
split.rs

1//! Split-domain natives. Wraps `server::command::ListSplits`.
2//!
3//! `list-splits` returns a typed `pair<split>` of `$split` entity refs;
4//! each carries id, account-id, commodity-id, and value (Ratio). The
5//! `value_denom` ride alongside via the Ratio field. Notes / reconcile
6//! state stay reachable from the underlying `Tag` rows but are not
7//! surfaced on the typed entity yet — extend the `$split` shape +
8//! `nomi_entity!` declaration to expose more fields.
9
10use scripting::runtime::{
11    alloc_entity_via_export, alloc_pair_chain, alloc_ratio_ref, alloc_string_ref, read_string_arg,
12};
13use server::command::split::{GetSplitTag, GetSplitTagValues, ListSplits, SetSplitTag};
14use server::command::{CmdError, CmdResult};
15use uuid::Uuid;
16use wasmtime::{AnyRef, ArrayRef, Caller, Linker, Rooted, StructRef, Val};
17
18use crate::host_failure::cmd_failure;
19use crate::natives::args::{present, tag_name_arg, uuid_arg};
20use crate::natives::native::register_native;
21use crate::session::SessionData;
22
23pub const REGISTERED_COMMANDS: &[&str] = &[
24    "list-splits",
25    "list-splits-by-transaction",
26    "set-split-tag",
27    "get-split-tag",
28    "get-split-tags",
29];
30
31pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
32    register_readonly(linker)?;
33    register_mutators(linker)?;
34    Ok(())
35}
36
37pub fn register_readonly(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
38    register_native(
39        linker,
40        "split_list_splits",
41        |caller, (id_arg,): (Option<Rooted<wasmtime::ArrayRef>>,)| {
42            Box::pin(async move {
43                let user_id = caller.data().ctx().user_id;
44                let id = read_string_arg(caller, id_arg)?;
45                let account_id = parse_account_id_arg(id)?;
46                let result = ListSplits::new()
47                    .user_id(user_id)
48                    .account(account_id)
49                    .run()
50                    .await;
51                let entries = list_split_entries("list-splits", result)?;
52                alloc_split_chain(caller, entries).await
53            })
54        },
55    )?;
56    register_native(
57        linker,
58        "split_list_splits_by_transaction",
59        |caller, (id_arg,): (Option<Rooted<wasmtime::ArrayRef>>,)| {
60            Box::pin(async move {
61                let user_id = caller.data().ctx().user_id;
62                let id = read_string_arg(caller, id_arg)?;
63                let transaction_id = parse_transaction_id_arg(id)?;
64                let result = ListSplits::new()
65                    .user_id(user_id)
66                    .transaction(transaction_id)
67                    .run()
68                    .await;
69                let entries = list_split_entries("list-splits-by-transaction", result)?;
70                alloc_split_chain(caller, entries).await
71            })
72        },
73    )?;
74    register_native(
75        linker,
76        "split_get_split_tag",
77        |caller, (id_arg, name_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
78            Box::pin(async move {
79                let user_id = caller.data().ctx().user_id;
80                let id = read_string_arg(caller, id_arg)?;
81                let name = read_string_arg(caller, name_arg)?;
82                let value = run_get_split_tag(user_id, id, name).await?;
83                Ok(Some(alloc_string_ref(caller, value.as_bytes())?))
84            })
85        },
86    )?;
87    register_native(
88        linker,
89        "split_get_split_tags",
90        |caller, (id_arg, name_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
91            Box::pin(async move {
92                let user_id = caller.data().ctx().user_id;
93                let id = read_string_arg(caller, id_arg)?;
94                let name = read_string_arg(caller, name_arg)?;
95                let values = run_get_split_tags(user_id, id, name).await?;
96                super::alloc_string_pair_chain(caller, values).await
97            })
98        },
99    )?;
100    Ok(())
101}
102
103pub fn register_mutators(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
104    register_native(
105        linker,
106        "split_set_split_tag",
107        |caller, (id_arg, name_arg, value_arg): super::StringArgTriple| {
108            Box::pin(async move {
109                let user_id = caller.data().ctx().user_id;
110                let id = read_string_arg(caller, id_arg)?;
111                let name = read_string_arg(caller, name_arg)?;
112                let value = read_string_arg(caller, value_arg)?;
113                run_set_split_tag(user_id, id, name, value).await
114            })
115        },
116    )?;
117    Ok(())
118}
119
120/// `set-split-tag` upsert: either a fresh `(split, tag_name, tag_value)`
121/// link or replace the existing value for that name. Returns 1 on
122/// success; the i32 return matches `set-account-tag`'s shape so a
123/// future error-cell migration only has to update one wire format.
124async fn run_set_split_tag(
125    user_id: Uuid,
126    id_arg: Option<String>,
127    name_arg: Option<String>,
128    value_arg: Option<String>,
129) -> wasmtime::Result<i32> {
130    let split_id = uuid_arg("set-split-tag", "split-id", id_arg)?;
131    let tag_name = tag_name_arg("set-split-tag", name_arg)?;
132    let tag_value = present("set-split-tag", "tag-value", value_arg)?;
133    SetSplitTag::new()
134        .user_id(user_id)
135        .split_id(split_id)
136        .tag_name(tag_name)
137        .tag_value(tag_value)
138        .run()
139        .await
140        .map(|_| 1)
141        .map_err(|err| cmd_failure("set-split-tag", err))
142}
143
144/// `get-split-tag` lookup. Returns the empty string when the tag isn't
145/// set on this split — keeps the wasm contract simple (`string` return,
146/// no `Option` boxing). Scripts test absence with `(equal? v "")`.
147async fn run_get_split_tag(
148    user_id: Uuid,
149    id_arg: Option<String>,
150    name_arg: Option<String>,
151) -> wasmtime::Result<String> {
152    let split_id = uuid_arg("get-split-tag", "split-id", id_arg)?;
153    let tag_name = tag_name_arg("get-split-tag", name_arg)?;
154    match GetSplitTag::new()
155        .user_id(user_id)
156        .split_id(split_id)
157        .tag_name(tag_name)
158        .run()
159        .await
160    {
161        Ok(Some(CmdResult::String(s))) => Ok(s),
162        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
163            "get-split-tag: expected String, got {other:?}"
164        ))),
165        Ok(None) => Ok(String::new()),
166        Err(err) => Err(cmd_failure("get-split-tag", err)),
167    }
168}
169
170/// `get-split-tags` lookup: every value of the name, ordered by value;
171/// the empty list when the tag isn't set.
172async fn run_get_split_tags(
173    user_id: Uuid,
174    id_arg: Option<String>,
175    name_arg: Option<String>,
176) -> wasmtime::Result<Vec<String>> {
177    let split_id = uuid_arg("get-split-tags", "split-id", id_arg)?;
178    let tag_name = tag_name_arg("get-split-tags", name_arg)?;
179    match GetSplitTagValues::new()
180        .user_id(user_id)
181        .split_id(split_id)
182        .tag_name(tag_name)
183        .run()
184        .await
185    {
186        Ok(Some(CmdResult::Lines(values))) => Ok(values),
187        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
188            "get-split-tags: expected Lines, got {other:?}"
189        ))),
190        Ok(None) => Ok(Vec::new()),
191        Err(err) => Err(cmd_failure("get-split-tags", err)),
192    }
193}
194
195/// Validates the :account-id arg into a UUID. Extracted so the validation
196/// contract is reachable from unit tests without a wasmtime `Caller`.
197fn parse_account_id_arg(id_arg: Option<String>) -> wasmtime::Result<Uuid> {
198    uuid_arg("list-splits", "account-id", id_arg)
199}
200
201/// Validates the :transaction-id arg into a UUID. Mirror of
202/// [`parse_account_id_arg`] for the transaction-keyed splits query — the
203/// server's `ListSplits` runs the by-transaction SQL when given a
204/// `.transaction()` filter, but `list-splits` only ever wired the account
205/// filter; this is the validation seam for the transaction variant.
206fn parse_transaction_id_arg(id_arg: Option<String>) -> wasmtime::Result<Uuid> {
207    uuid_arg("list-splits-by-transaction", "transaction-id", id_arg)
208}
209
210/// (id, account_id, commodity_id, value_num, value_denom, reconcile_code)
211/// per split, flattened from `TaggedSplits` for the wasm allocator loop.
212/// `reconcile_code` is the `tribool` wire encoding of `Option<bool>`
213/// (`entity_registry.org`): `0` = `None`/unknown, `1` = `Some(false)`, `2` =
214/// `Some(true)`. Splits don't carry tags on the wire (yet), so the tuple
215/// omits the tag map.
216type SplitEntry = (String, String, String, i64, i64, i32);
217
218/// Encodes `Option<bool>` as the `tribool` wire representation (ADR-0033
219/// Phase 5): `None` and `Some(false)` are DISTINCT states, so this never
220/// collapses "unknown" onto "false" the way a plain `unwrap_or(false)` would.
221fn tribool_code(reconciled: Option<bool>) -> i32 {
222    match reconciled {
223        None => 0,
224        Some(false) => 1,
225        Some(true) => 2,
226    }
227}
228
229fn list_split_entries(
230    name: &str,
231    result: Result<Option<CmdResult>, CmdError>,
232) -> wasmtime::Result<Vec<SplitEntry>> {
233    match result {
234        Ok(Some(CmdResult::TaggedSplits { entities })) => Ok(entities
235            .into_iter()
236            .map(|(s, _)| {
237                (
238                    s.id.to_string(),
239                    s.account_id.to_string(),
240                    s.commodity_id.to_string(),
241                    s.value_num,
242                    s.value_denom,
243                    tribool_code(s.reconcile_state),
244                )
245            })
246            .collect()),
247        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
248            "{name}: expected TaggedSplits, got {other:?}"
249        ))),
250        Ok(None) => Ok(Vec::new()),
251        Err(err) => Err(cmd_failure(name, err)),
252    }
253}
254
255async fn alloc_split_entity(
256    caller: &mut Caller<'_, SessionData>,
257    id: &str,
258    account_id: &str,
259    commodity_id: &str,
260    value_num: i64,
261    value_denom: i64,
262    reconcile_code: i32,
263) -> wasmtime::Result<Rooted<StructRef>> {
264    let id_ref = alloc_string_ref(caller, id.as_bytes())?;
265    let account_ref = alloc_string_ref(caller, account_id.as_bytes())?;
266    let commodity_ref = alloc_string_ref(caller, commodity_id.as_bytes())?;
267    let ratio_ref = alloc_ratio_ref(caller, value_num, value_denom)?;
268    let args = [
269        Val::AnyRef(Some(id_ref.to_anyref())),
270        Val::AnyRef(Some(account_ref.to_anyref())),
271        Val::AnyRef(Some(commodity_ref.to_anyref())),
272        Val::AnyRef(Some(ratio_ref.to_anyref())),
273        Val::I32(reconcile_code),
274    ];
275    alloc_entity_via_export(caller, "alloc_split", &args).await
276}
277
278async fn alloc_split_chain(
279    caller: &mut Caller<'_, SessionData>,
280    entries: Vec<SplitEntry>,
281) -> wasmtime::Result<Option<Rooted<StructRef>>> {
282    let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(entries.len());
283    for (id, account_id, commodity_id, num, denom, reconcile_code) in entries {
284        let entity_ref = alloc_split_entity(
285            caller,
286            &id,
287            &account_id,
288            &commodity_id,
289            num,
290            denom,
291            reconcile_code,
292        )
293        .await?;
294        anyrefs.push(Some(entity_ref.to_anyref()));
295    }
296    alloc_pair_chain(caller, anyrefs).await
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302    use finance::split::Split;
303    fn split(value_num: i64, value_denom: i64, reconciled: Option<bool>) -> Split {
304        Split {
305            id: Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(),
306            tx_id: Uuid::nil(),
307            account_id: Uuid::parse_str("22222222-2222-2222-2222-222222222222").unwrap(),
308            commodity_id: Uuid::parse_str("33333333-3333-3333-3333-333333333333").unwrap(),
309            reconcile_state: reconciled,
310            reconcile_date: None,
311            value_num,
312            value_denom,
313            lot_id: None,
314        }
315    }
316
317    #[test]
318    fn list_split_entries_keeps_unknown_apart_from_unreconciled() {
319        let entities = vec![
320            (split(1, 1, None), Vec::new()),
321            (split(7, 3, Some(false)), Vec::new()),
322            (split(3, 1, Some(true)), Vec::new()),
323        ];
324        let entries =
325            list_split_entries("test", Ok(Some(CmdResult::TaggedSplits { entities }))).unwrap();
326        let shown: Vec<_> = entries
327            .iter()
328            .map(|(_, _, _, num, denom, code)| (*num, *denom, *code))
329            .collect();
330        assert_eq!(shown, vec![(1, 1, 0), (7, 3, 1), (3, 1, 2)]);
331        assert_eq!(entries[0].1, "22222222-2222-2222-2222-222222222222");
332    }
333
334    #[test]
335    fn list_split_entries_refuses_another_result() {
336        let err = list_split_entries("test", Ok(Some(CmdResult::String("x".into())))).unwrap_err();
337        assert!(err.to_string().contains("expected TaggedSplits"), "{err}");
338    }
339
340    #[test]
341    fn parse_account_id_rejects_missing() {
342        let err = parse_account_id_arg(None).unwrap_err();
343        assert!(err.to_string().contains("missing or empty"), "got: {err}");
344    }
345
346    #[test]
347    fn parse_account_id_rejects_invalid_uuid() {
348        let err = parse_account_id_arg(Some("nope".into())).unwrap_err();
349        assert!(err.to_string().contains("invalid uuid"), "got: {err}");
350    }
351
352    #[test]
353    fn parse_transaction_id_rejects_missing() {
354        let err = parse_transaction_id_arg(None).unwrap_err();
355        assert!(
356            err.to_string()
357                .contains("list-splits-by-transaction: missing or empty"),
358            "got: {err}"
359        );
360    }
361
362    #[test]
363    fn parse_transaction_id_rejects_invalid_uuid() {
364        let err = parse_transaction_id_arg(Some("nope".into())).unwrap_err();
365        assert!(
366            err.to_string()
367                .contains("list-splits-by-transaction: invalid uuid"),
368            "got: {err}"
369        );
370    }
371
372    #[test]
373    fn parse_transaction_id_accepts_valid_uuid() {
374        let uuid = "11111111-1111-1111-1111-111111111111";
375        let parsed = parse_transaction_id_arg(Some(uuid.into())).unwrap();
376        assert_eq!(parsed, Uuid::parse_str(uuid).unwrap());
377    }
378}