1
//! Commodity-domain natives. Wraps `server::command::{GetCommodity,
2
//! CreateCommodity, ListCommodities}`.
3

            
4
use finance::tag::Tag;
5
use num_rational::Rational64;
6
use scripting::runtime::{
7
    alloc_commodity_ref, alloc_entity_via_export, alloc_pair_chain, alloc_string_ref,
8
    read_commodity_arg, read_string_arg,
9
};
10
use server::command::commodity::{
11
    ConvertCommodity, CreateCommodity, GetCommodity, ListCommodities,
12
};
13
use server::command::{CmdError, CmdResult, FinanceEntity};
14
use uuid::Uuid;
15
use wasmtime::{AnyRef, ArrayRef, Caller, Linker, Rooted, StructRef, Val};
16

            
17
use super::native::register_native;
18
use crate::host_failure::cmd_failure;
19
use crate::lookup_log::LookupKind;
20
use crate::natives::args::{args_error, required, uuid_arg};
21
use crate::session::SessionData;
22

            
23
mod tag;
24

            
25
pub 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

            
35
230200
pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
36
230200
    register_readonly(linker)?;
37
230200
    register_unlisted(linker)?;
38
230200
    register_mutators(linker)?;
39
230200
    Ok(())
40
230200
}
41

            
42
236811
pub fn register_readonly(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
43
236811
    register_native(linker, "commodity_list_commodities", |caller, ()| {
44
640
        Box::pin(async move {
45
640
            let user_id = caller.data().ctx().user_id;
46
640
            let result = ListCommodities::new().user_id(user_id).run().await;
47
640
            let entities = list_commodity_entities("list-commodities", result)?;
48
640
            alloc_commodity_chain(caller, entities).await
49
640
        })
50
640
    })?;
51
236811
    register_native(
52
236811
        linker,
53
236811
        "commodity_get_commodity",
54
13165
        |caller, (id_arg,): (Option<Rooted<ArrayRef>>,)| {
55
13165
            Box::pin(async move {
56
13165
                let user_id = caller.data().ctx().user_id;
57
13165
                let id = read_string_arg(caller, id_arg)?;
58
13165
                run_get_commodity(caller, user_id, id).await
59
13165
            })
60
13165
        },
61
    )?;
62
236811
    register_native(
63
236811
        linker,
64
236811
        "commodity_convert_commodity",
65
        |caller,
66
320
         (amount_arg, target_arg): (Option<Rooted<StructRef>>, Option<Rooted<ArrayRef>>)| {
67
320
            Box::pin(async move {
68
320
                let user_id = caller.data().ctx().user_id;
69
320
                let amount = read_commodity_arg(caller, amount_arg)?;
70
320
                let target = read_string_arg(caller, target_arg)?;
71
320
                let (numer, denom, target_id) = resolve_convert(user_id, amount, target).await?;
72
160
                let ref_ = alloc_commodity_ref(caller, numer, denom, target_id).await?;
73
160
                Ok(Some(ref_))
74
320
            })
75
320
        },
76
    )?;
77
236811
    Ok(())
78
236811
}
79

            
80
/// Reads that are not on the render allowlist; only the full linker binds them.
81
230200
pub fn register_unlisted(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
82
230200
    register_native(
83
230200
        linker,
84
230200
        "commodity_convert_amount",
85
641
        |caller, (amount_arg, from_arg, to_arg): super::StringArgTriple| {
86
641
            Box::pin(async move {
87
641
                let user_id = caller.data().ctx().user_id;
88
641
                let amount_str = read_string_arg(caller, amount_arg)?.unwrap_or_default();
89
641
                let from_id = uuid_arg(
90
641
                    "convert-amount",
91
641
                    "from-commodity",
92
641
                    read_string_arg(caller, from_arg)?,
93
                )?;
94
641
                let to_str = read_string_arg(caller, to_arg)?;
95
641
                let (num, denom) = parse_amount_str(&amount_str)?;
96
                let (result_num, result_denom, _) =
97
481
                    resolve_convert(user_id, Some((num, denom, from_id)), to_str).await?;
98
160
                let result = amount::wire_rational(Rational64::new_raw(result_num, result_denom));
99
160
                Ok(Some(alloc_string_ref(caller, result.as_bytes())?))
100
641
            })
101
641
        },
102
    )?;
103
230200
    Ok(())
104
230200
}
105

            
106
230200
pub fn register_mutators(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
107
230200
    register_native(
108
230200
        linker,
109
230200
        "commodity_set_commodity_tag",
110
168
        |caller, (id_arg, name_arg, value_arg): super::StringArgTriple| {
111
168
            Box::pin(async move {
112
168
                let user_id = caller.data().ctx().user_id;
113
168
                let id = read_string_arg(caller, id_arg)?;
114
168
                let name = read_string_arg(caller, name_arg)?;
115
168
                let value = read_string_arg(caller, value_arg)?;
116
168
                tag::run_set_commodity_tag(user_id, id, name, value).await
117
168
            })
118
168
        },
119
    )?;
120
230200
    register_native(
121
230200
        linker,
122
230200
        "commodity_clear_commodity_tag",
123
5
        |caller, (id_arg, name_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
124
5
            Box::pin(async move {
125
5
                let user_id = caller.data().ctx().user_id;
126
5
                let id = read_string_arg(caller, id_arg)?;
127
5
                let name = read_string_arg(caller, name_arg)?;
128
5
                tag::run_clear_commodity_tag(user_id, id, name).await
129
5
            })
130
5
        },
131
    )?;
132
230200
    register_native(
133
230200
        linker,
134
230200
        "commodity_create_commodity",
135
6080
        |caller, (symbol_arg, name_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
136
6080
            Box::pin(async move {
137
6080
                let user_id = caller.data().ctx().user_id;
138
6080
                let symbol = read_string_arg(caller, symbol_arg)?;
139
6080
                let name = read_string_arg(caller, name_arg)?;
140
6080
                let id = run_create_commodity(user_id, symbol, name).await?;
141
6080
                Ok(Some(alloc_string_ref(caller, id.as_bytes())?))
142
6080
            })
143
6080
        },
144
    )?;
145
230200
    Ok(())
146
230200
}
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.
154
801
async fn resolve_convert(
155
801
    user_id: Uuid,
156
801
    amount_arg: Option<(i64, i64, Uuid)>,
157
801
    target_arg: Option<String>,
158
801
) -> wasmtime::Result<(i64, i64, Uuid)> {
159
801
    let (amount_num, amount_denom, source_id) = amount_arg
160
        .ok_or_else(|| args_error("convert-commodity: missing commodity-typed amount argument"))?;
161
801
    let target_id = uuid_arg("convert-commodity", "target", target_arg)?;
162
801
    let result = ConvertCommodity::new()
163
801
        .user_id(user_id)
164
801
        .amount_num(amount_num)
165
801
        .amount_denom(amount_denom)
166
801
        .source_commodity_id(source_id)
167
801
        .target_commodity_id(target_id)
168
801
        .run()
169
801
        .await
170
481
        .map_err(|err| cmd_failure("convert-commodity", err))?;
171
320
    let rational = match result {
172
320
        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
320
    Ok((*rational.numer(), *rational.denom(), target_id))
185
801
}
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).
191
650
fn parse_amount_str(s: &str) -> wasmtime::Result<(i64, i64)> {
192
650
    if s.is_empty() {
193
1
        return Err(args_error(
194
1
            "convert-amount: invalid amount '': empty string",
195
1
        ));
196
649
    }
197
649
    match s.split_once('/') {
198
        None => {
199
164
            let n = s
200
164
                .parse::<i64>()
201
161
                .map_err(|_| args_error(format!("convert-amount: invalid amount '{s}'")))?;
202
3
            Ok((n, 1))
203
        }
204
        Some((n_str, d_str)) => {
205
485
            let n = n_str
206
485
                .parse::<i64>()
207
                .map_err(|_| args_error(format!("convert-amount: invalid amount '{s}'")))?;
208
485
            let d = d_str
209
485
                .parse::<i64>()
210
1
                .map_err(|_| args_error(format!("convert-amount: invalid amount '{s}'")))?;
211
484
            if d <= 0 {
212
2
                return Err(args_error("convert-amount: denominator must be positive"));
213
482
            }
214
482
            Ok((n, d))
215
        }
216
    }
217
650
}
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.
223
6082
async fn run_create_commodity(
224
6082
    user_id: Uuid,
225
6082
    symbol_arg: Option<String>,
226
6082
    name_arg: Option<String>,
227
6082
) -> wasmtime::Result<String> {
228
6082
    let symbol = required("create-commodity", "symbol", symbol_arg)?;
229
6081
    let name = required("create-commodity", "name", name_arg)?;
230
6080
    match CreateCommodity::new()
231
6080
        .symbol(symbol)
232
6080
        .name(name)
233
6080
        .user_id(user_id)
234
6080
        .run()
235
6080
        .await
236
    {
237
6080
        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
6082
}
247

            
248
13165
async fn run_get_commodity(
249
13165
    caller: &mut Caller<'_, SessionData>,
250
13165
    user_id: Uuid,
251
13165
    id_arg: Option<String>,
252
13165
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
253
13165
    let raw = required("get-commodity", "commodity-id", id_arg)?;
254
13165
    caller
255
13165
        .data()
256
13165
        .ctx()
257
13165
        .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
13165
    let entry = match Uuid::parse_str(&raw) {
266
        Ok(commodity_id) => {
267
163
            let result = GetCommodity::new()
268
163
                .user_id(user_id)
269
163
                .commodity_id(commodity_id)
270
163
                .run()
271
163
                .await;
272
163
            list_commodity_entities("get-commodity", result)?
273
                .into_iter()
274
                .next()
275
        }
276
13002
        Err(_) => resolve_commodity_symbol(user_id, &raw).await?,
277
    };
278

            
279
12681
    match entry {
280
        Some((id, symbol, name)) => Ok(Some(
281
12360
            alloc_commodity_entity(caller, &id, symbol.as_deref(), name.as_deref()).await?,
282
        )),
283
321
        None => Ok(None),
284
    }
285
13165
}
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).
293
13002
async fn resolve_commodity_symbol(
294
13002
    user_id: Uuid,
295
13002
    symbol: &str,
296
13002
) -> wasmtime::Result<Option<CommodityEntry>> {
297
13002
    let result = ListCommodities::new().user_id(user_id).run().await;
298
13002
    let mut matches = list_commodity_entities("get-commodity", result)?
299
        .into_iter()
300
16241
        .filter(|(_, sym, _)| {
301
16241
            sym.as_deref()
302
16241
                .is_some_and(|s| s.eq_ignore_ascii_case(symbol))
303
16241
        });
304
12841
    let first = matches.next();
305
12841
    if first.is_some() && matches.next().is_some() {
306
160
        return Err(args_error(format!(
307
160
            "get-commodity: symbol '{symbol}' is ambiguous (multiple commodities \
308
160
             share it); reference it by uuid instead"
309
160
        )));
310
12681
    }
311
12681
    Ok(first)
312
13002
}
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.
318
type 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`.
323
13805
fn list_commodity_entities(
324
13805
    name: &str,
325
13805
    result: Result<Option<CmdResult>, CmdError>,
326
13805
) -> wasmtime::Result<Vec<CommodityEntry>> {
327
13805
    match result {
328
13481
        Ok(Some(CmdResult::TaggedEntities { entities, .. })) => Ok(entities
329
13481
            .into_iter()
330
16721
            .filter_map(|(entity, tags)| match entity {
331
16721
                FinanceEntity::Commodity(c) => Some((
332
16721
                    c.id.to_string(),
333
16721
                    tag_value(&tags, "symbol").map(str::to_string),
334
16721
                    tag_value(&tags, "name").map(str::to_string),
335
16721
                )),
336
                _ => None,
337
16721
            })
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
324
        Err(err) => Err(cmd_failure(name, err)),
344
    }
345
13805
}
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)`.
350
12840
async fn alloc_commodity_entity(
351
12840
    caller: &mut Caller<'_, SessionData>,
352
12840
    id: &str,
353
12840
    symbol: Option<&str>,
354
12840
    name: Option<&str>,
355
12840
) -> wasmtime::Result<Rooted<StructRef>> {
356
12840
    let id_ref = alloc_string_ref(caller, id.as_bytes())?;
357
12840
    let symbol_ref = match symbol {
358
12840
        Some(s) => Some(alloc_string_ref(caller, s.as_bytes())?),
359
        None => None,
360
    };
361
12840
    let name_ref = match name {
362
12840
        Some(s) => Some(alloc_string_ref(caller, s.as_bytes())?),
363
        None => None,
364
    };
365
    let args = [
366
12840
        Val::AnyRef(Some(id_ref.to_anyref())),
367
12840
        Val::AnyRef(symbol_ref.map(|r| r.to_anyref())),
368
12840
        Val::AnyRef(name_ref.map(|r| r.to_anyref())),
369
    ];
370
12840
    alloc_entity_via_export(caller, "alloc_commodity_entity", &args).await
371
12840
}
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.
376
640
async fn alloc_commodity_chain(
377
640
    caller: &mut Caller<'_, SessionData>,
378
640
    entities: Vec<(String, Option<String>, Option<String>)>,
379
640
) -> wasmtime::Result<Option<Rooted<StructRef>>> {
380
640
    let mut anyrefs: Vec<Option<Rooted<AnyRef>>> = Vec::with_capacity(entities.len());
381
640
    for (id, symbol, name) in entities {
382
        let entity_ref =
383
480
            alloc_commodity_entity(caller, &id, symbol.as_deref(), name.as_deref()).await?;
384
480
        anyrefs.push(Some(entity_ref.to_anyref()));
385
    }
386
640
    alloc_pair_chain(caller, anyrefs).await
387
640
}
388

            
389
33446
fn tag_value<'a>(
390
33446
    tags: &'a std::collections::HashMap<String, FinanceEntity>,
391
33446
    key: &str,
392
33446
) -> Option<&'a str> {
393
33446
    tags.get(key).and_then(|t| match t {
394
33444
        FinanceEntity::Tag(Tag { tag_value, .. }) => Some(tag_value.as_str()),
395
        _ => None,
396
33444
    })
397
33446
}
398

            
399
#[cfg(test)]
400
mod tests;