Lines
93.43 %
Functions
67.16 %
Branches
100 %
//! Split-domain natives. Wraps `server::command::ListSplits`.
//!
//! `list-splits` returns a typed `pair<split>` of `$split` entity refs;
//! each carries id, account-id, commodity-id, and value (Ratio). The
//! `value_denom` ride alongside via the Ratio field. Notes / reconcile
//! state stay reachable from the underlying `Tag` rows but are not
//! surfaced on the typed entity yet — extend the `$split` shape +
//! `nomi_entity!` declaration to expose more fields.
use scripting::runtime::{
alloc_entity_via_export, alloc_pair_chain, alloc_ratio_ref, alloc_string_ref, read_string_arg,
};
use server::command::split::{GetSplitTag, GetSplitTagValues, ListSplits, SetSplitTag};
use server::command::{CmdError, CmdResult};
use uuid::Uuid;
use wasmtime::{AnyRef, ArrayRef, Caller, Linker, Rooted, StructRef, Val};
use crate::host_failure::cmd_failure;
use crate::natives::args::{present, tag_name_arg, uuid_arg};
use crate::natives::native::register_native;
use crate::session::SessionData;
pub const REGISTERED_COMMANDS: &[&str] = &[
"list-splits",
"list-splits-by-transaction",
"set-split-tag",
"get-split-tag",
"get-split-tags",
];
pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
register_readonly(linker)?;
register_mutators(linker)?;
Ok(())
}
pub fn register_readonly(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
register_native(
linker,
"split_list_splits",
|caller, (id_arg,): (Option<Rooted<wasmtime::ArrayRef>>,)| {
Box::pin(async move {
let user_id = caller.data().ctx().user_id;
let id = read_string_arg(caller, id_arg)?;
let account_id = parse_account_id_arg(id)?;
let result = ListSplits::new()
.user_id(user_id)
.account(account_id)
.run()
.await;
let entries = list_split_entries("list-splits", result)?;
alloc_split_chain(caller, entries).await
})
},
)?;
"split_list_splits_by_transaction",
let transaction_id = parse_transaction_id_arg(id)?;
.transaction(transaction_id)
let entries = list_split_entries("list-splits-by-transaction", result)?;
"split_get_split_tag",
|caller, (id_arg, name_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
let name = read_string_arg(caller, name_arg)?;
let value = run_get_split_tag(user_id, id, name).await?;
Ok(Some(alloc_string_ref(caller, value.as_bytes())?))
"split_get_split_tags",
let values = run_get_split_tags(user_id, id, name).await?;
super::alloc_string_pair_chain(caller, values).await
pub fn register_mutators(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
"split_set_split_tag",
|caller, (id_arg, name_arg, value_arg): super::StringArgTriple| {
let value = read_string_arg(caller, value_arg)?;
run_set_split_tag(user_id, id, name, value).await
/// `set-split-tag` upsert: either a fresh `(split, tag_name, tag_value)`
/// link or replace the existing value for that name. Returns 1 on
/// success; the i32 return matches `set-account-tag`'s shape so a
/// future error-cell migration only has to update one wire format.
async fn run_set_split_tag(
user_id: Uuid,
id_arg: Option<String>,
name_arg: Option<String>,
value_arg: Option<String>,
) -> wasmtime::Result<i32> {
let split_id = uuid_arg("set-split-tag", "split-id", id_arg)?;
let tag_name = tag_name_arg("set-split-tag", name_arg)?;
let tag_value = present("set-split-tag", "tag-value", value_arg)?;
SetSplitTag::new()
.split_id(split_id)
.tag_name(tag_name)
.tag_value(tag_value)
.await
.map(|_| 1)
.map_err(|err| cmd_failure("set-split-tag", err))
/// `get-split-tag` lookup. Returns the empty string when the tag isn't
/// set on this split — keeps the wasm contract simple (`string` return,
/// no `Option` boxing). Scripts test absence with `(equal? v "")`.
async fn run_get_split_tag(
) -> wasmtime::Result<String> {
let split_id = uuid_arg("get-split-tag", "split-id", id_arg)?;
let tag_name = tag_name_arg("get-split-tag", name_arg)?;
match GetSplitTag::new()
{
Ok(Some(CmdResult::String(s))) => Ok(s),
Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
"get-split-tag: expected String, got {other:?}"
))),
Ok(None) => Ok(String::new()),
Err(err) => Err(cmd_failure("get-split-tag", err)),
/// `get-split-tags` lookup: every value of the name, ordered by value;
/// the empty list when the tag isn't set.
async fn run_get_split_tags(
) -> wasmtime::Result<Vec<String>> {
let split_id = uuid_arg("get-split-tags", "split-id", id_arg)?;
let tag_name = tag_name_arg("get-split-tags", name_arg)?;
match GetSplitTagValues::new()
Ok(Some(CmdResult::Lines(values))) => Ok(values),
"get-split-tags: expected Lines, got {other:?}"
Ok(None) => Ok(Vec::new()),
Err(err) => Err(cmd_failure("get-split-tags", err)),
/// Validates the :account-id arg into a UUID. Extracted so the validation
/// contract is reachable from unit tests without a wasmtime `Caller`.
fn parse_account_id_arg(id_arg: Option<String>) -> wasmtime::Result<Uuid> {
uuid_arg("list-splits", "account-id", id_arg)
/// Validates the :transaction-id arg into a UUID. Mirror of
/// [`parse_account_id_arg`] for the transaction-keyed splits query — the
/// server's `ListSplits` runs the by-transaction SQL when given a
/// `.transaction()` filter, but `list-splits` only ever wired the account
/// filter; this is the validation seam for the transaction variant.
fn parse_transaction_id_arg(id_arg: Option<String>) -> wasmtime::Result<Uuid> {
uuid_arg("list-splits-by-transaction", "transaction-id", id_arg)
/// (id, account_id, commodity_id, value_num, value_denom, reconcile_code)
/// per split, flattened from `TaggedSplits` for the wasm allocator loop.
/// `reconcile_code` is the `tribool` wire encoding of `Option<bool>`
/// (`entity_registry.org`): `0` = `None`/unknown, `1` = `Some(false)`, `2` =
/// `Some(true)`. Splits don't carry tags on the wire (yet), so the tuple
/// omits the tag map.
type SplitEntry = (String, String, String, i64, i64, i32);
/// Encodes `Option<bool>` as the `tribool` wire representation (ADR-0033
/// Phase 5): `None` and `Some(false)` are DISTINCT states, so this never
/// collapses "unknown" onto "false" the way a plain `unwrap_or(false)` would.
fn tribool_code(reconciled: Option<bool>) -> i32 {
match reconciled {
None => 0,
Some(false) => 1,
Some(true) => 2,
fn list_split_entries(
name: &str,
result: Result<Option<CmdResult>, CmdError>,
) -> wasmtime::Result<Vec<SplitEntry>> {
match result {
Ok(Some(CmdResult::TaggedSplits { entities })) => Ok(entities
.into_iter()
.map(|(s, _)| {
(
s.id.to_string(),
s.account_id.to_string(),
s.commodity_id.to_string(),
s.value_num,
s.value_denom,
tribool_code(s.reconcile_state),
)
.collect()),
"{name}: expected TaggedSplits, got {other:?}"
Err(err) => Err(cmd_failure(name, err)),
async fn alloc_split_entity(
caller: &mut Caller<'_, SessionData>,
id: &str,
account_id: &str,
commodity_id: &str,
value_num: i64,
value_denom: i64,
reconcile_code: i32,
) -> wasmtime::Result<Rooted<StructRef>> {
let id_ref = alloc_string_ref(caller, id.as_bytes())?;
let account_ref = alloc_string_ref(caller, account_id.as_bytes())?;
let commodity_ref = alloc_string_ref(caller, commodity_id.as_bytes())?;
let ratio_ref = alloc_ratio_ref(caller, value_num, value_denom)?;
let args = [
Val::AnyRef(Some(id_ref.to_anyref())),
Val::AnyRef(Some(account_ref.to_anyref())),
Val::AnyRef(Some(commodity_ref.to_anyref())),
Val::AnyRef(Some(ratio_ref.to_anyref())),
Val::I32(reconcile_code),
alloc_entity_via_export(caller, "alloc_split", &args).await
async fn alloc_split_chain(
entries: Vec<SplitEntry>,
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(entries.len());
for (id, account_id, commodity_id, num, denom, reconcile_code) in entries {
let entity_ref = alloc_split_entity(
caller,
&id,
&account_id,
&commodity_id,
num,
denom,
reconcile_code,
.await?;
anyrefs.push(Some(entity_ref.to_anyref()));
alloc_pair_chain(caller, anyrefs).await
#[cfg(test)]
mod tests {
use super::*;
use finance::split::Split;
fn split(value_num: i64, value_denom: i64, reconciled: Option<bool>) -> Split {
Split {
id: Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(),
tx_id: Uuid::nil(),
account_id: Uuid::parse_str("22222222-2222-2222-2222-222222222222").unwrap(),
commodity_id: Uuid::parse_str("33333333-3333-3333-3333-333333333333").unwrap(),
reconcile_state: reconciled,
reconcile_date: None,
value_num,
value_denom,
lot_id: None,
#[test]
fn list_split_entries_keeps_unknown_apart_from_unreconciled() {
let entities = vec![
(split(1, 1, None), Vec::new()),
(split(7, 3, Some(false)), Vec::new()),
(split(3, 1, Some(true)), Vec::new()),
let entries =
list_split_entries("test", Ok(Some(CmdResult::TaggedSplits { entities }))).unwrap();
let shown: Vec<_> = entries
.iter()
.map(|(_, _, _, num, denom, code)| (*num, *denom, *code))
.collect();
assert_eq!(shown, vec![(1, 1, 0), (7, 3, 1), (3, 1, 2)]);
assert_eq!(entries[0].1, "22222222-2222-2222-2222-222222222222");
fn list_split_entries_refuses_another_result() {
let err = list_split_entries("test", Ok(Some(CmdResult::String("x".into())))).unwrap_err();
assert!(err.to_string().contains("expected TaggedSplits"), "{err}");
fn parse_account_id_rejects_missing() {
let err = parse_account_id_arg(None).unwrap_err();
assert!(err.to_string().contains("missing or empty"), "got: {err}");
fn parse_account_id_rejects_invalid_uuid() {
let err = parse_account_id_arg(Some("nope".into())).unwrap_err();
assert!(err.to_string().contains("invalid uuid"), "got: {err}");
fn parse_transaction_id_rejects_missing() {
let err = parse_transaction_id_arg(None).unwrap_err();
assert!(
err.to_string()
.contains("list-splits-by-transaction: missing or empty"),
"got: {err}"
);
fn parse_transaction_id_rejects_invalid_uuid() {
let err = parse_transaction_id_arg(Some("nope".into())).unwrap_err();
.contains("list-splits-by-transaction: invalid uuid"),
fn parse_transaction_id_accepts_valid_uuid() {
let uuid = "11111111-1111-1111-1111-111111111111";
let parsed = parse_transaction_id_arg(Some(uuid.into())).unwrap();
assert_eq!(parsed, Uuid::parse_str(uuid).unwrap());