@sinkaroid/rust-shapeshift 0.0.0-stage → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +145 -2
- package/bin/rust-shapeshift.js +29 -0
- package/package.json +45 -4
- package/skills/rust-shapeshift/SKILL.md +282 -0
- package/skills/rust-shapeshift/resources/adaptive_concurrency_and_load_shedding.md +122 -0
- package/skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md +139 -0
- package/skills/rust-shapeshift/resources/arena_allocation_and_bump_memory.md +83 -0
- package/skills/rust-shapeshift/resources/async_cancellation_safety_and_task_drainage.md +158 -0
- package/skills/rust-shapeshift/resources/axum_and_tower_architecture.md +145 -0
- package/skills/rust-shapeshift/resources/bounded_caching_and_pooling.md +105 -0
- package/skills/rust-shapeshift/resources/bounded_streaming_and_payload_guards.md +147 -0
- package/skills/rust-shapeshift/resources/bounds_check_elimination_and_zero_cost_memory.md +122 -0
- package/skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md +121 -0
- package/skills/rust-shapeshift/resources/compiler_niche_optimizations_and_size_assertions.md +126 -0
- package/skills/rust-shapeshift/resources/concurrency_model_checking_and_resource_budgets.md +170 -0
- package/skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md +158 -0
- package/skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md +115 -0
- package/skills/rust-shapeshift/resources/dom_and_scraper_pruning.md +157 -0
- package/skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md +143 -0
- package/skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md +192 -0
- package/skills/rust-shapeshift/resources/grpc_tonic_and_http2_memory_tuning.md +117 -0
- package/skills/rust-shapeshift/resources/hidden_drop_offload_and_wcet_contracts.md +255 -0
- package/skills/rust-shapeshift/resources/hot_path_string_and_zero_cost_helpers.md +113 -0
- package/skills/rust-shapeshift/resources/instruction_cache_and_cold_path_outlining.md +135 -0
- package/skills/rust-shapeshift/resources/io_uring_and_zero_syscall_networking.md +146 -0
- package/skills/rust-shapeshift/resources/jemalloc_profiling_and_allocator_switch.md +145 -0
- package/skills/rust-shapeshift/resources/kubernetes_runtime_and_resource_containment.md +207 -0
- package/skills/rust-shapeshift/resources/memory_allocator_tuning.md +125 -0
- package/skills/rust-shapeshift/resources/message_queue_and_stream_backpressure.md +125 -0
- package/skills/rust-shapeshift/resources/numa_architecture_and_hugepages.md +169 -0
- package/skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md +253 -0
- package/skills/rust-shapeshift/resources/profile_guided_optimization_and_fast_hashing.md +94 -0
- package/skills/rust-shapeshift/resources/rate_limiting_and_state.md +140 -0
- package/skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md +251 -0
- package/skills/rust-shapeshift/resources/redis_connection_and_caching_pitfalls.md +230 -0
- package/skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.md +130 -0
- package/skills/rust-shapeshift/resources/simd_vectorization_and_hardware_acceleration.md +108 -0
- package/skills/rust-shapeshift/resources/sqlx_and_database_pool_memory.md +156 -0
- package/skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md +134 -0
- package/skills/rust-shapeshift/resources/streaming_file_io_and_compression.md +97 -0
- package/skills/rust-shapeshift/resources/telemetry_and_metrics.md +170 -0
- package/skills/rust-shapeshift/resources/thread_per_core_and_shared_nothing.md +149 -0
- package/skills/rust-shapeshift/resources/tokio_thread_starvation_and_cpu_offload.md +124 -0
- package/skills/rust-shapeshift/resources/typestate_domain_proofs_and_buffer_recycling.md +254 -0
- package/skills/rust-shapeshift/resources/wasm_runtime_and_memory_sandboxing.md +114 -0
- package/skills/rust-shapeshift/resources/zero_allocation_error_architecture.md +130 -0
- package/skills/rust-shapeshift/resources/zero_copy_ipc_and_shared_memory.md +99 -0
- package/skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md +159 -0
- package/skills/rust-shapeshift/resources/zero_overhead_distributed_tracing.md +109 -0
- package/skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md +104 -0
- package/skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md +156 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
# Thread-Per-Core & Shared-Nothing Architecture
|
|
2
|
+
|
|
3
|
+
## The Problem: The Hidden Tax of Work-Stealing Schedulers
|
|
4
|
+
|
|
5
|
+
Multi-threaded async runtimes (such as standard multi-threaded Tokio) default to a **work-stealing algorithm**. While convenient for general-purpose workloads, work-stealing creates severe hardware bottlenecks under high throughput:
|
|
6
|
+
|
|
7
|
+
1. **L1/L2 Cache Invalidation & Thrashing**: When Core 1 runs out of work and steals a future from Core 2's deque, the task's working data is pulled across the CPU interconnect bus. The cache lines in Core 2's L1/L2 cache are invalidated via hardware coherence protocols (MESI/MOESI), destroying cache locality.
|
|
8
|
+
2. **Atomic Contention on Task Queues**: Work-stealing deques require atomic compare-and-swap operations on head and tail pointers. Under heavy thread counts (32–128 cores), cache-line bouncing on shared run queues degrades instruction execution pipelines.
|
|
9
|
+
3. **Cross-Thread Synchronization Overhead**: Sharing state across worker threads forces the use of cross-thread locks (`parking_lot::Mutex`, `tokio::sync::Mutex`) or multi-producer queues, introducing lock contention and tail latency jitter.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 1. The Thread-Per-Core (Shared-Nothing) Philosophy
|
|
14
|
+
|
|
15
|
+
Inspired by high-performance systems like ScyllaDB, Seastar, Datadog Vector, and high-frequency trading engines, the **Thread-Per-Core (Shared-Nothing)** architecture eliminates cross-core interference entirely:
|
|
16
|
+
|
|
17
|
+
```text
|
|
18
|
+
┌───────────────── CPU Core 0 ─────────────────┐ ┌───────────────── CPU Core 1 ─────────────────┐
|
|
19
|
+
│ [OS Thread Pinned to Core 0] │ │ [OS Thread Pinned to Core 1] │
|
|
20
|
+
│ ├── Local Single-Thread Executor (Current) │ │ ├── Local Single-Thread Executor (Current) │
|
|
21
|
+
│ ├── Local Memory Arena / Object Pool │ │ ├── Local Memory Arena / Object Pool │
|
|
22
|
+
│ └── Local Socket File Descriptors (REUSEPORT)│ │ └── Local Socket File Descriptors (REUSEPORT)│
|
|
23
|
+
└──────────────────────┬────────────────────────┘ └──────────────────────▲────────────────────────┘
|
|
24
|
+
│ │
|
|
25
|
+
└─────────── Lock-Free SPSC Ring Buffer ───────────┘
|
|
26
|
+
(Inter-Core Message Handoff)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### Core Tenets:
|
|
30
|
+
1. **1 Hardware Core = 1 OS Thread = 1 Local Executor**.
|
|
31
|
+
2. **Zero Cross-Core Sharing**: Every core manages its own connections, memory arenas, caches, and timers.
|
|
32
|
+
3. **Zero Mutexes on Hot Path**: Because memory is owned exclusively by the pinned thread, state mutation uses standard `RefCell` or raw borrowing—**zero atomic synchronization overhead**.
|
|
33
|
+
4. **Inter-Core Communication via SPSC Rings**: If Core 0 must message Core 1, it deposits an event into a single-producer single-consumer lock-free queue.
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## 2. Pinned OS Threads & CPU Affinity in Rust
|
|
38
|
+
|
|
39
|
+
Bind worker threads strictly to physical CPU cores to prevent the Linux kernel scheduler from migrating threads across cores:
|
|
40
|
+
|
|
41
|
+
```rust
|
|
42
|
+
use std::thread;
|
|
43
|
+
|
|
44
|
+
pub fn spawn_pinned_worker<F>(core_id: usize, work: F) -> thread::JoinHandle<()>
|
|
45
|
+
where
|
|
46
|
+
F: FnOnce() + Send + 'static,
|
|
47
|
+
{
|
|
48
|
+
thread::Builder::new()
|
|
49
|
+
.name(format!("worker-core-{}", core_id))
|
|
50
|
+
.spawn(move || {
|
|
51
|
+
// Pin the current OS thread to the designated physical core
|
|
52
|
+
let core_ids = core_affinity::get_core_ids().expect("failed to get core IDs");
|
|
53
|
+
if let Some(core) = core_ids.get(core_id) {
|
|
54
|
+
core_affinity::set_for_current(*core);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
work();
|
|
58
|
+
})
|
|
59
|
+
.expect("failed to spawn worker thread")
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## 3. Kernel SO_REUSEPORT Network Partitioning
|
|
66
|
+
|
|
67
|
+
Instead of accepting TCP connections on a single central listener and delegating sockets across threads, each pinned core opens its own independent `TcpListener` bound to the same port using `SO_REUSEPORT`.
|
|
68
|
+
|
|
69
|
+
The Linux kernel's network stack distributes inbound SYN packets directly across listeners using a 4-tuple hash:
|
|
70
|
+
|
|
71
|
+
```rust
|
|
72
|
+
use socket2::{Domain, Protocol, Socket, Type};
|
|
73
|
+
use std::net::SocketAddr;
|
|
74
|
+
|
|
75
|
+
pub fn create_reuseport_listener(addr: SocketAddr) -> std::io::Result<std::net::TcpListener> {
|
|
76
|
+
let domain = if addr.is_ipv6() { Domain::IPV6 } else { Domain::IPV4 };
|
|
77
|
+
let socket = Socket::new(domain, Type::STREAM, Some(Protocol::TCP))?;
|
|
78
|
+
|
|
79
|
+
// Enable SO_REUSEPORT: kernel distributes incoming connections evenly
|
|
80
|
+
socket.set_reuse_port(true)?;
|
|
81
|
+
socket.set_reuse_address(true)?;
|
|
82
|
+
socket.set_nonblocking(true)?;
|
|
83
|
+
|
|
84
|
+
socket.bind(&addr.into())?;
|
|
85
|
+
socket.listen(1024)?;
|
|
86
|
+
|
|
87
|
+
Ok(socket.into())
|
|
88
|
+
}
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
---
|
|
92
|
+
|
|
93
|
+
## 4. Single-Threaded Tokio Current-Thread Isolation
|
|
94
|
+
|
|
95
|
+
Run an independent Tokio `current_thread` runtime on each pinned core:
|
|
96
|
+
|
|
97
|
+
```rust
|
|
98
|
+
pub fn run_thread_per_core_cluster(addr: SocketAddr, num_cores: usize) {
|
|
99
|
+
let mut handles = Vec::new();
|
|
100
|
+
|
|
101
|
+
for core_id in 0..num_cores {
|
|
102
|
+
let handle = spawn_pinned_worker(core_id, move || {
|
|
103
|
+
// Local current_thread runtime: NO WORK-STEALING!
|
|
104
|
+
let rt = tokio::runtime::Builder::new_current_thread()
|
|
105
|
+
.enable_all()
|
|
106
|
+
.build()
|
|
107
|
+
.expect("failed to build local runtime");
|
|
108
|
+
|
|
109
|
+
rt.block_on(async move {
|
|
110
|
+
let listener = create_reuseport_listener(addr).expect("failed to bind reuseport");
|
|
111
|
+
let listener = tokio::net::TcpListener::from_std(listener).expect("convert listener");
|
|
112
|
+
|
|
113
|
+
loop {
|
|
114
|
+
let (socket, _) = match listener.accept().await {
|
|
115
|
+
Ok(conn) => conn,
|
|
116
|
+
Err(_) => continue,
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
// Spawns locally on this core ONLY: 100% L1/L2 cache locality
|
|
120
|
+
tokio::task::spawn_local(async move {
|
|
121
|
+
handle_connection_locally(socket).await;
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
handles.push(handle);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
for h in handles {
|
|
131
|
+
let _ = h.join();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async fn handle_connection_locally(mut socket: tokio::net::TcpStream) {
|
|
136
|
+
// Zero atomic overhead: local state mutation without cross-thread locks
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
## 5. Performance Comparison
|
|
143
|
+
|
|
144
|
+
| Metric | Work-Stealing Runtime | Thread-Per-Core (Shared-Nothing) |
|
|
145
|
+
| :--- | :--- | :--- |
|
|
146
|
+
| **L1/L2 Cache Hit Rate** | ~75%–85% under high load | **>98%** (zero cross-core task migration) |
|
|
147
|
+
| **Tail Latency (p99.99)** | Millisecond-level jitter spikes | **Deterministic microsecond range** |
|
|
148
|
+
| **Core Scalability** | Diminishing returns past 32 cores | **Linear scaling up to 128+ cores** |
|
|
149
|
+
| **Memory Allocation** | Global allocator lock contention | Core-local arenas (zero lock contention) |
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# Tokio Thread Starvation & CPU Workload Offloading
|
|
2
|
+
|
|
3
|
+
Tokio is a **cooperative asynchronous runtime**, not a preemptive one. Unlike runtimes with preemptive schedulers that can interrupt long-running tasks, a Tokio worker thread executes an asynchronous task continuously until that task voluntarily yields control at an `.await` boundary.
|
|
4
|
+
|
|
5
|
+
If a worker thread runs heavy, synchronous CPU-bound logic (DOM parsing, large regex scans, decompression, or cryptography), that thread is **blocked**. The I/O reactor on that thread cannot process incoming TCP sockets, leading to severe latency spikes, socket timeouts, and degraded p99 metrics.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. The Cooperative Scheduling Trap
|
|
10
|
+
|
|
11
|
+
Tokio defaults to creating worker threads equal to the number of logical CPU cores (`num_cpus`):
|
|
12
|
+
|
|
13
|
+
```text
|
|
14
|
+
Incoming HTTP Request ---> [ Tokio Worker 1 ] (Runs synchronous CPU work for 25ms)
|
|
15
|
+
Incoming Health Check ---> [ Tokio Worker 1 ] (STARVED! Waits 25ms behind CPU work)
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
If 4 concurrent requests trigger synchronous parsing on a 4-core server, **100% of Tokio worker threads are blocked**. All other connections, including Kubernetes liveness probes (`/healthz`) and Prometheus scrapers (`/metrics`), stall.
|
|
19
|
+
|
|
20
|
+
### Rule of Thumb
|
|
21
|
+
Any synchronous CPU operation expected to take **more than 100 µs to 1 ms** MUST NOT run directly on a Tokio worker thread.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## 2. Offloading with `tokio::task::spawn_blocking`
|
|
26
|
+
|
|
27
|
+
For synchronous operations that take a few milliseconds (e.g., parsing a pruned HTML document or decoding a large payload), offload execution to Tokio's dedicated blocking threadpool:
|
|
28
|
+
|
|
29
|
+
```rust
|
|
30
|
+
use axum::{extract::State, response::IntoResponse, Json};
|
|
31
|
+
use std::sync::Arc;
|
|
32
|
+
|
|
33
|
+
pub async fn parse_document_handler(
|
|
34
|
+
State(state): State<Arc<AppState>>,
|
|
35
|
+
raw_body: String,
|
|
36
|
+
) -> Result<impl IntoResponse, AppError> {
|
|
37
|
+
// Prune the raw string on the async thread (nanosecond slice)
|
|
38
|
+
let pruned = crate::pruning::slice_html(&raw_body);
|
|
39
|
+
let pruned_owned = pruned.to_string();
|
|
40
|
+
|
|
41
|
+
// 🚀 OFFLOAD CPU-BOUND PARSING TO BLOCKING POOL
|
|
42
|
+
let parsed_items = tokio::task::spawn_blocking(move || {
|
|
43
|
+
crate::parser::extract_cards(&pruned_owned)
|
|
44
|
+
})
|
|
45
|
+
.await
|
|
46
|
+
.map_err(|join_err| AppError::Internal(format!("Blocking task panicked: {join_err}")))?;
|
|
47
|
+
|
|
48
|
+
Ok(Json(parsed_items))
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Why this protects throughput:
|
|
53
|
+
- Tokio's blocking threadpool dynamically spins up to 512 threads dedicated purely to synchronous blocking tasks.
|
|
54
|
+
- Tokio worker threads remain **100% responsive** to I/O events, TCP handshakes, and immediate async handlers.
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## 3. High-Throughput Parallelism with `rayon`
|
|
59
|
+
|
|
60
|
+
When a single request requires intensive CPU processing across multiple chunks (e.g., parsing 50 large provider manifests or running parallel batch transformations), `rayon` provides work-stealing parallelism:
|
|
61
|
+
|
|
62
|
+
```toml
|
|
63
|
+
# Cargo.toml
|
|
64
|
+
[dependencies]
|
|
65
|
+
rayon = "1.10"
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
```rust
|
|
69
|
+
use rayon::prelude::*;
|
|
70
|
+
|
|
71
|
+
pub async fn batch_process_items(raw_chunks: Vec<String>) -> Vec<ProcessedCard> {
|
|
72
|
+
tokio::task::spawn_blocking(move || {
|
|
73
|
+
raw_chunks
|
|
74
|
+
.par_iter()
|
|
75
|
+
.map(|chunk| crate::parser::parse_single_chunk(chunk))
|
|
76
|
+
.collect()
|
|
77
|
+
})
|
|
78
|
+
.await
|
|
79
|
+
.unwrap_or_default()
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
> **Warning**: Never call Tokio's async `.await` inside a `rayon` parallel iterator. Rayon is strictly for synchronous CPU computations.
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
## 4. Measuring Event Loop Health
|
|
88
|
+
|
|
89
|
+
To verify that worker threads are never starved, continuously measure Tokio event loop lag:
|
|
90
|
+
|
|
91
|
+
```rust
|
|
92
|
+
use std::time::{Duration, Instant};
|
|
93
|
+
|
|
94
|
+
pub fn spawn_event_loop_monitor() {
|
|
95
|
+
tokio::spawn(async move {
|
|
96
|
+
let mut interval = tokio::time::interval(Duration::from_millis(500));
|
|
97
|
+
loop {
|
|
98
|
+
let start = Instant::now();
|
|
99
|
+
interval.tick().await;
|
|
100
|
+
let elapsed = start.elapsed();
|
|
101
|
+
|
|
102
|
+
// If the 500ms timer takes >510ms, worker threads are experiencing lag
|
|
103
|
+
let lag = elapsed.saturating_sub(Duration::from_millis(500));
|
|
104
|
+
if lag > Duration::from_millis(10) {
|
|
105
|
+
tracing::warn!(
|
|
106
|
+
lag_ms = lag.as_millis(),
|
|
107
|
+
"Tokio worker thread starvation detected!"
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## 5. Summary Checklist
|
|
118
|
+
|
|
119
|
+
| Task Type | Execution Strategy | Target Threadpool |
|
|
120
|
+
|---|---|---|
|
|
121
|
+
| Network I/O (`reqwest`, `redis`, TCP) | `.await` | Tokio Worker Pool |
|
|
122
|
+
| Fast string slicing ($\le 100$ µs) | Direct inline execution | Tokio Worker Pool |
|
|
123
|
+
| Medium DOM / JSON parsing (1ms–15ms) | `tokio::task::spawn_blocking` | Tokio Blocking Pool |
|
|
124
|
+
| Massive batch CPU calculations | `rayon` inside `spawn_blocking` | Rayon Work-Stealing Pool |
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
# Zero-Cost Typestates, Compile-Time Domain Proofs & Buffer Recycling
|
|
2
|
+
|
|
3
|
+
## The Problem: Runtime Defensive Overhead and Heap Churn
|
|
4
|
+
|
|
5
|
+
High-throughput systems written with traditional object-oriented habits suffer from two compounding performance drains:
|
|
6
|
+
|
|
7
|
+
1. **Defensive Runtime Branching**: Repeated checks across internal function boundaries (e.g., verifying if a connection is authenticated, if an ID is valid, or if a payload is within size bounds). Every `if !conn.is_authed()` branch consumes branch predictor slots and adds latency.
|
|
8
|
+
2. **Ephemeral Allocation Churn**: Continuously allocating new strings, buffers, and vectors inside request loops (`format!("key:{}", id)`, `Vec::new()`, `payload.to_owned()`), leading to heap fragmentation and cache invalidations.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. "Parse, Don't Validate" & Zero-Cost Domain Types
|
|
13
|
+
|
|
14
|
+
Validation checks an input, returns a boolean or unit `Ok(())`, and discards the proof. Downstream functions are forced to re-check or trust invariants without compiler guarantees.
|
|
15
|
+
|
|
16
|
+
Parsing inspects the input once and transforms it into a distinct type whose existence proves the invariant holds.
|
|
17
|
+
|
|
18
|
+
### Anti-Pattern: Validating with Plain Strings
|
|
19
|
+
|
|
20
|
+
```rust
|
|
21
|
+
// BAD: Every downstream method must wonder if `email` is valid
|
|
22
|
+
pub fn send_notification(email: &str, message: &str) -> Result<(), AppError> {
|
|
23
|
+
if !email.contains('@') {
|
|
24
|
+
return Err(AppError::InvalidEmail);
|
|
25
|
+
}
|
|
26
|
+
// ...
|
|
27
|
+
Ok(())
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### Production Pattern: Constructive Domain Parsing
|
|
32
|
+
|
|
33
|
+
```rust
|
|
34
|
+
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
|
35
|
+
pub struct ValidatedEmail(String);
|
|
36
|
+
|
|
37
|
+
impl ValidatedEmail {
|
|
38
|
+
pub fn parse(raw: String) -> Result<Self, DomainError> {
|
|
39
|
+
if raw.contains('@') && raw.len() <= 254 {
|
|
40
|
+
Ok(Self(raw))
|
|
41
|
+
} else {
|
|
42
|
+
Err(DomainError::InvalidEmail)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
#[inline(always)]
|
|
47
|
+
pub fn as_str(&self) -> &str {
|
|
48
|
+
&self.0
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Downstream functions accept the proof; ZERO runtime validation branches required
|
|
53
|
+
pub fn send_notification(email: &ValidatedEmail, message: &str) {
|
|
54
|
+
// Guaranteed by the type system at zero runtime cost
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## 2. Affine Typestates: Eliminating Runtime State Flags
|
|
61
|
+
|
|
62
|
+
Instead of maintaining a struct with mutable state flags (`is_connected: bool`, `is_authenticated: bool`) that must be checked on every socket operation, model connection progression as distinct compile-time states using phantom types.
|
|
63
|
+
|
|
64
|
+
State transitions consume `self` by value, making illegal states structurally impossible to represent.
|
|
65
|
+
|
|
66
|
+
### Production Pattern: Compile-Time Connection Pipeline
|
|
67
|
+
|
|
68
|
+
```rust
|
|
69
|
+
use std::marker::PhantomData;
|
|
70
|
+
|
|
71
|
+
// State markers (zero-sized types)
|
|
72
|
+
pub struct Disconnected;
|
|
73
|
+
pub struct Handshaking;
|
|
74
|
+
pub struct Established;
|
|
75
|
+
|
|
76
|
+
pub struct Connection<State> {
|
|
77
|
+
stream: std::net::TcpStream,
|
|
78
|
+
_marker: PhantomData<State>,
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
impl Connection<Disconnected> {
|
|
82
|
+
pub fn new(stream: std::net::TcpStream) -> Self {
|
|
83
|
+
Self {
|
|
84
|
+
stream,
|
|
85
|
+
_marker: PhantomData,
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/// Transition to Handshaking state
|
|
90
|
+
pub fn begin_handshake(mut self) -> Result<Connection<Handshaking>, std::io::Error> {
|
|
91
|
+
// Perform initial protocol exchange
|
|
92
|
+
Ok(Connection {
|
|
93
|
+
stream: self.stream,
|
|
94
|
+
_marker: PhantomData,
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
impl Connection<Handshaking> {
|
|
100
|
+
/// Transition to Established state upon valid auth token
|
|
101
|
+
pub fn authenticate(mut self, token: &[u8]) -> Result<Connection<Established>, ProtocolError> {
|
|
102
|
+
// Verify credentials
|
|
103
|
+
Ok(Connection {
|
|
104
|
+
stream: self.stream,
|
|
105
|
+
_marker: PhantomData,
|
|
106
|
+
})
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
impl Connection<Established> {
|
|
111
|
+
/// ONLY callable when the connection is provably established.
|
|
112
|
+
/// Eliminates all `if !is_authed` checks!
|
|
113
|
+
pub fn send_data(&mut self, payload: &[u8]) -> Result<(), std::io::Error> {
|
|
114
|
+
use std::io::Write;
|
|
115
|
+
self.stream.write_all(payload)
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
---
|
|
121
|
+
|
|
122
|
+
## 3. Exhaustive Matching on Domain Enums
|
|
123
|
+
|
|
124
|
+
Never use wildcard arms (`_ =>`) when matching domain enums under your application's control. Wildcards hide unhandled variants when new protocol features are added.
|
|
125
|
+
|
|
126
|
+
```rust
|
|
127
|
+
pub enum ProtocolOp {
|
|
128
|
+
Ping,
|
|
129
|
+
Subscribe { channel_id: u64 },
|
|
130
|
+
Publish { channel_id: u64, payload_len: u32 },
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// BAD: Wildcard quietly ignores unhandled operations
|
|
134
|
+
// match op {
|
|
135
|
+
// ProtocolOp::Ping => handle_ping(),
|
|
136
|
+
// _ => handle_other(),
|
|
137
|
+
// }
|
|
138
|
+
|
|
139
|
+
// GOOD: Exhaustive match enforces complete handling at compile time
|
|
140
|
+
pub fn dispatch_op(op: ProtocolOp) {
|
|
141
|
+
match op {
|
|
142
|
+
ProtocolOp::Ping => handle_ping(),
|
|
143
|
+
ProtocolOp::Subscribe { channel_id } => handle_subscribe(channel_id),
|
|
144
|
+
ProtocolOp::Publish { channel_id, payload_len } => handle_publish(channel_id, payload_len),
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
## 4. Buffer Recycling & Allocation Reuse
|
|
152
|
+
|
|
153
|
+
### `clone_from` for Reusing Existing Capacities
|
|
154
|
+
|
|
155
|
+
When a persistent worker must replace its state with newly received data, calling `.clone()` or `.to_owned()` releases the existing allocation and asks the heap allocator for a new buffer.
|
|
156
|
+
|
|
157
|
+
Using `clone_from` reuses the existing capacity in-place without allocator syscalls:
|
|
158
|
+
|
|
159
|
+
```rust
|
|
160
|
+
pub struct WorkerBuffer {
|
|
161
|
+
pub scratch: String,
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
impl WorkerBuffer {
|
|
165
|
+
pub fn update(&mut self, incoming: &str) {
|
|
166
|
+
// Reuses the internal capacity of `self.scratch` if it fits!
|
|
167
|
+
self.scratch.clone_from(&incoming.to_string());
|
|
168
|
+
|
|
169
|
+
// Even better: clear and push without intermediate allocation
|
|
170
|
+
self.scratch.clear();
|
|
171
|
+
self.scratch.push_str(incoming);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### In-Place String Formatting via `write!`
|
|
177
|
+
|
|
178
|
+
Avoid `format!` on the hot path. Use `std::fmt::Write` directly on a reusable buffer:
|
|
179
|
+
|
|
180
|
+
```rust
|
|
181
|
+
use std::fmt::Write;
|
|
182
|
+
|
|
183
|
+
pub fn build_cache_key(buffer: &mut String, prefix: &str, user_id: u64, tenant_id: u32) {
|
|
184
|
+
buffer.clear(); // Keep preallocated capacity
|
|
185
|
+
// Zero heap allocation! Writes directly into existing memory.
|
|
186
|
+
let _ = write!(buffer, "{}:{}:{}", prefix, tenant_id, user_id);
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
---
|
|
191
|
+
|
|
192
|
+
## 5. Ring Buffer Slab Pooling for Network Frames
|
|
193
|
+
|
|
194
|
+
In high-concurrency packet and framing loops, avoid allocating a `Vec<u8>` per frame. Preallocate a bounded object pool using a lock-free queue (`crossbeam::queue::ArrayQueue`):
|
|
195
|
+
|
|
196
|
+
```rust
|
|
197
|
+
use crossbeam::queue::ArrayQueue;
|
|
198
|
+
use std::sync::Arc;
|
|
199
|
+
|
|
200
|
+
pub struct BufferPool {
|
|
201
|
+
pool: Arc<ArrayQueue<Vec<u8>>>,
|
|
202
|
+
buffer_capacity: usize,
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
impl BufferPool {
|
|
206
|
+
pub fn new(pool_size: usize, buffer_capacity: usize) -> Self {
|
|
207
|
+
let queue = ArrayQueue::new(pool_size);
|
|
208
|
+
for _ in 0..pool_size {
|
|
209
|
+
let _ = queue.push(Vec::with_capacity(buffer_capacity));
|
|
210
|
+
}
|
|
211
|
+
Self {
|
|
212
|
+
pool: Arc::new(queue),
|
|
213
|
+
buffer_capacity,
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
pub fn acquire(&self) -> PooledBuffer {
|
|
218
|
+
let buf = self.pool.pop().unwrap_or_else(|| Vec::with_capacity(self.buffer_capacity));
|
|
219
|
+
PooledBuffer {
|
|
220
|
+
buffer: Some(buf),
|
|
221
|
+
pool: self.pool.clone(),
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
pub struct PooledBuffer {
|
|
227
|
+
buffer: Option<Vec<u8>>,
|
|
228
|
+
pool: Arc<ArrayQueue<Vec<u8>>>,
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
impl std::ops::Deref for PooledBuffer {
|
|
232
|
+
type Target = Vec<u8>;
|
|
233
|
+
fn deref(&self) -> &Self::Target {
|
|
234
|
+
self.buffer.as_ref().unwrap()
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
impl std::ops::DerefMut for PooledBuffer {
|
|
239
|
+
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
240
|
+
self.buffer.as_mut().unwrap()
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
impl Drop for PooledBuffer {
|
|
245
|
+
fn drop(&mut self) {
|
|
246
|
+
if let Some(mut buf) = self.buffer.take() {
|
|
247
|
+
buf.clear(); // Retain capacity for next borrower
|
|
248
|
+
let _ = self.pool.push(buf);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
With `PooledBuffer`, frames borrow preallocated buffers and return them to the lock-free pool on drop without involving the OS heap allocator.
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# WebAssembly Runtime and Memory Sandboxing
|
|
2
|
+
|
|
3
|
+
Embedding WebAssembly (Wasm) engines (`wasmtime`) enables safe, multi-tenant user extensibility and plugin systems. However, untrusted guest Wasm modules can allocate linear memory unboundedly until host RAM is exhausted, or enter infinite CPU loops that starve Tokio worker threads.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Hard Linear Memory Ceilings with `ResourceLimiter`
|
|
8
|
+
|
|
9
|
+
Prevent guest modules from growing their linear memory beyond a strict memory budget (e.g., max 16MB) by implementing `wasmtime::ResourceLimiter`:
|
|
10
|
+
|
|
11
|
+
```rust
|
|
12
|
+
use wasmtime::*;
|
|
13
|
+
|
|
14
|
+
pub struct PluginState {
|
|
15
|
+
pub max_memory_bytes: usize,
|
|
16
|
+
pub current_memory_bytes: usize,
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
impl ResourceLimiter for PluginState {
|
|
20
|
+
fn memory_growing(
|
|
21
|
+
&mut self,
|
|
22
|
+
current: usize,
|
|
23
|
+
desired: usize,
|
|
24
|
+
_maximum: Option<usize>,
|
|
25
|
+
) -> Result<bool, wasmtime::Error> {
|
|
26
|
+
if desired > self.max_memory_bytes {
|
|
27
|
+
// Rejects linear memory allocation: protects host from OOM
|
|
28
|
+
Ok(false)
|
|
29
|
+
} else {
|
|
30
|
+
self.current_memory_bytes = desired;
|
|
31
|
+
Ok(true)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
fn table_growing(
|
|
36
|
+
&mut self,
|
|
37
|
+
_current: usize,
|
|
38
|
+
desired: usize,
|
|
39
|
+
_maximum: Option<usize>,
|
|
40
|
+
) -> Result<bool, wasmtime::Error> {
|
|
41
|
+
Ok(desired <= 10_000) // Bound table elements to 10k
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## 2. Epoch-Based CPU Interruption and Fuel Metering
|
|
49
|
+
|
|
50
|
+
Infinite loops in guest Wasm code block the host thread. Use epoch interruption or fuel metering to terminate rogue execution:
|
|
51
|
+
|
|
52
|
+
```rust
|
|
53
|
+
use wasmtime::*;
|
|
54
|
+
use std::time::Duration;
|
|
55
|
+
|
|
56
|
+
pub fn configure_safe_wasm_engine() -> Result<Engine, wasmtime::Error> {
|
|
57
|
+
let mut config = Config::new();
|
|
58
|
+
|
|
59
|
+
// Enable epoch interruption to interrupt infinite guest loops
|
|
60
|
+
config.epoch_interruption(true);
|
|
61
|
+
|
|
62
|
+
// Disable multi-memory to contain memory footprint
|
|
63
|
+
config.wasm_multi_memory(false);
|
|
64
|
+
|
|
65
|
+
Engine::new(&config)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
pub async fn run_plugin_with_timeout<T>(
|
|
69
|
+
engine: &Engine,
|
|
70
|
+
store: &mut Store<T>,
|
|
71
|
+
timeout: Duration,
|
|
72
|
+
) {
|
|
73
|
+
let engine_clone = engine.clone();
|
|
74
|
+
|
|
75
|
+
// Spawn watchdog to increment epoch when timeout expires
|
|
76
|
+
let watchdog = tokio::spawn(async move {
|
|
77
|
+
tokio::time::sleep(timeout).await;
|
|
78
|
+
engine_clone.increment_epoch();
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// Store configured to trap when epoch expires
|
|
82
|
+
store.set_epoch_deadline(1);
|
|
83
|
+
|
|
84
|
+
// Run guest execution...
|
|
85
|
+
watchdog.abort();
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## 3. Zero-Copy Guest-Host Memory Slices
|
|
92
|
+
|
|
93
|
+
Avoid copying data when passing request payloads into the guest Wasm module. Access the guest's linear memory directly as a borrowed byte slice:
|
|
94
|
+
|
|
95
|
+
```rust
|
|
96
|
+
pub fn inspect_guest_memory(
|
|
97
|
+
memory: &Memory,
|
|
98
|
+
store: &impl AsContext,
|
|
99
|
+
ptr: usize,
|
|
100
|
+
len: usize,
|
|
101
|
+
) -> Result<&[u8], &'static str> {
|
|
102
|
+
let raw_slice = memory.data(store);
|
|
103
|
+
raw_slice.get(ptr..ptr + len).ok_or("Out of bounds memory access")
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## 4. Production Checklist
|
|
110
|
+
|
|
111
|
+
- [ ] Attached `ResourceLimiter` enforcing hard linear memory ceiling (e.g. 16MB–64MB per instance).
|
|
112
|
+
- [ ] Enabled `epoch_interruption(true)` or fuel metering on the `Engine`.
|
|
113
|
+
- [ ] Watchdog task terminates runaway execution after deadline.
|
|
114
|
+
- [ ] Zero-copy host reads directly access `memory.data()` bounds without vector cloning.
|