shopify_function_wasm_api 0.3.1

High-level interface for interfacing with the Shopify Function Wasm API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! # Shopify Function Wasm API
//!
//! This crate provides a high-level API for interfacing with the Shopify Function Wasm API.
//!
//! ## Usage
//!
//! ```rust,no_run
//! use shopify_function_wasm_api::{Context, Serialize, Deserialize, Value};
//! use std::error::Error;
//!
//! fn main() {
//!     run().unwrap();
//! }
//!
//! fn run() -> Result<(), Box<dyn Error>> {
//!     shopify_function_wasm_api::init_panic_handler();
//!     let mut context = Context::new();
//!     let input = context.input_get()?;
//!     let value: i32 = Deserialize::deserialize(&input)?;
//!     value.serialize(&mut context)?;
//!     Ok(())
//! }
//! ```

#![warn(missing_docs)]

use shopify_function_wasm_api_core::read::{ErrorCode, NanBox, Val, ValueRef};
use std::{cell::RefCell, collections::HashMap};

pub mod log;
pub mod read;
pub mod write;

pub use read::Deserialize;
pub use write::Serialize;

#[cfg(target_family = "wasm")]
#[link(wasm_import_module = "shopify_function_v2")]
extern "C" {
    // Read API.
    fn shopify_function_input_get() -> Val;
    fn shopify_function_input_get_val_len(scope: Val) -> usize;
    fn shopify_function_input_read_utf8_str(src: usize, out: *mut u8, len: usize);
    fn shopify_function_input_get_obj_prop(scope: Val, ptr: *const u8, len: usize) -> Val;
    fn shopify_function_input_get_interned_obj_prop(
        scope: Val,
        interned_string_id: shopify_function_wasm_api_core::InternedStringId,
    ) -> Val;
    fn shopify_function_input_get_at_index(scope: Val, index: usize) -> Val;
    fn shopify_function_input_get_obj_key_at_index(scope: Val, index: usize) -> Val;

    // Write API.
    fn shopify_function_output_new_bool(bool: u32) -> usize;
    fn shopify_function_output_new_null() -> usize;
    fn shopify_function_output_new_i32(int: i32) -> usize;
    fn shopify_function_output_new_f64(float: f64) -> usize;
    fn shopify_function_output_new_utf8_str(ptr: *const u8, len: usize) -> usize;
    fn shopify_function_output_new_interned_utf8_str(
        id: shopify_function_wasm_api_core::InternedStringId,
    ) -> usize;
    fn shopify_function_output_new_object(len: usize) -> usize;
    fn shopify_function_output_finish_object() -> usize;
    fn shopify_function_output_new_array(len: usize) -> usize;
    fn shopify_function_output_finish_array() -> usize;

    // Log API.
    fn shopify_function_log_new_utf8_str(ptr: *const u8, len: usize);

    // Other.
    fn shopify_function_intern_utf8_str(ptr: *const u8, len: usize) -> usize;
}

#[cfg(not(target_family = "wasm"))]
mod provider_fallback {
    use super::Val;
    use shopify_function_wasm_api_core::write::WriteResult;

    // Read API.
    pub(crate) unsafe fn shopify_function_input_get() -> Val {
        shopify_function_provider::read::shopify_function_input_get()
    }
    pub(crate) unsafe fn shopify_function_input_get_val_len(scope: Val) -> usize {
        shopify_function_provider::read::shopify_function_input_get_val_len(scope)
    }
    pub(crate) unsafe fn shopify_function_input_read_utf8_str(
        src: usize,
        out: *mut u8,
        len: usize,
    ) {
        let src = shopify_function_provider::read::shopify_function_input_get_utf8_str_addr(src);
        std::ptr::copy(src as _, out, len);
    }
    pub(crate) unsafe fn shopify_function_input_get_obj_prop(
        scope: Val,
        ptr: *const u8,
        len: usize,
    ) -> Val {
        shopify_function_provider::read::shopify_function_input_get_obj_prop(scope, ptr as _, len)
    }
    pub(crate) unsafe fn shopify_function_input_get_interned_obj_prop(
        scope: Val,
        interned_string_id: shopify_function_wasm_api_core::InternedStringId,
    ) -> Val {
        shopify_function_provider::read::shopify_function_input_get_interned_obj_prop(
            scope,
            interned_string_id,
        )
    }
    pub(crate) unsafe fn shopify_function_input_get_at_index(scope: Val, index: usize) -> Val {
        shopify_function_provider::read::shopify_function_input_get_at_index(scope, index)
    }
    pub(crate) unsafe fn shopify_function_input_get_obj_key_at_index(
        scope: Val,
        index: usize,
    ) -> Val {
        shopify_function_provider::read::shopify_function_input_get_obj_key_at_index(scope, index)
    }

    // Write API.
    pub(crate) unsafe fn shopify_function_output_new_bool(bool: u32) -> usize {
        shopify_function_provider::write::shopify_function_output_new_bool(bool) as usize
    }
    pub(crate) unsafe fn shopify_function_output_new_null() -> usize {
        shopify_function_provider::write::shopify_function_output_new_null() as usize
    }
    pub(crate) unsafe fn shopify_function_output_new_i32(int: i32) -> usize {
        shopify_function_provider::write::shopify_function_output_new_i32(int) as usize
    }
    pub(crate) unsafe fn shopify_function_output_new_f64(float: f64) -> usize {
        shopify_function_provider::write::shopify_function_output_new_f64(float) as usize
    }
    pub(crate) unsafe fn shopify_function_output_new_utf8_str(ptr: *const u8, len: usize) -> usize {
        let result = shopify_function_provider::write::shopify_function_output_new_utf8_str(len);
        let write_result = (result >> usize::BITS) as usize;
        let dst = result as usize;
        if write_result == WriteResult::Ok as usize {
            std::ptr::copy(ptr as _, dst as _, len);
        }
        write_result
    }
    pub(crate) unsafe fn shopify_function_output_new_interned_utf8_str(
        id: shopify_function_wasm_api_core::InternedStringId,
    ) -> usize {
        shopify_function_provider::write::shopify_function_output_new_interned_utf8_str(id) as usize
    }
    pub(crate) unsafe fn shopify_function_output_new_object(len: usize) -> usize {
        shopify_function_provider::write::shopify_function_output_new_object(len) as usize
    }
    pub(crate) unsafe fn shopify_function_output_finish_object() -> usize {
        shopify_function_provider::write::shopify_function_output_finish_object() as usize
    }
    pub(crate) unsafe fn shopify_function_output_new_array(len: usize) -> usize {
        shopify_function_provider::write::shopify_function_output_new_array(len) as usize
    }
    pub(crate) unsafe fn shopify_function_output_finish_array() -> usize {
        shopify_function_provider::write::shopify_function_output_finish_array() as usize
    }

    // Logging.
    pub(crate) unsafe fn shopify_function_log_new_utf8_str(ptr: *const u8, len: usize) {
        let addr = shopify_function_provider::log::shopify_function_log_new_utf8_str(len)
            as *const [usize; 5];
        let array = *addr;
        let source_offset = array[0];
        let dst_offset1 = array[1];
        let len1 = array[2];
        let dst_offset2 = array[3];
        let len2 = array[4];
        std::ptr::copy(ptr.add(source_offset) as _, dst_offset1 as _, len1);
        std::ptr::copy(ptr.add(source_offset).add(len1), dst_offset2 as _, len2);
    }

    // Other.
    pub(crate) unsafe fn shopify_function_intern_utf8_str(ptr: *const u8, len: usize) -> usize {
        let result = shopify_function_provider::shopify_function_intern_utf8_str(len);
        let id = (result >> usize::BITS) as usize;
        let dst = result as usize;
        std::ptr::copy(ptr as _, dst as _, len);
        id
    }
}
#[cfg(not(target_family = "wasm"))]
use provider_fallback::*;

/// An identifier for an interned UTF-8 string.
///
/// This is returned by [`Context::intern_utf8_str`], and can be used for both reading and writing.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct InternedStringId(shopify_function_wasm_api_core::InternedStringId);

impl InternedStringId {
    fn as_usize(&self) -> usize {
        self.0
    }
}

// The underlying string interner is thread local so the cache needs to be thread local too
thread_local! {
    static INTERNED_STRING_CACHE: RefCell<HashMap::<&'static str, InternedStringId>> = RefCell::new(HashMap::new());
}

/// A mechanism for caching interned string IDs.
pub struct CachedInternedStringId {
    value: &'static str,
}

impl CachedInternedStringId {
    /// Create a new cached interned string ID.
    pub const fn new(value: &'static str) -> Self {
        Self { value }
    }

    /// Load the interned string ID.
    pub fn load(&self) -> InternedStringId {
        INTERNED_STRING_CACHE.with_borrow_mut(|cache| {
            *cache.entry(self.value).or_insert_with(|| {
                InternedStringId(unsafe {
                    shopify_function_intern_utf8_str(self.value.as_ptr(), self.value.len())
                })
            })
        })
    }
}

/// A value read from the input.
///
/// This can be any of the following types:
/// - boolean
/// - number
/// - string
/// - null
/// - object
/// - array
/// - error
#[derive(Copy, Clone)]
pub struct Value {
    nan_box: NanBox,
}

impl Value {
    fn new_child(&self, nan_box: NanBox) -> Self {
        Self { nan_box }
    }

    /// Intern a string. This is just a convenience method equivalent to calling [`Context::intern_utf8_str`], if you don't have a [`Context`] easily accessible.
    pub fn intern_utf8_str(&self, s: &str) -> InternedStringId {
        let len = s.len();
        let ptr = s.as_ptr();
        let id = unsafe { shopify_function_intern_utf8_str(ptr, len) };
        InternedStringId(id)
    }

    /// Get the value as a boolean, if it is one.
    pub fn as_bool(&self) -> Option<bool> {
        match self.nan_box.try_decode() {
            Ok(ValueRef::Bool(b)) => Some(b),
            _ => None,
        }
    }

    /// Check if the value is null.
    pub fn is_null(&self) -> bool {
        matches!(self.nan_box.try_decode(), Ok(ValueRef::Null))
    }

    /// Get the value as a number, if it is one. Note that this will apply to both integers and floats.
    pub fn as_number(&self) -> Option<f64> {
        match self.nan_box.try_decode() {
            Ok(ValueRef::Number(n)) => Some(n),
            _ => None,
        }
    }

    /// Get the value as a string, if it is one.
    pub fn as_string(&self) -> Option<String> {
        match self.nan_box.try_decode() {
            Ok(ValueRef::String { ptr, len }) => {
                let len = if len == NanBox::MAX_VALUE_LENGTH {
                    unsafe { shopify_function_input_get_val_len(self.nan_box.to_bits()) }
                } else {
                    len
                };
                let mut buf = vec![0; len];
                unsafe { shopify_function_input_read_utf8_str(ptr as _, buf.as_mut_ptr(), len) };
                Some(unsafe { String::from_utf8_unchecked(buf) })
            }
            _ => None,
        }
    }

    /// Check if the value is an object.
    pub fn is_obj(&self) -> bool {
        matches!(self.nan_box.try_decode(), Ok(ValueRef::Object { .. }))
    }

    /// Get a property from the object.
    pub fn get_obj_prop(&self, prop: &str) -> Self {
        let scope = unsafe {
            shopify_function_input_get_obj_prop(self.nan_box.to_bits(), prop.as_ptr(), prop.len())
        };
        self.new_child(NanBox::from_bits(scope))
    }

    /// Get a property from the object by its interned string ID.
    pub fn get_interned_obj_prop(&self, interned_string_id: InternedStringId) -> Self {
        let scope = unsafe {
            shopify_function_input_get_interned_obj_prop(
                self.nan_box.to_bits(),
                interned_string_id.as_usize(),
            )
        };
        self.new_child(NanBox::from_bits(scope))
    }

    /// Check if the value is an array.
    pub fn is_array(&self) -> bool {
        matches!(self.nan_box.try_decode(), Ok(ValueRef::Array { .. }))
    }

    /// Get the length of the array, if it is one.
    pub fn array_len(&self) -> Option<usize> {
        match self.nan_box.try_decode() {
            Ok(ValueRef::Array { len, .. }) => {
                let len = if len == NanBox::MAX_VALUE_LENGTH {
                    unsafe { shopify_function_input_get_val_len(self.nan_box.to_bits()) }
                } else {
                    len
                };
                if len == usize::MAX {
                    None
                } else {
                    Some(len)
                }
            }
            _ => None,
        }
    }

    /// Get the length of the object, if it is one.
    pub fn obj_len(&self) -> Option<usize> {
        match self.nan_box.try_decode() {
            Ok(ValueRef::Object { len, .. }) => {
                let len = if len == NanBox::MAX_VALUE_LENGTH {
                    unsafe { shopify_function_input_get_val_len(self.nan_box.to_bits()) }
                } else {
                    len
                };
                if len == usize::MAX {
                    None
                } else {
                    Some(len)
                }
            }
            _ => None,
        }
    }

    /// Get an element from the array or object by its index.
    pub fn get_at_index(&self, index: usize) -> Self {
        let scope = unsafe { shopify_function_input_get_at_index(self.nan_box.to_bits(), index) };
        self.new_child(NanBox::from_bits(scope))
    }

    /// Get the key of an object by its index.
    pub fn get_obj_key_at_index(&self, index: usize) -> Option<String> {
        match self.nan_box.try_decode() {
            Ok(ValueRef::Object { .. }) => {
                let scope = unsafe {
                    shopify_function_input_get_obj_key_at_index(self.nan_box.to_bits(), index)
                };
                let value = self.new_child(NanBox::from_bits(scope));
                value.as_string()
            }
            _ => None,
        }
    }

    /// Get the error code, if it is one.
    pub fn as_error(&self) -> Option<ErrorCode> {
        match self.nan_box.try_decode() {
            Ok(ValueRef::Error(e)) => Some(e),
            _ => None,
        }
    }
}

/// A context for reading and writing values.
///
/// This is created by calling [`Context::new`], and is used to read values from the input and write values to the output.
pub struct Context;

/// An error that can occur when creating a [`Context`].
#[derive(Debug)]
#[non_exhaustive]
pub enum ContextError {
    /// The pointer to the context is null.
    NullPointer,
}

impl std::error::Error for ContextError {}

impl std::fmt::Display for ContextError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ContextError::NullPointer => write!(f, "Null pointer encountered"),
        }
    }
}

impl Context {
    /// Create a new context.
    ///
    /// This is only intended to be invoked when compiled to a Wasm target.
    ///
    /// # Panics
    /// This will panic if called from a non-Wasm environment.
    pub fn new() -> Self {
        #[cfg(not(target_family = "wasm"))]
        panic!("Cannot run in non-WASM environment; use `new_with_input` instead");

        #[cfg(target_family = "wasm")]
        {
            Self
        }
    }

    /// Create a new context from a JSON value, which will be the top-level value of the input.
    ///
    /// This is only available when compiled to a non-Wasm target, for usage in unit tests.
    #[cfg(not(target_family = "wasm"))]
    pub fn new_with_input(input: serde_json::Value) -> Self {
        let bytes = rmp_serde::to_vec(&input).unwrap();
        shopify_function_provider::initialize_from_msgpack_bytes(bytes);
        Self
    }

    /// Get the top-level value of the input.
    pub fn input_get(&self) -> Result<Value, ContextError> {
        let val = unsafe { shopify_function_input_get() };
        Ok(Value {
            nan_box: NanBox::from_bits(val),
        })
    }

    /// Intern a string. This can lead to performance gains if you are using the same string multiple times,
    /// as it saves unnecessary string copies. For example, if you are reading the same property from multiple objects,
    /// or serializing the same key on an object, you can intern the string once and reuse it.
    pub fn intern_utf8_str(&self, s: &str) -> InternedStringId {
        let len = s.len();
        let ptr = s.as_ptr();
        let id = unsafe { shopify_function_intern_utf8_str(ptr, len) };
        InternedStringId(id)
    }
}

impl Default for Context {
    fn default() -> Self {
        Self::new()
    }
}

/// Configures panics to write to the logging API.
pub fn init_panic_handler() {
    #[cfg(target_family = "wasm")]
    std::panic::set_hook(Box::new(|info| {
        let message = format!("{info}\n");
        log::log_utf8_str(&message);
    }));
}

#[cfg(test)]
mod tests {
    use std::thread;

    use super::*;

    // A CachedInternedStringId does not have to be static but in practice, the `shopify_function`
    // macro makes it static so we should test with it being static.
    static CACHED_INTERNED_STRING_ID: CachedInternedStringId = CachedInternedStringId::new("test");

    #[test]
    fn test_interned_string_id_cache() {
        let mut context = Context::new_with_input(serde_json::json!({}));
        let id = CACHED_INTERNED_STRING_ID.load();
        let id2 = CACHED_INTERNED_STRING_ID.load();
        context.write_interned_utf8_str(id).unwrap();
        assert_eq!(id, id2);

        // Test writing again with new context in same test to test same thread execution.
        let mut context = Context::new_with_input(serde_json::json!({}));
        context.write_interned_utf8_str(id).unwrap();
    }

    #[test]
    fn test_interned_string_id_in_another_test() {
        let mut context = Context::new_with_input(serde_json::json!({}));
        let id = CACHED_INTERNED_STRING_ID.load();
        context.write_interned_utf8_str(id).unwrap();
    }

    #[test]
    fn test_interned_string_in_new_thread() {
        let mut context = Context::new_with_input(serde_json::json!({}));
        let id = CACHED_INTERNED_STRING_ID.load();
        context.write_interned_utf8_str(id).unwrap();
        // Test this still works across multiple threads.
        thread::spawn(|| {
            let mut context = Context::new_with_input(serde_json::json!({}));
            let id = CACHED_INTERNED_STRING_ID.load();
            context.write_interned_utf8_str(id).unwrap();
        })
        .join()
        .unwrap();
    }

    #[test]
    fn test_array_len_with_null_ptr() {
        Context::new_with_input(serde_json::json!({}));
        let value = Value {
            nan_box: NanBox::array(0, NanBox::MAX_VALUE_LENGTH),
        };
        let len = value.array_len();
        assert_eq!(len, None);
    }

    #[test]
    fn test_array_len_with_non_length_eligible_nan_box() {
        Context::new_with_input(serde_json::json!({}));
        let value = Value {
            nan_box: NanBox::null(),
        };
        let len = value.array_len();
        assert_eq!(len, None);
    }

    #[test]
    fn test_obj_len_with_null_ptr() {
        Context::new_with_input(serde_json::json!({}));
        let value = Value {
            nan_box: NanBox::obj(0, NanBox::MAX_VALUE_LENGTH),
        };
        let len = value.obj_len();
        assert_eq!(len, None);
    }

    #[test]
    fn test_obj_len_with_non_length_eligible_nan_box() {
        Context::new_with_input(serde_json::json!({}));
        let value = Value {
            nan_box: NanBox::null(),
        };
        let len = value.obj_len();
        assert_eq!(len, None);
    }
}