Skip to main content

rpc/natives/commodity/
mod.rs

1//! Commodity-domain natives. Wraps `server::command::{GetCommodity,
2//! CreateCommodity, ListCommodities}`.
3
4use finance::tag::Tag;
5use num_rational::Rational64;
6use scripting::runtime::{
7    alloc_commodity_ref, alloc_entity_via_export, alloc_pair_chain, alloc_string_ref,
8    read_commodity_arg, read_string_arg,
9};
10use server::command::commodity::{
11    ConvertCommodity, CreateCommodity, GetCommodity, ListCommodities,
12};
13use server::command::{CmdError, CmdResult, FinanceEntity};
14use uuid::Uuid;
15use wasmtime::{AnyRef, ArrayRef, Caller, Linker, Rooted, StructRef, Val};
16
17use super::native::register_native;
18use crate::host_failure::cmd_failure;
19use crate::lookup_log::LookupKind;
20use crate::natives::args::{args_error, required, uuid_arg};
21use crate::session::SessionData;
22
23mod tag;
24
25pub const REGISTERED_COMMANDS: &[&str] = &[
26    "get-commodity",
27    "create-commodity",
28    "list-commodities",
29    "convert-commodity",
30    "convert-amount",
31    "set-commodity-tag",
32    "clear-commodity-tag",
33];
34
35pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
36    register_readonly(linker)?;
37    register_unlisted(linker)?;
38    register_mutators(linker)?;
39    Ok(())
40}
41
42pub fn register_readonly(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
43    register_native(linker, "commodity_list_commodities", |caller, ()| {
44        Box::pin(async move {
45            let user_id = caller.data().ctx().user_id;
46            let result = ListCommodities::new().user_id(user_id).run().await;
47            let entities = list_commodity_entities("list-commodities", result)?;
48            alloc_commodity_chain(caller, entities).await
49        })
50    })?;
51    register_native(
52        linker,
53        "commodity_get_commodity",
54        |caller, (id_arg,): (Option<Rooted<ArrayRef>>,)| {
55            Box::pin(async move {
56                let user_id = caller.data().ctx().user_id;
57                let id = read_string_arg(caller, id_arg)?;
58                run_get_commodity(caller, user_id, id).await
59            })
60        },
61    )?;
62    register_native(
63        linker,
64        "commodity_convert_commodity",
65        |caller,
66         (amount_arg, target_arg): (Option<Rooted<StructRef>>, Option<Rooted<ArrayRef>>)| {
67            Box::pin(async move {
68                let user_id = caller.data().ctx().user_id;
69                let amount = read_commodity_arg(caller, amount_arg)?;
70                let target = read_string_arg(caller, target_arg)?;
71                let (numer, denom, target_id) = resolve_convert(user_id, amount, target).await?;
72                let ref_ = alloc_commodity_ref(caller, numer, denom, target_id).await?;
73                Ok(Some(ref_))
74            })
75        },
76    )?;
77    Ok(())
78}
79
80/// Reads that are not on the render allowlist; only the full linker binds them.
81pub fn register_unlisted(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
82    register_native(
83        linker,
84        "commodity_convert_amount",
85        |caller, (amount_arg, from_arg, to_arg): super::StringArgTriple| {
86            Box::pin(async move {
87                let user_id = caller.data().ctx().user_id;
88                let amount_str = read_string_arg(caller, amount_arg)?.unwrap_or_default();
89                let from_id = uuid_arg(
90                    "convert-amount",
91                    "from-commodity",
92                    read_string_arg(caller, from_arg)?,
93                )?;
94                let to_str = read_string_arg(caller, to_arg)?;
95                let (num, denom) = parse_amount_str(&amount_str)?;
96                let (result_num, result_denom, _) =
97                    resolve_convert(user_id, Some((num, denom, from_id)), to_str).await?;
98                let result = amount::wire_rational(Rational64::new_raw(result_num, result_denom));
99                Ok(Some(alloc_string_ref(caller, result.as_bytes())?))
100            })
101        },
102    )?;
103    Ok(())
104}
105
106pub fn register_mutators(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
107    register_native(
108        linker,
109        "commodity_set_commodity_tag",
110        |caller, (id_arg, name_arg, value_arg): super::StringArgTriple| {
111            Box::pin(async move {
112                let user_id = caller.data().ctx().user_id;
113                let id = read_string_arg(caller, id_arg)?;
114                let name = read_string_arg(caller, name_arg)?;
115                let value = read_string_arg(caller, value_arg)?;
116                tag::run_set_commodity_tag(user_id, id, name, value).await
117            })
118        },
119    )?;
120    register_native(
121        linker,
122        "commodity_clear_commodity_tag",
123        |caller, (id_arg, name_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
124            Box::pin(async move {
125                let user_id = caller.data().ctx().user_id;
126                let id = read_string_arg(caller, id_arg)?;
127                let name = read_string_arg(caller, name_arg)?;
128                tag::run_clear_commodity_tag(user_id, id, name).await
129            })
130        },
131    )?;
132    register_native(
133        linker,
134        "commodity_create_commodity",
135        |caller, (symbol_arg, name_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
136            Box::pin(async move {
137                let user_id = caller.data().ctx().user_id;
138                let symbol = read_string_arg(caller, symbol_arg)?;
139                let name = read_string_arg(caller, name_arg)?;
140                let id = run_create_commodity(user_id, symbol, name).await?;
141                Ok(Some(alloc_string_ref(caller, id.as_bytes())?))
142            })
143        },
144    )?;
145    Ok(())
146}
147
148/// Companion to `get-commodity`. Looks up the most recent Price row
149/// between source and target commodities, multiplies the supplied
150/// amount, and returns the converted `(numer, denom, target_id)`.
151/// Caller wraps the tuple into a `$commodity` ref via
152/// `alloc_commodity_ref`. Surfaces `wasmtime::Error::msg` on
153/// missing/invalid args or absent conversion path.
154async fn resolve_convert(
155    user_id: Uuid,
156    amount_arg: Option<(i64, i64, Uuid)>,
157    target_arg: Option<String>,
158) -> wasmtime::Result<(i64, i64, Uuid)> {
159    let (amount_num, amount_denom, source_id) = amount_arg
160        .ok_or_else(|| args_error("convert-commodity: missing commodity-typed amount argument"))?;
161    let target_id = uuid_arg("convert-commodity", "target", target_arg)?;
162    let result = ConvertCommodity::new()
163        .user_id(user_id)
164        .amount_num(amount_num)
165        .amount_denom(amount_denom)
166        .source_commodity_id(source_id)
167        .target_commodity_id(target_id)
168        .run()
169        .await
170        .map_err(|err| cmd_failure("convert-commodity", err))?;
171    let rational = match result {
172        Some(CmdResult::Rational(r)) => r,
173        Some(other) => {
174            return Err(wasmtime::Error::msg(format!(
175                "convert-commodity: unexpected variant {other:?}"
176            )));
177        }
178        None => {
179            return Err(wasmtime::Error::msg(
180                "convert-commodity: command returned no rational",
181            ));
182        }
183    };
184    Ok((*rational.numer(), *rational.denom(), target_id))
185}
186
187/// Parses a ratio-token string `"num"` or `"num/denom"` into `(num, denom)`.
188/// Accepts an optional leading `-` on the numerator. Rejects empty strings,
189/// non-integer parts, and non-positive denominators (a non-positive `denom`
190/// would later overflow `Rational64` sign normalization).
191fn parse_amount_str(s: &str) -> wasmtime::Result<(i64, i64)> {
192    if s.is_empty() {
193        return Err(args_error(
194            "convert-amount: invalid amount '': empty string",
195        ));
196    }
197    match s.split_once('/') {
198        None => {
199            let n = s
200                .parse::<i64>()
201                .map_err(|_| args_error(format!("convert-amount: invalid amount '{s}'")))?;
202            Ok((n, 1))
203        }
204        Some((n_str, d_str)) => {
205            let n = n_str
206                .parse::<i64>()
207                .map_err(|_| args_error(format!("convert-amount: invalid amount '{s}'")))?;
208            let d = d_str
209                .parse::<i64>()
210                .map_err(|_| args_error(format!("convert-amount: invalid amount '{s}'")))?;
211            if d <= 0 {
212                return Err(args_error("convert-amount: denominator must be positive"));
213            }
214            Ok((n, d))
215        }
216    }
217}
218
219/// Writes a new commodity row for the session user with `symbol` and
220/// `name` tags. Returns the new entity's UUID in `(:commodity-id "...")`.
221/// Args ride the capture queue: compiler pushes symbol first, then name;
222/// host pops via FIFO take_arg in matching order.
223async fn run_create_commodity(
224    user_id: Uuid,
225    symbol_arg: Option<String>,
226    name_arg: Option<String>,
227) -> wasmtime::Result<String> {
228    let symbol = required("create-commodity", "symbol", symbol_arg)?;
229    let name = required("create-commodity", "name", name_arg)?;
230    match CreateCommodity::new()
231        .symbol(symbol)
232        .name(name)
233        .user_id(user_id)
234        .run()
235        .await
236    {
237        Ok(Some(CmdResult::String(id))) => Ok(id),
238        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
239            "create-commodity: expected String id, got {other:?}"
240        ))),
241        Ok(None) => Err(wasmtime::Error::msg(
242            "create-commodity: command returned no id",
243        )),
244        Err(err) => Err(cmd_failure("create-commodity", err)),
245    }
246}
247
248async fn run_get_commodity(
249    caller: &mut Caller<'_, SessionData>,
250    user_id: Uuid,
251    id_arg: Option<String>,
252) -> wasmtime::Result<Option<Rooted<StructRef>>> {
253    let raw = required("get-commodity", "commodity-id", id_arg)?;
254    caller
255        .data()
256        .ctx()
257        .record_lookup(LookupKind::Commodity, &raw);
258
259    // Accept a uuid OR a symbol, mirroring get-account's id/name fallback: a
260    // uuid arg is an id lookup (unchanged); a non-uuid arg is matched
261    // case-insensitively against commodity symbols, so `(get-commodity "USD")`
262    // works in templates without pasting a uuid. Like get-account, a
263    // uuid-SHAPED symbol is only reachable by its real id, not by the symbol
264    // string — an accepted, consistent limitation for a pathological name.
265    let entry = match Uuid::parse_str(&raw) {
266        Ok(commodity_id) => {
267            let result = GetCommodity::new()
268                .user_id(user_id)
269                .commodity_id(commodity_id)
270                .run()
271                .await;
272            list_commodity_entities("get-commodity", result)?
273                .into_iter()
274                .next()
275        }
276        Err(_) => resolve_commodity_symbol(user_id, &raw).await?,
277    };
278
279    match entry {
280        Some((id, symbol, name)) => Ok(Some(
281            alloc_commodity_entity(caller, &id, symbol.as_deref(), name.as_deref()).await?,
282        )),
283        None => Ok(None),
284    }
285}
286
287/// Resolves a commodity by its symbol (case-insensitive) for `get-commodity`.
288/// `None` when no symbol matches; an ERROR when more than one does — symbols
289/// aren't unique in the schema, and silently binding to an arbitrary one would
290/// draft a transaction against the wrong commodity. Failing loudly is the safe
291/// choice for a finance value (and is stricter than `get-account`, which is
292/// acceptable: a wrong currency is worse than a wrong account label).
293async fn resolve_commodity_symbol(
294    user_id: Uuid,
295    symbol: &str,
296) -> wasmtime::Result<Option<CommodityEntry>> {
297    let result = ListCommodities::new().user_id(user_id).run().await;
298    let mut matches = list_commodity_entities("get-commodity", result)?
299        .into_iter()
300        .filter(|(_, sym, _)| {
301            sym.as_deref()
302                .is_some_and(|s| s.eq_ignore_ascii_case(symbol))
303        });
304    let first = matches.next();
305    if first.is_some() && matches.next().is_some() {
306        return Err(args_error(format!(
307            "get-commodity: symbol '{symbol}' is ambiguous (multiple commodities \
308             share it); reference it by uuid instead"
309        )));
310    }
311    Ok(first)
312}
313
314/// Unwraps a `CmdResult::TaggedEntities` and extracts the (id, symbol-tag,
315/// (id, symbol-tag, name-tag) triple per commodity, flattened from
316/// `TaggedEntities` so the wasm marshalling site walks one typed row
317/// per commodity.
318type CommodityEntry = (String, Option<String>, Option<String>);
319
320/// name-tag) triple per commodity. Returns the typed shape the host fn
321/// then folds through the entity allocator + pair chain. Wrong variant or
322/// command error surfaces as `wasmtime::Error`.
323fn list_commodity_entities(
324    name: &str,
325    result: Result<Option<CmdResult>, CmdError>,
326) -> wasmtime::Result<Vec<CommodityEntry>> {
327    match result {
328        Ok(Some(CmdResult::TaggedEntities { entities, .. })) => Ok(entities
329            .into_iter()
330            .filter_map(|(entity, tags)| match entity {
331                FinanceEntity::Commodity(c) => Some((
332                    c.id.to_string(),
333                    tag_value(&tags, "symbol").map(str::to_string),
334                    tag_value(&tags, "name").map(str::to_string),
335                )),
336                _ => None,
337            })
338            .collect()),
339        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
340            "{name}: expected TaggedEntities, got {other:?}"
341        ))),
342        Ok(None) => Ok(Vec::new()),
343        Err(err) => Err(cmd_failure(name, err)),
344    }
345}
346
347/// Re-enters wasm to construct a `$commodity_entity` struct ref carrying the
348/// id, symbol-tag, and name-tag as `$i8_array` payloads. Missing tags ride
349/// as null `(ref null $i8_array)`.
350async fn alloc_commodity_entity(
351    caller: &mut Caller<'_, SessionData>,
352    id: &str,
353    symbol: Option<&str>,
354    name: Option<&str>,
355) -> wasmtime::Result<Rooted<StructRef>> {
356    let id_ref = alloc_string_ref(caller, id.as_bytes())?;
357    let symbol_ref = match symbol {
358        Some(s) => Some(alloc_string_ref(caller, s.as_bytes())?),
359        None => None,
360    };
361    let name_ref = match name {
362        Some(s) => Some(alloc_string_ref(caller, s.as_bytes())?),
363        None => None,
364    };
365    let args = [
366        Val::AnyRef(Some(id_ref.to_anyref())),
367        Val::AnyRef(symbol_ref.map(|r| r.to_anyref())),
368        Val::AnyRef(name_ref.map(|r| r.to_anyref())),
369    ];
370    alloc_entity_via_export(caller, "alloc_commodity_entity", &args).await
371}
372
373/// Allocates a pair chain of `$commodity_entity` refs from the typed
374/// triples extracted by `list_commodity_entities`. Returns the chain head,
375/// or `None` for an empty result set.
376async fn alloc_commodity_chain(
377    caller: &mut Caller<'_, SessionData>,
378    entities: Vec<(String, Option<String>, Option<String>)>,
379) -> wasmtime::Result<Option<Rooted<StructRef>>> {
380    let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(entities.len());
381    for (id, symbol, name) in entities {
382        let entity_ref =
383            alloc_commodity_entity(caller, &id, symbol.as_deref(), name.as_deref()).await?;
384        anyrefs.push(Some(entity_ref.to_anyref()));
385    }
386    alloc_pair_chain(caller, anyrefs).await
387}
388
389fn tag_value<'a>(
390    tags: &'a std::collections::HashMap<String, FinanceEntity>,
391    key: &str,
392) -> Option<&'a str> {
393    tags.get(key).and_then(|t| match t {
394        FinanceEntity::Tag(Tag { tag_value, .. }) => Some(tag_value.as_str()),
395        _ => None,
396    })
397}
398
399#[cfg(test)]
400mod tests;