rs3gw 0.2.1

High-Performance AI/HPC Object Storage Gateway powered by scirs2-io
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
# WASM Plugin Developer Guide

Complete guide for developing custom WebAssembly plugins for rs3gw's transformation system.

## Table of Contents

- [Introduction]#introduction
- [Plugin Contract]#plugin-contract
- [Development Setup]#development-setup
- [Creating Your First Plugin]#creating-your-first-plugin
- [Advanced Topics]#advanced-topics
- [Best Practices]#best-practices
- [Testing and Debugging]#testing-and-debugging
- [Performance Optimization]#performance-optimization
- [Security Considerations]#security-considerations
- [Examples]#examples

## Introduction

rs3gw's WASM plugin system allows you to extend object transformations without modifying the core codebase. Plugins are:

- **Sandboxed**: Execute in an isolated WebAssembly environment
- **Safe**: Rust's safety guarantees prevent memory corruption
- **Portable**: Write once, run anywhere (any platform that runs rs3gw)
- **Fast**: Near-native performance via JIT compilation
- **Extensible**: Add custom transformations for domain-specific needs

### Use Cases

- **Data Processing**: Custom encryption, compression, or format conversion
- **Image/Video Filters**: Domain-specific image transformations
- **Text Processing**: Natural language processing, tokenization
- **Data Validation**: Custom validation rules for uploaded objects
- **Format Conversion**: Convert between proprietary formats
- **PII Redaction**: Remove sensitive information from documents

## Plugin Contract

All rs3gw WASM plugins must implement the following interface:

### Required Exports

#### 1. Linear Memory

```wasm
(memory (export "memory") ...)
```

WebAssembly linear memory for data transfer. Automatically exported in Rust projects.

#### 2. Memory Allocation

```rust
#[no_mangle]
pub extern "C" fn alloc(size: u32) -> u32
```

**Purpose**: Allocate memory for input data from rs3gw

**Parameters**:
- `size`: Number of bytes to allocate

**Returns**:
- Pointer to allocated memory
- `0` if allocation failed

**Example**:
```rust
#[no_mangle]
pub extern "C" fn alloc(size: u32) -> u32 {
    let layout = Layout::from_size_align(size as usize, 1).unwrap();
    unsafe {
        let ptr = ALLOCATOR.alloc(layout);
        ptr as u32
    }
}
```

#### 3. Transform Function

```rust
#[no_mangle]
pub extern "C" fn transform(ptr: u32, len: u32) -> u64
```

**Purpose**: Main transformation logic

**Parameters**:
- `ptr`: Pointer to input data in linear memory
- `len`: Length of input data in bytes

**Returns**:
- `u64` with packed output pointer and length:
  - High 32 bits: Output data pointer
  - Low 32 bits: Output data length

**Example**:
```rust
#[no_mangle]
pub extern "C" fn transform(ptr: u32, len: u32) -> u64 {
    unsafe {
        let input = slice::from_raw_parts(ptr as *const u8, len as usize);

        // Process input...
        let output_ptr = /* allocate output */;
        let output_len = /* output length */;

        // Pack and return
        ((output_ptr as u64) << 32) | (output_len as u64)
    }
}
```

### Optional Exports

#### Plugin Metadata

```rust
// Version number
#[no_mangle]
pub extern "C" fn plugin_version() -> u32 {
    1
}

// Plugin name (packed ptr:len)
#[no_mangle]
pub extern "C" fn plugin_name() -> u64 {
    const NAME: &[u8] = b"my-plugin";
    let ptr = NAME.as_ptr() as u32;
    let len = NAME.len() as u32;
    ((ptr as u64) << 32) | (len as u64)
}

// Plugin description
#[no_mangle]
pub extern "C" fn plugin_description() -> u64 {
    // Similar to plugin_name
}
```

## Development Setup

### Prerequisites

1. **Rust Toolchain** (1.85+)
   ```bash
   curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
   ```

2. **WASM Target**
   ```bash
   rustup target add wasm32-unknown-unknown
   ```

3. **WASM Tools** (optional but recommended)
   ```bash
   # For optimization
   cargo install wasm-opt

   # For testing
   cargo install wasmtime-cli

   # For inspection
   cargo install twiggy
   ```

### Project Structure

```
my-wasm-plugin/
├── Cargo.toml
├── src/
│   └── lib.rs
├── build.sh
├── test.sh
└── README.md
```

### Cargo.toml Template

```toml
[package]
name = "my-wasm-plugin"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
# Keep dependencies minimal for smaller WASM size

[profile.release]
opt-level = "z"      # Optimize for size
lto = true           # Link-time optimization
strip = true         # Strip symbols
panic = "abort"      # Smaller binary
codegen-units = 1    # Better optimization
```

## Creating Your First Plugin

### Step 1: Initialize Project

```bash
cargo new --lib my-wasm-plugin
cd my-wasm-plugin
```

### Step 2: Configure Cargo.toml

Update `Cargo.toml` with the template above.

### Step 3: Implement Plugin

```rust
// src/lib.rs
use core::slice;
use core::alloc::{GlobalAlloc, Layout};
use core::panic::PanicInfo;

// Simple bump allocator
struct BumpAllocator;
static mut HEAP: [u8; 64 * 1024] = [0; 64 * 1024];
static mut HEAP_POS: usize = 0;

unsafe impl GlobalAlloc for BumpAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let size = layout.size();
        let align = layout.align();
        let pos = (HEAP_POS + align - 1) & !(align - 1);

        if pos + size > HEAP.len() {
            return core::ptr::null_mut();
        }

        HEAP_POS = pos + size;
        HEAP.as_mut_ptr().add(pos)
    }

    unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
}

#[global_allocator]
static ALLOCATOR: BumpAllocator = BumpAllocator;

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

#[no_mangle]
pub extern "C" fn alloc(size: u32) -> u32 {
    let layout = Layout::from_size_align(size as usize, 1).unwrap();
    unsafe {
        let ptr = ALLOCATOR.alloc(layout);
        if ptr.is_null() { 0 } else { ptr as u32 }
    }
}

#[no_mangle]
pub extern "C" fn transform(ptr: u32, len: u32) -> u64 {
    unsafe {
        let input = slice::from_raw_parts(ptr as *const u8, len as usize);
        let output_ptr = alloc(len);
        if output_ptr == 0 { return 0; }

        let output = slice::from_raw_parts_mut(output_ptr as *mut u8, len as usize);

        // Your transformation logic here
        output.copy_from_slice(input);

        ((output_ptr as u64) << 32) | (len as u64)
    }
}
```

### Step 4: Build

```bash
cargo build --target wasm32-unknown-unknown --release
```

The output will be at:
`target/wasm32-unknown-unknown/release/my_wasm_plugin.wasm`

### Step 5: Test with rs3gw

```rust
// Register plugin
let wasm_binary = std::fs::read("my_wasm_plugin.wasm")?;
let transformer = WasmPluginTransformer::new();
transformer.register_plugin("my-plugin".to_string(), wasm_binary).await?;

// Use plugin
let result = transformer.transform(
    b"input data",
    &TransformationType::WasmPlugin {
        plugin_name: "my-plugin".to_string(),
        params: HashMap::new(),
    }
).await?;
```

## Advanced Topics

### Custom Allocators

For production plugins, consider using specialized allocators:

#### wee_alloc (Size-optimized)

```toml
[dependencies]
wee_alloc = "0.4"
```

```rust
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
```

#### dlmalloc (Performance-optimized)

```toml
[dependencies]
dlmalloc = "0.2"
```

```rust
#[global_allocator]
static ALLOC: dlmalloc::GlobalDlmalloc = dlmalloc::GlobalDlmalloc;
```

### Parameter Passing

Parameters can be passed via the `params` HashMap and encoded in input data:

```rust
// Example: JSON header with parameters
#[no_mangle]
pub extern "C" fn transform(ptr: u32, len: u32) -> u64 {
    unsafe {
        let input = slice::from_raw_parts(ptr as *const u8, len as usize);

        // Parse JSON header (simplified)
        // Format: 4-byte length + JSON params + data
        let param_len = u32::from_le_bytes([input[0], input[1], input[2], input[3]]);
        let params_bytes = &input[4..4 + param_len as usize];
        let data = &input[4 + param_len as usize..];

        // Process based on parameters...
    }
}
```

### Error Handling

Return error codes or use special sentinel values:

```rust
#[no_mangle]
pub extern "C" fn transform(ptr: u32, len: u32) -> u64 {
    // Return 0 on error
    if ptr == 0 || len == 0 {
        return 0;
    }

    // ... transformation logic ...

    // Return packed result
    result
}
```

### WASI Support

For file I/O and system interactions:

```toml
[dependencies]
wasi = "0.11"
```

```rust
use wasi::*;

#[no_mangle]
pub extern "C" fn transform(ptr: u32, len: u32) -> u64 {
    // Can now use file I/O
    // Note: rs3gw must enable WASI in wasmtime configuration
}
```

## Best Practices

### 1. Memory Management

- **Keep heap size reasonable**: 64KB for simple plugins, up to 1MB for complex ones
- **Avoid allocations in hot paths**: Reuse buffers when possible
- **Clean up resources**: Even with bump allocator, be mindful of memory
- **Check allocation failures**: Always handle null pointers

### 2. Performance

- **Minimize copies**: Transform data in-place when possible
- **Use SIMD**: Leverage WASM SIMD instructions for parallel operations
- **Optimize build settings**: Use `opt-level = "z"` and LTO
- **Profile your code**: Use `twiggy` to analyze binary size

### 3. Security

- **Validate inputs**: Check bounds and data integrity
- **Avoid panics**: Use Result types and proper error handling
- **Limit resource usage**: Set reasonable heap limits
- **No unsafe network access**: WASM sandbox prevents this by default

### 4. Portability

- **No platform-specific code**: Keep code cross-platform
- **Document dependencies**: List any required WASI capabilities
- **Version your plugins**: Use `plugin_version()` for compatibility

## Testing and Debugging

### Unit Testing

```rust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_transform() {
        // Initialize allocator
        unsafe { HEAP_POS = 0; }

        let input = b"test";
        let ptr = alloc(input.len() as u32);
        unsafe {
            let slice = slice::from_raw_parts_mut(ptr as *mut u8, input.len());
            slice.copy_from_slice(input);
        }

        let result = transform(ptr, input.len() as u32);
        assert_ne!(result, 0);
    }
}
```

### Integration Testing with wasmtime

```bash
# Run with wasmtime
wasmtime run --invoke transform my_plugin.wasm 0 10
```

### Debugging

```rust
// Add debug prints (requires WASI)
#[no_mangle]
pub extern "C" fn debug_log(ptr: u32, len: u32) {
    unsafe {
        let msg = slice::from_raw_parts(ptr as *const u8, len as usize);
        eprintln!("DEBUG: {}", String::from_utf8_lossy(msg));
    }
}
```

## Performance Optimization

### Build Optimization

```bash
# Standard release build
cargo build --target wasm32-unknown-unknown --release

# With wasm-opt
wasm-opt -Oz input.wasm -o output.wasm

# With binaryen
wasm-opt -O4 input.wasm -o output.wasm
```

### Runtime Optimization

1. **Ahead-of-Time Compilation**: Pre-compile WASM modules
2. **Module Caching**: Cache compiled modules between requests
3. **Memory Reuse**: Reuse WASM instances when possible

### Profiling

```bash
# Analyze binary size
twiggy top my_plugin.wasm

# Find code bloat
twiggy garbage my_plugin.wasm

# Inspect functions
twiggy paths my_plugin.wasm transform
```

## Security Considerations

### Sandboxing

WASM provides strong isolation:
- No access to host file system (without WASI)
- No network access (without explicit permissions)
- Memory limited to allocated linear memory
- No access to other processes

### Resource Limits

rs3gw enforces limits on WASM execution:
- Maximum memory allocation
- Maximum execution time
- Stack size limits

### Input Validation

Always validate plugin inputs:

```rust
#[no_mangle]
pub extern "C" fn transform(ptr: u32, len: u32) -> u64 {
    // Check for valid pointer and length
    if ptr == 0 || len == 0 || len > MAX_INPUT_SIZE {
        return 0;
    }

    // Validate data format
    unsafe {
        let input = slice::from_raw_parts(ptr as *const u8, len as usize);
        if !is_valid_input(input) {
            return 0;
        }

        // ... safe to process ...
    }
}
```

## Examples

### 1. Base64 Encoder

```rust
#[no_mangle]
pub extern "C" fn transform(ptr: u32, len: u32) -> u64 {
    unsafe {
        let input = slice::from_raw_parts(ptr as *const u8, len as usize);
        let output_len = ((len + 2) / 3) * 4;
        let output_ptr = alloc(output_len);

        if output_ptr == 0 { return 0; }

        let output = slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize);
        base64_encode(input, output);

        ((output_ptr as u64) << 32) | (output_len as u64)
    }
}
```

### 2. JSON Prettifier

```rust
#[no_mangle]
pub extern "C" fn transform(ptr: u32, len: u32) -> u64 {
    unsafe {
        let input = slice::from_raw_parts(ptr as *const u8, len as usize);

        // Parse and prettify JSON
        let formatted = match prettify_json(input) {
            Some(data) => data,
            None => return 0,
        };

        let output_ptr = alloc(formatted.len() as u32);
        if output_ptr == 0 { return 0; }

        let output = slice::from_raw_parts_mut(output_ptr as *mut u8, formatted.len());
        output.copy_from_slice(&formatted);

        ((output_ptr as u64) << 32) | (formatted.len() as u64)
    }
}
```

### 3. Image Watermark

```rust
// Note: This is a conceptual example
// In practice, use image processing libraries compatible with WASM

#[no_mangle]
pub extern "C" fn transform(ptr: u32, len: u32) -> u64 {
    unsafe {
        let input = slice::from_raw_parts(ptr as *const u8, len as usize);

        // Load image, add watermark, encode back
        let watermarked = add_watermark(input, "© Company 2025");

        let output_ptr = alloc(watermarked.len() as u32);
        if output_ptr == 0 { return 0; }

        let output = slice::from_raw_parts_mut(output_ptr as *mut u8, watermarked.len());
        output.copy_from_slice(&watermarked);

        ((output_ptr as u64) << 32) | (watermarked.len() as u64)
    }
}
```

## Troubleshooting

### Common Issues

**Problem**: "Memory access out of bounds"
- **Solution**: Check heap size, ensure allocations fit in linear memory

**Problem**: Plugin returns 0
- **Solution**: Add error logging, check allocation failures

**Problem**: Slow performance
- **Solution**: Profile with twiggy, optimize hot paths, reduce allocations

**Problem**: Large binary size
- **Solution**: Use `opt-level = "z"`, wasm-opt, minimize dependencies

## Resources

- [WebAssembly Specification]https://webassembly.github.io/spec/
- [Rust and WebAssembly Book]https://rustwasm.github.io/docs/book/
- [wasmtime Documentation]https://docs.wasmtime.dev/
- [WASI Documentation]https://wasi.dev/
- [rs3gw GitHub Repository]https://github.com/cool-japan/rs3gw

## Support

For questions and issues:
- GitHub Issues: https://github.com/cool-japan/rs3gw/issues
- Documentation: https://github.com/cool-japan/rs3gw/docs
- Examples: https://github.com/cool-japan/rs3gw/examples