wasm-sandbox 0.4.1

A secure WebAssembly sandbox with dead-simple ease of use, progressive complexity APIs, and comprehensive safety controls
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
# Basic Usage


📖 **[← Back to Documentation]../README.md** | 🏠 **[← Main README]../../README.md** | 🚀 **[API Reference]https://docs.rs/wasm-sandbox**

Common usage patterns and everyday operations with wasm-sandbox.

## Quick Start


### Simple Function Calls


```rust
use wasm_sandbox::{WasmSandbox, Result};

#[tokio::main]

async fn main() -> Result<()> {
    // Create a sandbox
    let sandbox = WasmSandbox::builder()
        .source("calculator.wasm")
        .build()
        .await?;

    // Call functions with different types
    let sum: i32 = sandbox.call("add", (10, 20)).await?;
    let greeting: String = sandbox.call("greet", "Alice").await?;
    let result: f64 = sandbox.call("sqrt", 16.0).await?;

    println!("Sum: {}, Greeting: {}, Square root: {}", sum, greeting, result);
    Ok(())
}
```

### Working with Complex Data


```rust
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]

struct Person {
    name: String,
    age: u32,
    email: String,
}

#[derive(Serialize, Deserialize)]

struct ProcessedData {
    count: usize,
    average_age: f64,
    valid_emails: usize,
}

#[tokio::main]

async fn main() -> Result<()> {
    let sandbox = WasmSandbox::builder()
        .source("data_processor.wasm")
        .build()
        .await?;

    let people = vec![
        Person {
            name: "Alice".to_string(),
            age: 30,
            email: "alice@example.com".to_string(),
        },
        Person {
            name: "Bob".to_string(),
            age: 25,
            email: "bob@test.com".to_string(),
        },
    ];

    // Pass complex data structures
    let result: ProcessedData = sandbox.call("process_people", &people).await?;
    println!("Processed {} people, average age: {:.1}", 
             result.count, result.average_age);
    
    Ok(())
}
```

## Configuration Patterns


### Builder Pattern Configuration


```rust
use wasm_sandbox::{WasmSandbox, SecurityPolicy, Capability};
use std::time::Duration;

#[tokio::main]

async fn main() -> Result<()> {
    let sandbox = WasmSandbox::builder()
        // Module source
        .source("module.wasm")
        
        // Resource limits
        .memory_limit(64 * 1024 * 1024) // 64MB
        .cpu_timeout(Duration::from_secs(30))
        .max_file_operations(100)
        
        // Security settings
        .security_policy(SecurityPolicy::strict())
        .add_capability(Capability::FileRead("/data".into()))
        
        // Performance options
        .optimization_level(OptimizationLevel::Speed)
        .enable_cache(true)
        
        // Debugging
        .debug_mode(false)
        .audit_enabled(true)
        
        .build()
        .await?;

    Ok(())
}
```

### Configuration from File


```rust
use serde::{Serialize, Deserialize};
use std::fs;

#[derive(Serialize, Deserialize)]

struct SandboxConfig {
    wasm_file: String,
    memory_limit_mb: u64,
    cpu_timeout_secs: u64,
    security_level: String,
    capabilities: Vec<String>,
}

impl SandboxConfig {
    fn load(path: &str) -> Result<Self> {
        let content = fs::read_to_string(path)?;
        Ok(serde_json::from_str(&content)?)
    }

    async fn create_sandbox(&self) -> Result<WasmSandbox> {
        let mut policy = match self.security_level.as_str() {
            "strict" => SecurityPolicy::strict(),
            "basic" => SecurityPolicy::basic(),
            "permissive" => SecurityPolicy::permissive(),
            _ => SecurityPolicy::basic(),
        };

        // Add capabilities from config
        for cap in &self.capabilities {
            match cap.as_str() {
                "file_read" => policy.add_capability(Capability::FileRead("/data".into())),
                "network" => policy.add_capability(Capability::NetworkAccess {
                    allowed_hosts: vec!["api.example.com".to_string()],
                    allowed_ports: vec![443],
                }),
                _ => {}
            }
        }

        WasmSandbox::builder()
            .source(&self.wasm_file)
            .memory_limit(self.memory_limit_mb * 1024 * 1024)
            .cpu_timeout(Duration::from_secs(self.cpu_timeout_secs))
            .security_policy(policy)
            .build()
            .await
    }
}

#[tokio::main]

async fn main() -> Result<()> {
    // Load configuration from file
    let config = SandboxConfig::load("sandbox_config.json")?;
    let sandbox = config.create_sandbox().await?;

    // Use configured sandbox
    let result = sandbox.call("process", "test data").await?;
    println!("Result: {:?}", result);

    Ok(())
}
```

Example `sandbox_config.json`:

```json
{
    "wasm_file": "modules/processor.wasm",
    "memory_limit_mb": 128,
    "cpu_timeout_secs": 60,
    "security_level": "strict",
    "capabilities": ["file_read", "network"]
}
```

## Error Handling Patterns


### Basic Error Handling


```rust
use wasm_sandbox::{WasmError, ErrorKind};

async fn safe_call(sandbox: &WasmSandbox, input: &str) -> Result<String> {
    match sandbox.call("process", input).await {
        Ok(result) => Ok(result),
        Err(WasmError::RuntimeError(e)) => {
            eprintln!("Runtime error: {}", e);
            // Try fallback
            sandbox.call("fallback_process", input).await
        }
        Err(WasmError::ResourceLimitExceeded(limit)) => {
            eprintln!("Resource limit exceeded: {:?}", limit);
            // Reduce input size and retry
            let reduced_input = &input[..input.len().min(1000)];
            sandbox.call("process", reduced_input).await
        }
        Err(e) => {
            eprintln!("Unexpected error: {}", e);
            Err(e)
        }
    }
}
```

### Comprehensive Error Recovery


```rust
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};

struct RetryableSandbox {
    sandbox: WasmSandbox,
    failure_count: Arc<AtomicU32>,
    max_retries: u32,
}

impl RetryableSandbox {
    async fn call_with_retry<T, A>(&self, function: &str, args: A) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
        A: serde::Serialize + Clone,
    {
        let mut attempts = 0;
        
        loop {
            match self.sandbox.call(function, &args).await {
                Ok(result) => {
                    // Reset failure count on success
                    self.failure_count.store(0, Ordering::Relaxed);
                    return Ok(result);
                }
                Err(e) => {
                    attempts += 1;
                    self.failure_count.fetch_add(1, Ordering::Relaxed);
                    
                    if attempts >= self.max_retries {
                        return Err(e);
                    }
                    
                    // Exponential backoff
                    let delay = Duration::from_millis(100 * 2_u64.pow(attempts));
                    tokio::time::sleep(delay).await;
                    
                    // Reset sandbox on certain errors
                    match &e {
                        WasmError::RuntimeError(_) => {
                            if let Err(reset_err) = self.sandbox.reset().await {
                                eprintln!("Failed to reset sandbox: {}", reset_err);
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
    }
}
```

## Data Serialization


### Multiple Serialization Formats


```rust
use wasm_sandbox::{WasmSandbox, SerializationFormat};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]

struct TestData {
    id: u32,
    values: Vec<f64>,
    metadata: std::collections::HashMap<String, String>,
}

async fn test_serialization_formats() -> Result<()> {
    let data = TestData {
        id: 42,
        values: vec![1.0, 2.0, 3.0],
        metadata: [("key".to_string(), "value".to_string())].into(),
    };

    // JSON serialization (default)
    let json_sandbox = WasmSandbox::builder()
        .source("processor.wasm")
        .serialization_format(SerializationFormat::Json)
        .build()
        .await?;

    let json_result: TestData = json_sandbox.call("process", &data).await?;
    println!("JSON result: {:?}", json_result);

    // MessagePack serialization (more efficient)
    let msgpack_sandbox = WasmSandbox::builder()
        .source("processor.wasm")
        .serialization_format(SerializationFormat::MessagePack)
        .build()
        .await?;

    let msgpack_result: TestData = msgpack_sandbox.call("process", &data).await?;
    println!("MessagePack result: {:?}", msgpack_result);

    // Bincode serialization (fastest)
    let bincode_sandbox = WasmSandbox::builder()
        .source("processor.wasm")
        .serialization_format(SerializationFormat::Bincode)
        .build()
        .await?;

    let bincode_result: TestData = bincode_sandbox.call("process", &data).await?;
    println!("Bincode result: {:?}", bincode_result);

    Ok(())
}
```

### Custom Serialization


```rust
use serde::{Serialize, Deserialize};

// Custom serialization trait
trait CustomSerialize {
    fn serialize_custom(&self) -> Result<Vec<u8>>;
    fn deserialize_custom(data: &[u8]) -> Result<Self> where Self: Sized;
}

struct CustomDataProcessor {
    sandbox: WasmSandbox,
}

impl CustomDataProcessor {
    async fn process_custom<T, R>(&self, data: &T) -> Result<R>
    where
        T: CustomSerialize,
        R: CustomSerialize,
    {
        // Serialize input using custom format
        let input_bytes = data.serialize_custom()?;
        
        // Call WebAssembly function with raw bytes
        let output_bytes: Vec<u8> = self.sandbox.call("process_bytes", &input_bytes).await?;
        
        // Deserialize result using custom format
        R::deserialize_custom(&output_bytes)
    }
}
```

## Resource Management


### Memory Monitoring


```rust
use wasm_sandbox::monitoring::MemoryMonitor;

async fn monitor_memory_usage() -> Result<()> {
    let sandbox = WasmSandbox::builder()
        .source("memory_intensive.wasm")
        .memory_limit(128 * 1024 * 1024) // 128MB
        .build()
        .await?;

    // Create memory monitor
    let monitor = MemoryMonitor::new();
    monitor.start_monitoring(&sandbox).await?;

    // Perform memory-intensive operation
    let result = sandbox.call("process_large_data", &large_dataset).await?;

    // Check memory usage
    let usage = monitor.get_current_usage().await?;
    println!("Peak memory usage: {} MB", usage.peak_memory / (1024 * 1024));
    println!("Current memory usage: {} MB", usage.current_memory / (1024 * 1024));

    // Generate memory report
    let report = monitor.generate_report().await?;
    if !report.potential_leaks.is_empty() {
        println!("Warning: {} potential memory leaks detected", report.potential_leaks.len());
    }

    Ok(())
}
```

### CPU Usage Monitoring


```rust
use wasm_sandbox::monitoring::CpuMonitor;
use std::time::Instant;

async fn monitor_cpu_usage() -> Result<()> {
    let sandbox = WasmSandbox::builder()
        .source("cpu_intensive.wasm")
        .cpu_timeout(Duration::from_secs(60))
        .build()
        .await?;

    let start_time = Instant::now();
    let cpu_monitor = CpuMonitor::new();
    cpu_monitor.start_monitoring(&sandbox).await?;

    // CPU-intensive operation
    let result = sandbox.call("fibonacci", 40).await?;

    let elapsed = start_time.elapsed();
    let cpu_usage = cpu_monitor.get_cpu_usage().await?;

    println!("Wall time: {:?}", elapsed);
    println!("CPU time: {:?}", cpu_usage.total_cpu_time);
    println!("CPU efficiency: {:.1}%", 
             (cpu_usage.total_cpu_time.as_secs_f64() / elapsed.as_secs_f64()) * 100.0);

    Ok(())
}
```

## Batch Processing


### Processing Multiple Items


```rust
async fn batch_process(items: Vec<String>) -> Result<Vec<String>> {
    let sandbox = WasmSandbox::builder()
        .source("batch_processor.wasm")
        .build()
        .await?;

    // Option 1: Process items individually
    let mut results = Vec::new();
    for item in &items {
        let result: String = sandbox.call("process_item", item).await?;
        results.push(result);
    }

    // Option 2: Process entire batch at once (more efficient)
    let batch_result: Vec<String> = sandbox.call("process_batch", &items).await?;

    Ok(batch_result)
}
```

### Parallel Batch Processing


```rust
use futures::stream::{FuturesUnordered, StreamExt};

async fn parallel_batch_process(items: Vec<String>) -> Result<Vec<String>> {
    let sandbox = Arc::new(WasmSandbox::builder()
        .source("processor.wasm")
        .build()
        .await?);

    // Create futures for each item
    let mut futures = FuturesUnordered::new();
    
    for item in items {
        let sandbox_clone = Arc::clone(&sandbox);
        let future = async move {
            sandbox_clone.call::<String, String>("process", &item).await
        };
        futures.push(future);
    }

    // Collect results
    let mut results = Vec::new();
    while let Some(result) = futures.next().await {
        results.push(result?);
    }

    Ok(results)
}
```

## State Management


### Stateful Sandbox Operations


```rust
struct StatefulProcessor {
    sandbox: WasmSandbox,
}

impl StatefulProcessor {
    async fn new() -> Result<Self> {
        let sandbox = WasmSandbox::builder()
            .source("stateful.wasm")
            .build()
            .await?;

        // Initialize state
        sandbox.call::<(), ()>("initialize", ()).await?;

        Ok(Self { sandbox })
    }

    async fn add_data(&self, data: &str) -> Result<()> {
        self.sandbox.call("add_data", data).await
    }

    async fn process_accumulated(&self) -> Result<String> {
        self.sandbox.call("process_all", ()).await
    }

    async fn reset_state(&self) -> Result<()> {
        self.sandbox.call("reset", ()).await
    }

    async fn get_state_info(&self) -> Result<StateInfo> {
        self.sandbox.call("get_state", ()).await
    }
}

#[derive(serde::Deserialize)]

struct StateInfo {
    item_count: u32,
    memory_usage: u64,
    processing_time: f64,
}
```

### Session Management


```rust
use std::collections::HashMap;
use uuid::Uuid;

struct SessionManager {
    sessions: HashMap<Uuid, WasmSandbox>,
}

impl SessionManager {
    pub fn new() -> Self {
        Self {
            sessions: HashMap::new(),
        }
    }

    pub async fn create_session(&mut self) -> Result<Uuid> {
        let session_id = Uuid::new_v4();
        let sandbox = WasmSandbox::builder()
            .source("session_processor.wasm")
            .build()
            .await?;

        self.sessions.insert(session_id, sandbox);
        Ok(session_id)
    }

    pub async fn execute_in_session<T, A>(&self, session_id: Uuid, function: &str, args: A) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
        A: serde::Serialize,
    {
        let sandbox = self.sessions.get(&session_id)
            .ok_or_else(|| "Session not found")?;

        sandbox.call(function, args).await
    }

    pub fn close_session(&mut self, session_id: Uuid) -> Result<()> {
        self.sessions.remove(&session_id)
            .ok_or_else(|| "Session not found")?;
        Ok(())
    }
}
```

## Performance Optimization


### Connection Pooling


```rust
use std::sync::Arc;
use tokio::sync::Semaphore;

struct SandboxPool {
    sandboxes: Vec<Arc<WasmSandbox>>,
    semaphore: Arc<Semaphore>,
}

impl SandboxPool {
    async fn new(wasm_path: &str, pool_size: usize) -> Result<Self> {
        let mut sandboxes = Vec::new();
        
        for _ in 0..pool_size {
            let sandbox = Arc::new(WasmSandbox::builder()
                .source(wasm_path)
                .build()
                .await?);
            sandboxes.push(sandbox);
        }

        Ok(Self {
            sandboxes,
            semaphore: Arc::new(Semaphore::new(pool_size)),
        })
    }

    async fn execute<T, A>(&self, function: &str, args: A) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
        A: serde::Serialize,
    {
        // Acquire semaphore permit
        let _permit = self.semaphore.acquire().await.unwrap();
        
        // Get available sandbox (simple round-robin)
        let sandbox_index = fastrand::usize(..self.sandboxes.len());
        let sandbox = &self.sandboxes[sandbox_index];
        
        sandbox.call(function, args).await
    }
}
```

### Caching Results


```rust
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;

struct CachedSandbox {
    sandbox: WasmSandbox,
    cache: HashMap<u64, serde_json::Value>,
    cache_ttl: Duration,
    cache_timestamps: HashMap<u64, Instant>,
}

impl CachedSandbox {
    async fn call_cached<T, A>(&mut self, function: &str, args: A) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
        A: serde::Serialize + Hash,
    {
        // Generate cache key
        let mut hasher = DefaultHasher::new();
        function.hash(&mut hasher);
        args.hash(&mut hasher);
        let cache_key = hasher.finish();

        // Check cache
        if let Some(cached_value) = self.cache.get(&cache_key) {
            if let Some(timestamp) = self.cache_timestamps.get(&cache_key) {
                if timestamp.elapsed() < self.cache_ttl {
                    return Ok(serde_json::from_value(cached_value.clone())?);
                }
            }
        }

        // Execute function
        let result = self.sandbox.call(function, args).await?;
        
        // Cache result
        let json_value = serde_json::to_value(&result)?;
        self.cache.insert(cache_key, json_value);
        self.cache_timestamps.insert(cache_key, Instant::now());

        Ok(result)
    }
}
```

Next: **[Security Configuration](security-config.md)** - Configure capabilities and security policies

---

**Usage Patterns:** Master common wasm-sandbox operations for efficient and reliable WebAssembly execution.