flaron-sdk 1.0.0

Official Rust SDK for writing Flaron edge flares - WebAssembly modules that run on the Flaron CDN edge runtime.
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
//! Raw FFI bindings to the `flaron/v1` host module.
//!
//! These declarations match the Wasm imports the flaron host registers in
//! `internal/corona/hostapi*.go`. They are private to the crate; consumers use
//! the safe wrappers in [`crate::request`], [`crate::spark`], etc.
//!
//! Calling convention:
//! * `i64` returns are packed `(ptr << 32) | len` pairs that point at memory
//!   the host wrote into the guest's linear memory via the guest-exported
//!   `alloc` function. A return value of `0` always means "no result".
//! * `i32` returns from write-style functions are status codes - `0` means
//!   success, non-zero values are documented per host function.
//! * String/byte arguments are passed as `(ptr, len)` pairs into guest memory
//!   the SDK already owns (string slices, `&[u8]`, JSON buffers).
//!
//! ## Test mock host
//!
//! On non-wasm targets (anywhere `cargo test` runs natively), the real extern
//! block is replaced by a thread-local mock host implemented in Rust. Tests
//! configure the mock through [`test_host`] and the SDK runs unchanged. The
//! mock host writes responses into the same per-thread bump arena the wasm
//! build uses, so wire-format handling is exercised exactly as it would be
//! on a real edge node.

#[cfg(target_arch = "wasm32")]
#[link(wasm_import_module = "flaron/v1")]
extern "C" {
    pub fn req_method() -> i64;
    pub fn req_url() -> i64;
    pub fn req_header_get(name_ptr: i32, name_len: i32) -> i64;
    pub fn req_body() -> i64;

    pub fn resp_set_status(status: i32);
    pub fn resp_header_set(name_ptr: i32, name_len: i32, val_ptr: i32, val_len: i32);
    pub fn resp_body_set(body_ptr: i32, body_len: i32);

    pub fn beam_fetch(url_ptr: i32, url_len: i32, opts_ptr: i32, opts_len: i32) -> i64;

    pub fn log_info(msg_ptr: i32, msg_len: i32);
    pub fn log_warn(msg_ptr: i32, msg_len: i32);
    pub fn log_error(msg_ptr: i32, msg_len: i32);

    pub fn crypto_hash(args_ptr: i32, args_len: i32) -> i64;
    pub fn crypto_hmac(args_ptr: i32, args_len: i32) -> i64;
    pub fn crypto_sign_jwt(args_ptr: i32, args_len: i32) -> i64;
    pub fn crypto_encrypt_aes(args_ptr: i32, args_len: i32) -> i64;
    pub fn crypto_decrypt_aes(args_ptr: i32, args_len: i32) -> i64;
    pub fn crypto_random_bytes(length: i32) -> i64;

    pub fn encoding_base64_encode(data_ptr: i32, data_len: i32) -> i64;
    pub fn encoding_base64_decode(data_ptr: i32, data_len: i32) -> i64;
    pub fn encoding_hex_encode(data_ptr: i32, data_len: i32) -> i64;
    pub fn encoding_hex_decode(data_ptr: i32, data_len: i32) -> i64;
    pub fn encoding_url_encode(data_ptr: i32, data_len: i32) -> i64;
    pub fn encoding_url_decode(data_ptr: i32, data_len: i32) -> i64;

    pub fn id_uuid(args_ptr: i32, args_len: i32) -> i64;
    pub fn id_ulid() -> i64;
    pub fn id_nanoid(length: i32) -> i64;
    pub fn id_ksuid() -> i64;
    pub fn snowflake_id() -> i64;

    pub fn timestamp(args_ptr: i32, args_len: i32) -> i64;

    pub fn spark_get(key_ptr: i32, key_len: i32) -> i64;
    pub fn spark_set(key_ptr: i32, key_len: i32, val_ptr: i32, val_len: i32, ttl_secs: i32) -> i32;
    pub fn spark_delete(key_ptr: i32, key_len: i32);
    pub fn spark_list() -> i64;
    pub fn spark_pull(origin_ptr: i32, origin_len: i32, keys_ptr: i32, keys_len: i32) -> i32;

    pub fn plasma_get(key_ptr: i32, key_len: i32) -> i64;
    pub fn plasma_set(key_ptr: i32, key_len: i32, val_ptr: i32, val_len: i32) -> i32;
    pub fn plasma_delete(key_ptr: i32, key_len: i32) -> i32;
    pub fn plasma_increment(key_ptr: i32, key_len: i32, delta: i64) -> i64;
    pub fn plasma_decrement(key_ptr: i32, key_len: i32, delta: i64) -> i64;
    pub fn plasma_list() -> i64;

    pub fn secret_get(key_ptr: i32, key_len: i32) -> i64;

    pub fn ws_send(data_ptr: i32, data_len: i32) -> i32;
    pub fn ws_close_conn(code: i32);
    pub fn ws_conn_id() -> i64;
    pub fn ws_event_type() -> i64;
    pub fn ws_event_data() -> i64;
    pub fn ws_close_code() -> i32;
}

// =====================================================================
// Mock host for non-wasm builds (cargo test on the host).
// =====================================================================

#[cfg(not(target_arch = "wasm32"))]
pub use host_mock::*;

#[cfg(not(target_arch = "wasm32"))]
#[allow(dead_code)]
pub mod test_host {
    use std::cell::RefCell;
    use std::collections::HashMap;

    /// Captured state for a single test thread. Configure fields to set up
    /// host responses, then call the SDK; inspect fields after to verify
    /// captured arguments.
    #[derive(Default, Debug)]
    pub struct MockHost {
        // ----- Request -----
        pub req_method: Option<String>,
        pub req_url: Option<String>,
        pub req_headers: HashMap<String, String>,
        pub req_body: Option<Vec<u8>>,

        // ----- Response (captured by setters) -----
        pub resp_status: Option<i32>,
        pub resp_headers: Vec<(String, String)>,
        pub resp_body: Option<Vec<u8>>,

        // ----- Beam -----
        pub beam_response: Option<Vec<u8>>,
        pub last_beam_url: Option<String>,
        pub last_beam_opts: Option<String>,

        // ----- Logging -----
        pub logs: Vec<(&'static str, String)>,

        // ----- Crypto -----
        pub crypto_hash_response: Option<String>,
        pub crypto_hmac_response: Option<String>,
        pub crypto_sign_jwt_response: Option<String>,
        pub crypto_encrypt_aes_response: Option<String>,
        pub crypto_decrypt_aes_response: Option<Vec<u8>>,
        pub crypto_random_bytes_response: Option<String>,
        pub last_crypto_hash_args: Option<String>,
        pub last_crypto_hmac_args: Option<String>,
        pub last_crypto_sign_jwt_args: Option<String>,
        pub last_crypto_encrypt_aes_args: Option<String>,
        pub last_crypto_decrypt_aes_args: Option<String>,
        pub last_random_bytes_length: Option<i32>,

        // ----- Encoding -----
        pub encoding_base64_encode_response: Option<String>,
        pub encoding_base64_decode_response: Option<Vec<u8>>,
        pub encoding_hex_encode_response: Option<String>,
        pub encoding_hex_decode_response: Option<Vec<u8>>,
        pub encoding_url_encode_response: Option<String>,
        pub encoding_url_decode_response: Option<String>,
        pub last_encoding_base64_encode_input: Option<Vec<u8>>,
        pub last_encoding_base64_decode_input: Option<String>,
        pub last_encoding_hex_encode_input: Option<Vec<u8>>,
        pub last_encoding_hex_decode_input: Option<String>,
        pub last_encoding_url_encode_input: Option<String>,
        pub last_encoding_url_decode_input: Option<String>,

        // ----- ID generators -----
        pub id_uuid_response: Option<String>,
        pub id_ulid_response: Option<String>,
        pub id_nanoid_response: Option<String>,
        pub id_ksuid_response: Option<String>,
        pub snowflake_id_response: Option<String>,
        pub last_id_uuid_args: Option<String>,
        pub last_nanoid_length: Option<i32>,

        // ----- Timestamp -----
        pub timestamp_response: Option<String>,
        pub last_timestamp_args: Option<String>,

        // ----- Spark -----
        pub spark_store: HashMap<String, (Vec<u8>, u32)>,
        pub spark_set_error: i32,
        pub spark_pull_result: i32,
        pub spark_deletes: Vec<String>,
        pub spark_pull_calls: Vec<(String, String)>,
        pub last_spark_set: Option<(String, Vec<u8>, i32)>,

        // ----- Plasma -----
        pub plasma_store: HashMap<String, Vec<u8>>,
        pub plasma_counters: HashMap<String, i64>,
        pub plasma_set_error: i32,
        pub plasma_delete_error: i32,
        pub plasma_increment_error: bool,
        pub plasma_deletes: Vec<String>,
        pub last_plasma_set: Option<(String, Vec<u8>)>,
        pub last_plasma_increment: Option<(String, i64)>,
        pub last_plasma_decrement: Option<(String, i64)>,

        // ----- Secrets -----
        pub secrets: HashMap<String, Vec<u8>>,
        pub last_secret_get: Option<String>,

        // ----- WebSocket -----
        pub ws_send_error: i32,
        pub ws_conn_id: Option<String>,
        pub ws_event_type: Option<String>,
        pub ws_event_data: Option<Vec<u8>>,
        pub ws_close_code: i32,
        pub ws_closes: Vec<i32>,
        pub ws_sends: Vec<Vec<u8>>,
    }

    thread_local! {
        static MOCK: RefCell<MockHost> = RefCell::new(MockHost::default());
    }

    /// Run a closure with mutable access to this thread's mock host.
    pub fn with_mock<R>(f: impl FnOnce(&mut MockHost) -> R) -> R {
        MOCK.with(|m| f(&mut m.borrow_mut()))
    }

    /// Read mock host state without mutation.
    pub fn read_mock<R>(f: impl FnOnce(&MockHost) -> R) -> R {
        MOCK.with(|m| f(&m.borrow()))
    }

    /// Reset the mock host AND the bump arena to a clean slate. Call at the
    /// top of every test.
    pub fn reset() {
        MOCK.with(|m| *m.borrow_mut() = MockHost::default());
        crate::mem::reset_arena();
    }
}

#[cfg(not(target_arch = "wasm32"))]
mod host_mock {
    use super::test_host::with_mock;
    use crate::mem;

    /// Allocate from the arena and copy bytes in, returning packed
    /// `(offset, len)`. Returns 0 on allocation failure.
    fn write_arena(data: &[u8]) -> i64 {
        if data.is_empty() {
            // Non-zero packed value for empty results: take a 1-byte slot
            // so the offset isn't 0 (which the SDK reads as "no result").
            let offset = mem::guest_alloc(1);
            if offset == 0 {
                return 0;
            }
            return mem::encode_ptr_len(offset as u32, 0);
        }
        let offset = mem::guest_alloc(data.len() as i32);
        if offset == 0 {
            return 0;
        }
        mem::arena_write_at(offset as usize, data);
        mem::encode_ptr_len(offset as u32, data.len() as u32)
    }

    /// Read SDK-passed argument bytes from the arena. On non-wasm targets the
    /// SDK uses [`mem::host_arg_bytes`] to copy each arg into the arena
    /// before passing the offset, so we read it back the same way.
    fn read_arg(offset: i32, len: i32) -> Vec<u8> {
        if len <= 0 {
            return Vec::new();
        }
        mem::arena_read_at(offset as usize, len as usize)
    }

    fn read_arg_str(offset: i32, len: i32) -> String {
        String::from_utf8_lossy(&read_arg(offset, len)).into_owned()
    }

    // ---------- Request ----------

    pub unsafe fn req_method() -> i64 {
        with_mock(|m| match m.req_method.as_deref() {
            Some(s) => write_arena(s.as_bytes()),
            None => 0,
        })
    }

    pub unsafe fn req_url() -> i64 {
        with_mock(|m| match m.req_url.as_deref() {
            Some(s) => write_arena(s.as_bytes()),
            None => 0,
        })
    }

    pub unsafe fn req_header_get(name_ptr: i32, name_len: i32) -> i64 {
        let name = read_arg_str(name_ptr, name_len);
        with_mock(|m| match m.req_headers.get(&name) {
            Some(v) => write_arena(v.as_bytes()),
            None => 0,
        })
    }

    pub unsafe fn req_body() -> i64 {
        with_mock(|m| match m.req_body.as_deref() {
            Some(b) => write_arena(b),
            None => 0,
        })
    }

    // ---------- Response ----------

    pub unsafe fn resp_set_status(status: i32) {
        with_mock(|m| m.resp_status = Some(status));
    }

    pub unsafe fn resp_header_set(name_ptr: i32, name_len: i32, val_ptr: i32, val_len: i32) {
        let name = read_arg_str(name_ptr, name_len);
        let val = read_arg_str(val_ptr, val_len);
        with_mock(|m| m.resp_headers.push((name, val)));
    }

    pub unsafe fn resp_body_set(body_ptr: i32, body_len: i32) {
        let body = read_arg(body_ptr, body_len);
        with_mock(|m| m.resp_body = Some(body));
    }

    // ---------- Beam ----------

    pub unsafe fn beam_fetch(url_ptr: i32, url_len: i32, opts_ptr: i32, opts_len: i32) -> i64 {
        let url = read_arg_str(url_ptr, url_len);
        let opts = read_arg_str(opts_ptr, opts_len);
        with_mock(|m| {
            m.last_beam_url = Some(url);
            m.last_beam_opts = Some(opts);
            match m.beam_response.as_deref() {
                Some(b) => write_arena(b),
                None => 0,
            }
        })
    }

    // ---------- Logging ----------

    pub unsafe fn log_info(msg_ptr: i32, msg_len: i32) {
        let msg = read_arg_str(msg_ptr, msg_len);
        with_mock(|m| m.logs.push(("info", msg)));
    }

    pub unsafe fn log_warn(msg_ptr: i32, msg_len: i32) {
        let msg = read_arg_str(msg_ptr, msg_len);
        with_mock(|m| m.logs.push(("warn", msg)));
    }

    pub unsafe fn log_error(msg_ptr: i32, msg_len: i32) {
        let msg = read_arg_str(msg_ptr, msg_len);
        with_mock(|m| m.logs.push(("error", msg)));
    }

    // ---------- Crypto ----------

    pub unsafe fn crypto_hash(args_ptr: i32, args_len: i32) -> i64 {
        let args = read_arg_str(args_ptr, args_len);
        with_mock(|m| {
            m.last_crypto_hash_args = Some(args);
            match m.crypto_hash_response.as_deref() {
                Some(s) => write_arena(s.as_bytes()),
                None => 0,
            }
        })
    }

    pub unsafe fn crypto_hmac(args_ptr: i32, args_len: i32) -> i64 {
        let args = read_arg_str(args_ptr, args_len);
        with_mock(|m| {
            m.last_crypto_hmac_args = Some(args);
            match m.crypto_hmac_response.as_deref() {
                Some(s) => write_arena(s.as_bytes()),
                None => 0,
            }
        })
    }

    pub unsafe fn crypto_sign_jwt(args_ptr: i32, args_len: i32) -> i64 {
        let args = read_arg_str(args_ptr, args_len);
        with_mock(|m| {
            m.last_crypto_sign_jwt_args = Some(args);
            match m.crypto_sign_jwt_response.as_deref() {
                Some(s) => write_arena(s.as_bytes()),
                None => 0,
            }
        })
    }

    pub unsafe fn crypto_encrypt_aes(args_ptr: i32, args_len: i32) -> i64 {
        let args = read_arg_str(args_ptr, args_len);
        with_mock(|m| {
            m.last_crypto_encrypt_aes_args = Some(args);
            match m.crypto_encrypt_aes_response.as_deref() {
                Some(s) => write_arena(s.as_bytes()),
                None => 0,
            }
        })
    }

    pub unsafe fn crypto_decrypt_aes(args_ptr: i32, args_len: i32) -> i64 {
        let args = read_arg_str(args_ptr, args_len);
        with_mock(|m| {
            m.last_crypto_decrypt_aes_args = Some(args);
            match m.crypto_decrypt_aes_response.as_deref() {
                Some(b) => write_arena(b),
                None => 0,
            }
        })
    }

    pub unsafe fn crypto_random_bytes(length: i32) -> i64 {
        with_mock(|m| {
            m.last_random_bytes_length = Some(length);
            match m.crypto_random_bytes_response.as_deref() {
                Some(s) => write_arena(s.as_bytes()),
                None => 0,
            }
        })
    }

    // ---------- Encoding ----------

    pub unsafe fn encoding_base64_encode(data_ptr: i32, data_len: i32) -> i64 {
        let input = read_arg(data_ptr, data_len);
        with_mock(|m| {
            m.last_encoding_base64_encode_input = Some(input);
            match m.encoding_base64_encode_response.as_deref() {
                Some(s) => write_arena(s.as_bytes()),
                None => 0,
            }
        })
    }

    pub unsafe fn encoding_base64_decode(data_ptr: i32, data_len: i32) -> i64 {
        let input = read_arg_str(data_ptr, data_len);
        with_mock(|m| {
            m.last_encoding_base64_decode_input = Some(input);
            match m.encoding_base64_decode_response.as_deref() {
                Some(b) => write_arena(b),
                None => 0,
            }
        })
    }

    pub unsafe fn encoding_hex_encode(data_ptr: i32, data_len: i32) -> i64 {
        let input = read_arg(data_ptr, data_len);
        with_mock(|m| {
            m.last_encoding_hex_encode_input = Some(input);
            match m.encoding_hex_encode_response.as_deref() {
                Some(s) => write_arena(s.as_bytes()),
                None => 0,
            }
        })
    }

    pub unsafe fn encoding_hex_decode(data_ptr: i32, data_len: i32) -> i64 {
        let input = read_arg_str(data_ptr, data_len);
        with_mock(|m| {
            m.last_encoding_hex_decode_input = Some(input);
            match m.encoding_hex_decode_response.as_deref() {
                Some(b) => write_arena(b),
                None => 0,
            }
        })
    }

    pub unsafe fn encoding_url_encode(data_ptr: i32, data_len: i32) -> i64 {
        let input = read_arg_str(data_ptr, data_len);
        with_mock(|m| {
            m.last_encoding_url_encode_input = Some(input);
            match m.encoding_url_encode_response.as_deref() {
                Some(s) => write_arena(s.as_bytes()),
                None => 0,
            }
        })
    }

    pub unsafe fn encoding_url_decode(data_ptr: i32, data_len: i32) -> i64 {
        let input = read_arg_str(data_ptr, data_len);
        with_mock(|m| {
            m.last_encoding_url_decode_input = Some(input);
            match m.encoding_url_decode_response.as_deref() {
                Some(s) => write_arena(s.as_bytes()),
                None => 0,
            }
        })
    }

    // ---------- ID generators ----------

    pub unsafe fn id_uuid(args_ptr: i32, args_len: i32) -> i64 {
        let args = read_arg_str(args_ptr, args_len);
        with_mock(|m| {
            m.last_id_uuid_args = Some(args);
            match m.id_uuid_response.as_deref() {
                Some(s) => write_arena(s.as_bytes()),
                None => 0,
            }
        })
    }

    pub unsafe fn id_ulid() -> i64 {
        with_mock(|m| match m.id_ulid_response.as_deref() {
            Some(s) => write_arena(s.as_bytes()),
            None => 0,
        })
    }

    pub unsafe fn id_nanoid(length: i32) -> i64 {
        with_mock(|m| {
            m.last_nanoid_length = Some(length);
            match m.id_nanoid_response.as_deref() {
                Some(s) => write_arena(s.as_bytes()),
                None => 0,
            }
        })
    }

    pub unsafe fn id_ksuid() -> i64 {
        with_mock(|m| match m.id_ksuid_response.as_deref() {
            Some(s) => write_arena(s.as_bytes()),
            None => 0,
        })
    }

    pub unsafe fn snowflake_id() -> i64 {
        with_mock(|m| match m.snowflake_id_response.as_deref() {
            Some(s) => write_arena(s.as_bytes()),
            None => 0,
        })
    }

    // ---------- Timestamp ----------

    pub unsafe fn timestamp(args_ptr: i32, args_len: i32) -> i64 {
        let args = read_arg_str(args_ptr, args_len);
        with_mock(|m| {
            m.last_timestamp_args = Some(args);
            match m.timestamp_response.as_deref() {
                Some(s) => write_arena(s.as_bytes()),
                None => 0,
            }
        })
    }

    // ---------- Spark ----------

    pub unsafe fn spark_get(key_ptr: i32, key_len: i32) -> i64 {
        let key = read_arg_str(key_ptr, key_len);
        with_mock(|m| match m.spark_store.get(&key) {
            Some((value, ttl)) => {
                let mut payload = ttl.to_le_bytes().to_vec();
                payload.extend_from_slice(value);
                write_arena(&payload)
            }
            None => 0,
        })
    }

    pub unsafe fn spark_set(
        key_ptr: i32,
        key_len: i32,
        val_ptr: i32,
        val_len: i32,
        ttl_secs: i32,
    ) -> i32 {
        let key = read_arg_str(key_ptr, key_len);
        let val = read_arg(val_ptr, val_len);
        with_mock(|m| {
            m.last_spark_set = Some((key.clone(), val.clone(), ttl_secs));
            if m.spark_set_error != 0 {
                return m.spark_set_error;
            }
            m.spark_store.insert(key, (val, ttl_secs.max(0) as u32));
            0
        })
    }

    pub unsafe fn spark_delete(key_ptr: i32, key_len: i32) {
        let key = read_arg_str(key_ptr, key_len);
        with_mock(|m| {
            m.spark_store.remove(&key);
            m.spark_deletes.push(key);
        });
    }

    pub unsafe fn spark_list() -> i64 {
        with_mock(|m| {
            let keys: Vec<&String> = m.spark_store.keys().collect();
            let json = serde_json::to_string(&keys).unwrap_or_else(|_| "[]".into());
            write_arena(json.as_bytes())
        })
    }

    pub unsafe fn spark_pull(
        origin_ptr: i32,
        origin_len: i32,
        keys_ptr: i32,
        keys_len: i32,
    ) -> i32 {
        let origin = read_arg_str(origin_ptr, origin_len);
        let keys = read_arg_str(keys_ptr, keys_len);
        with_mock(|m| {
            m.spark_pull_calls.push((origin, keys));
            m.spark_pull_result
        })
    }

    // ---------- Plasma ----------

    pub unsafe fn plasma_get(key_ptr: i32, key_len: i32) -> i64 {
        let key = read_arg_str(key_ptr, key_len);
        with_mock(|m| match m.plasma_store.get(&key) {
            Some(v) => write_arena(v),
            None => 0,
        })
    }

    pub unsafe fn plasma_set(key_ptr: i32, key_len: i32, val_ptr: i32, val_len: i32) -> i32 {
        let key = read_arg_str(key_ptr, key_len);
        let val = read_arg(val_ptr, val_len);
        with_mock(|m| {
            m.last_plasma_set = Some((key.clone(), val.clone()));
            if m.plasma_set_error != 0 {
                return m.plasma_set_error;
            }
            m.plasma_store.insert(key, val);
            0
        })
    }

    pub unsafe fn plasma_delete(key_ptr: i32, key_len: i32) -> i32 {
        let key = read_arg_str(key_ptr, key_len);
        with_mock(|m| {
            m.plasma_deletes.push(key.clone());
            if m.plasma_delete_error != 0 {
                return m.plasma_delete_error;
            }
            m.plasma_store.remove(&key);
            0
        })
    }

    pub unsafe fn plasma_increment(key_ptr: i32, key_len: i32, delta: i64) -> i64 {
        let key = read_arg_str(key_ptr, key_len);
        with_mock(|m| {
            m.last_plasma_increment = Some((key.clone(), delta));
            if m.plasma_increment_error {
                return 0;
            }
            let counter = m.plasma_counters.entry(key).or_insert(0);
            *counter += delta;
            let bytes = counter.to_le_bytes();
            write_arena(&bytes)
        })
    }

    pub unsafe fn plasma_decrement(key_ptr: i32, key_len: i32, delta: i64) -> i64 {
        let key = read_arg_str(key_ptr, key_len);
        with_mock(|m| {
            m.last_plasma_decrement = Some((key.clone(), delta));
            if m.plasma_increment_error {
                return 0;
            }
            let counter = m.plasma_counters.entry(key).or_insert(0);
            *counter -= delta;
            let bytes = counter.to_le_bytes();
            write_arena(&bytes)
        })
    }

    pub unsafe fn plasma_list() -> i64 {
        with_mock(|m| {
            let keys: Vec<&String> = m.plasma_store.keys().collect();
            let json = serde_json::to_string(&keys).unwrap_or_else(|_| "[]".into());
            write_arena(json.as_bytes())
        })
    }

    // ---------- Secrets ----------

    pub unsafe fn secret_get(key_ptr: i32, key_len: i32) -> i64 {
        let key = read_arg_str(key_ptr, key_len);
        with_mock(|m| {
            m.last_secret_get = Some(key.clone());
            match m.secrets.get(&key) {
                Some(v) => write_arena(v),
                None => 0,
            }
        })
    }

    // ---------- WebSocket ----------

    pub unsafe fn ws_send(data_ptr: i32, data_len: i32) -> i32 {
        let data = read_arg(data_ptr, data_len);
        with_mock(|m| {
            m.ws_sends.push(data);
            m.ws_send_error
        })
    }

    pub unsafe fn ws_close_conn(code: i32) {
        with_mock(|m| m.ws_closes.push(code));
    }

    pub unsafe fn ws_conn_id() -> i64 {
        with_mock(|m| match m.ws_conn_id.as_deref() {
            Some(s) => write_arena(s.as_bytes()),
            None => 0,
        })
    }

    pub unsafe fn ws_event_type() -> i64 {
        with_mock(|m| match m.ws_event_type.as_deref() {
            Some(s) => write_arena(s.as_bytes()),
            None => 0,
        })
    }

    pub unsafe fn ws_event_data() -> i64 {
        with_mock(|m| match m.ws_event_data.as_deref() {
            Some(b) => write_arena(b),
            None => 0,
        })
    }

    pub unsafe fn ws_close_code() -> i32 {
        with_mock(|m| m.ws_close_code)
    }
}