@sinkaroid/rust-shapeshift 0.0.0-stage → 1.0.2
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,169 @@
|
|
|
1
|
+
# NUMA Architecture, HugePages & TLB Cache Saturation
|
|
2
|
+
|
|
3
|
+
## The Problem: Silicon Topography & The Memory Bus Penalty
|
|
4
|
+
|
|
5
|
+
On multi-socket servers or modern multi-chiplet processors (AMD EPYC, Intel Xeon, Ampere Altra), physical RAM is not a uniform pool. It is partitioned across multiple **NUMA (Non-Uniform Memory Access) Nodes**, where each CPU socket or core complex directly controls a local bank of memory channels:
|
|
6
|
+
|
|
7
|
+
1. **Remote NUMA Interconnect Latency**: When a thread executing on CPU Socket 0 accesses data stored in RAM connected to Socket 1, the memory request must traverse the inter-socket bus (AMD Infinity Fabric / Intel UPI). Remote memory access incurs **2x to 3x higher latency** and consumes scarce inter-socket bandwidth.
|
|
8
|
+
2. **Translation Lookaside Buffer (TLB) Thrashing**: Standard Linux virtual memory uses 4 KB pages. When an application manages large buffers (e.g., a 1 GB packet buffer, cache, or database page pool), the CPU must map **262,144 page entries**. The CPU's L1/L2 TLB (which can hold only 64–1,500 entries) is perpetually thrashed, forcing the hardware MMU to perform slow 4-level page table walks in RAM.
|
|
9
|
+
3. **Paging Jitter**: Under memory pressure, the Linux kernel page daemon (`kswapd`) can swap out active pages or rebalance memory zones, causing latency spikes.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 1. NUMA Node Topology in Rust
|
|
14
|
+
|
|
15
|
+
Before allocating large shared structures, discover the host hardware NUMA nodes and bind threads to memory controllers co-located with their physical CPU socket:
|
|
16
|
+
|
|
17
|
+
```rust
|
|
18
|
+
#[cfg(target_os = "linux")]
|
|
19
|
+
pub fn get_current_numa_node() -> Option<usize> {
|
|
20
|
+
let mut cpu: u32 = 0;
|
|
21
|
+
let mut node: u32 = 0;
|
|
22
|
+
|
|
23
|
+
// Use vDSO getcpu syscall (zero kernel transition)
|
|
24
|
+
let ret = unsafe {
|
|
25
|
+
libc::syscall(
|
|
26
|
+
libc::SYS_getcpu,
|
|
27
|
+
&mut cpu as *mut u32,
|
|
28
|
+
&mut node as *mut u32,
|
|
29
|
+
std::ptr::null_mut::<libc::c_void>(),
|
|
30
|
+
)
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
if ret == 0 {
|
|
34
|
+
Some(node as usize)
|
|
35
|
+
} else {
|
|
36
|
+
None
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Allocating NUMA-Local Memory with `libnuma`
|
|
42
|
+
|
|
43
|
+
When preallocating large pools or ring buffers, bind the memory physical pages to the current thread's NUMA node using `mbind`:
|
|
44
|
+
|
|
45
|
+
```rust
|
|
46
|
+
#[cfg(target_os = "linux")]
|
|
47
|
+
pub unsafe fn allocate_numa_local(size_bytes: usize, numa_node: usize) -> Result<*mut u8, std::io::Error> {
|
|
48
|
+
// 1. Allocate anonymous memory via mmap
|
|
49
|
+
let ptr = libc::mmap(
|
|
50
|
+
std::ptr::null_mut(),
|
|
51
|
+
size_bytes,
|
|
52
|
+
libc::PROT_READ | libc::PROT_WRITE,
|
|
53
|
+
libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
|
|
54
|
+
-1,
|
|
55
|
+
0,
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
if ptr == libc::MAP_FAILED {
|
|
59
|
+
return Err(std::io::Error::last_os_error());
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 2. Bind memory pages strictly to the target NUMA node
|
|
63
|
+
let mut nodemask: libc::c_ulong = 1 << numa_node;
|
|
64
|
+
let ret = libc::mbind(
|
|
65
|
+
ptr,
|
|
66
|
+
size_bytes,
|
|
67
|
+
libc::MPOL_BIND, // Strict policy: fail rather than allocate remote memory
|
|
68
|
+
&mut nodemask,
|
|
69
|
+
std::mem::size_of::<libc::c_ulong>() as libc::c_ulong * 8,
|
|
70
|
+
0,
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
if ret != 0 {
|
|
74
|
+
libc::munmap(ptr, size_bytes);
|
|
75
|
+
return Err(std::io::Error::last_os_error());
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
Ok(ptr as *mut u8)
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
## 2. HugePages (2 MB & 1 GB Pages): Eliminating TLB Misses
|
|
85
|
+
|
|
86
|
+
Replacing standard 4 KB pages with **2 MB HugePages** reduces page table entries by a factor of **512x**, allowing massive memory buffers to fit entirely inside the CPU's hardware TLB cache:
|
|
87
|
+
|
|
88
|
+
| Metric | Standard 4 KB Page | 2 MB HugePage |
|
|
89
|
+
| :--- | :--- | :--- |
|
|
90
|
+
| **Page Table Walk Depth** | 4 levels (PML4 $\to$ PDP $\to$ PD $\to$ PT) | **3 levels** (bypasses Page Table) |
|
|
91
|
+
| **TLB Coverage (1,024 entries)** | 4 MB of RAM | **2 GB of RAM** |
|
|
92
|
+
| **Address Translation Time** | 20–40 ns on TLB miss | **<1 ns (Hot TLB Hit)** |
|
|
93
|
+
|
|
94
|
+
### Allocating HugePages via `madvise` (Transparent HugePages - THP)
|
|
95
|
+
|
|
96
|
+
For application buffers that grow dynamically, advise the Linux kernel to back the virtual memory range with 2 MB transparent huge pages:
|
|
97
|
+
|
|
98
|
+
```rust
|
|
99
|
+
pub unsafe fn advise_hugepages(ptr: *mut u8, len: usize) -> std::io::Result<()> {
|
|
100
|
+
#[cfg(target_os = "linux")]
|
|
101
|
+
{
|
|
102
|
+
// Require memory address to be aligned to 2MB boundary
|
|
103
|
+
let ret = libc::madvise(ptr as *mut _, len, libc::MADV_HUGEPAGE);
|
|
104
|
+
if ret != 0 {
|
|
105
|
+
return Err(std::io::Error::last_os_error());
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
Ok(())
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Direct Allocation via `MAP_HUGETLB` (Explicit 2MB HugePages)
|
|
113
|
+
|
|
114
|
+
For dedicated ring buffers and frame pools:
|
|
115
|
+
|
|
116
|
+
```rust
|
|
117
|
+
#[cfg(target_os = "linux")]
|
|
118
|
+
pub unsafe fn allocate_explicit_hugepages(size_bytes: usize) -> Result<*mut u8, std::io::Error> {
|
|
119
|
+
// Round up size to 2MB boundary
|
|
120
|
+
let page_size = 2 * 1024 * 1024;
|
|
121
|
+
let aligned_size = (size_bytes + page_size - 1) & !(page_size - 1);
|
|
122
|
+
|
|
123
|
+
let ptr = libc::mmap(
|
|
124
|
+
std::ptr::null_mut(),
|
|
125
|
+
aligned_size,
|
|
126
|
+
libc::PROT_READ | libc::PROT_WRITE,
|
|
127
|
+
libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_HUGETLB,
|
|
128
|
+
-1,
|
|
129
|
+
0,
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
if ptr == libc::MAP_FAILED {
|
|
133
|
+
return Err(std::io::Error::last_os_error());
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
Ok(ptr as *mut u8)
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
## 3. Physical Page Pinning with `mlockall`
|
|
143
|
+
|
|
144
|
+
To eliminate latency spikes caused by minor page faults or Linux page eviction, lock the entire process address space into physical RAM:
|
|
145
|
+
|
|
146
|
+
```rust
|
|
147
|
+
pub fn lock_process_memory() -> Result<(), std::io::Error> {
|
|
148
|
+
#[cfg(target_os = "linux")]
|
|
149
|
+
unsafe {
|
|
150
|
+
// MCL_CURRENT: Lock all currently mapped pages
|
|
151
|
+
// MCL_FUTURE: Lock all pages mapped in the future
|
|
152
|
+
let ret = libc::mlockall(libc::MCL_CURRENT | libc::MCL_FUTURE);
|
|
153
|
+
if ret != 0 {
|
|
154
|
+
return Err(std::io::Error::last_os_error());
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
Ok(())
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
*Note: Requires `ulimit -l unlimited` or the Linux `CAP_IPC_LOCK` capability.*
|
|
162
|
+
|
|
163
|
+
---
|
|
164
|
+
|
|
165
|
+
## 4. Production Architectural Checklist for Silicon Topography
|
|
166
|
+
|
|
167
|
+
1. **NUMA Binding with Thread Affinity**: Pair every `core_affinity::set_for_current` call with NUMA-local memory allocation (`MPOL_BIND`). Never allow a worker thread on Socket 1 to allocate buffers on Socket 0.
|
|
168
|
+
2. **Pre-Fault Buffers at Startup**: Always write a single byte to every 2 MB page during the initialization phase (`ptr.write_volatile(0)`) to trigger kernel page allocation upfront, ensuring zero fault overhead during runtime.
|
|
169
|
+
3. **Verify via Linux Procfs**: Inspect `/proc/<pid>/numa_maps` to ensure zero pages are mapped on remote NUMA nodes.
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
# Ownership, Borrowing, Visibility & Memory Decision Matrix
|
|
2
|
+
|
|
3
|
+
In Rust systems architecture, memory safety and extreme runtime efficiency are direct consequences of the **Ownership and Borrow Checker Permission Model**. Novice developers and unguided AI agents frequently resort to `.clone()` as a crutch to bypass compiler borrow errors, introducing unnecessary heap churn, latency spikes, and CPU cache misses.
|
|
4
|
+
|
|
5
|
+
This playbook provides the authoritative **Decision Matrix** for placing data on the Stack vs Heap, mastering the Borrow Checker's permission mechanics, and applying strict visibility encapsulation.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. The Borrow Checker Permission Model (R / W / O)
|
|
10
|
+
|
|
11
|
+
At any given point in execution, the Rust compiler tracks three fundamental permissions for every variable and memory path:
|
|
12
|
+
|
|
13
|
+
- **Read (`R`)**: The data can be read, copied, or referenced.
|
|
14
|
+
- **Write (`W`)**: The data can be mutated or overwritten.
|
|
15
|
+
- **Own (`O`)**: The owner can move, transfer, or deallocate the memory.
|
|
16
|
+
|
|
17
|
+
```text
|
|
18
|
+
Variable Binding: let mut x = String::from("data");
|
|
19
|
+
[ Permissions: R + W + O ]
|
|
20
|
+
|
|
|
21
|
+
+---> Shared Borrow: let y = &x;
|
|
22
|
+
| x: [ R (W and O SUSPENDED) ]
|
|
23
|
+
| y: [ R + O (points to x) ]
|
|
24
|
+
|
|
|
25
|
+
+---> Exclusive Borrow: let z = &mut x;
|
|
26
|
+
x: [ NONE (R, W, and O completely REVOKED) ]
|
|
27
|
+
z: [ R + W + O (exclusive access to x's target) ]
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### The Universal Rule: Aliasing XOR Mutability
|
|
31
|
+
Memory can have:
|
|
32
|
+
- **Unlimited simultaneous Readers (`&T`)** with zero Writers, OR
|
|
33
|
+
- **Exactly ONE Writer (`&mut T`)** with zero Readers.
|
|
34
|
+
|
|
35
|
+
Never both simultaneously.
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## 2. Eliminating the `.clone()` Anti-Pattern
|
|
40
|
+
|
|
41
|
+
When an AI agent or developer writes `.clone()`, it is often an architectural smell indicating a failure to understand ownership transfer or borrowing.
|
|
42
|
+
|
|
43
|
+
### Anti-Pattern 1: Cloning to pass data into a function that only reads it
|
|
44
|
+
```rust
|
|
45
|
+
// ❌ WRONG: Allocates a new String on the heap just to read its length
|
|
46
|
+
fn print_length(s: String) {
|
|
47
|
+
println!("Length: {}", s.len());
|
|
48
|
+
}
|
|
49
|
+
print_length(name.clone());
|
|
50
|
+
|
|
51
|
+
// ✅ CORRECT: Borrow as a zero-cost slice (&str)
|
|
52
|
+
fn print_length(s: &str) {
|
|
53
|
+
println!("Length: {}", s.len());
|
|
54
|
+
}
|
|
55
|
+
print_length(&name);
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Anti-Pattern 2: Cloning struct fields in getters
|
|
59
|
+
```rust
|
|
60
|
+
// ❌ WRONG: Clones internal state, forcing heap allocation on every call
|
|
61
|
+
pub struct Config {
|
|
62
|
+
database_url: String,
|
|
63
|
+
}
|
|
64
|
+
impl Config {
|
|
65
|
+
pub fn database_url(&self) -> String {
|
|
66
|
+
self.database_url.clone()
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ✅ CORRECT: Return a borrowed reference (&str)
|
|
71
|
+
impl Config {
|
|
72
|
+
pub fn database_url(&self) -> &str {
|
|
73
|
+
&self.database_url
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### When is `.clone()` acceptable?
|
|
79
|
+
1. Cloning primitives or small `Copy` types (`u32`, `bool`, `[u8; 16]`).
|
|
80
|
+
2. Cloning an `Arc<T>` pointer (only increments an atomic counter; 0 heap allocation).
|
|
81
|
+
3. Explicit, intentional creation of an independent, mutable copy when mutation must not affect the original.
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## 3. The Memory Placement Decision Matrix: Where Should Data Live?
|
|
86
|
+
|
|
87
|
+
Use this decision matrix when defining structs, function signatures, and state:
|
|
88
|
+
|
|
89
|
+
```text
|
|
90
|
+
Does the data outlive the current scope?
|
|
91
|
+
/ \
|
|
92
|
+
NO YES
|
|
93
|
+
/ \
|
|
94
|
+
Borrow as `&T` or `&str` Is it shared across multiple
|
|
95
|
+
(Zero allocations, stack) threads or Tokio tasks?
|
|
96
|
+
/ \
|
|
97
|
+
YES NO
|
|
98
|
+
/ \
|
|
99
|
+
Use `Arc<T>` (Read-only) Is the size known at
|
|
100
|
+
or `Arc<RwLock<T>>` (Mut) compile-time & small (<2KB)?
|
|
101
|
+
/ \
|
|
102
|
+
YES NO
|
|
103
|
+
/ \
|
|
104
|
+
Store DIRECT in Is it a short string
|
|
105
|
+
struct on Stack (<= 24 bytes)?
|
|
106
|
+
(Zero indirection) / \
|
|
107
|
+
YES NO
|
|
108
|
+
/ \
|
|
109
|
+
Use `CompactString` Use `Box<T>` / `Box<str>`
|
|
110
|
+
(Inlined on stack) (Explicit Heap, lean Future)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Detailed Placement Guidelines:
|
|
114
|
+
|
|
115
|
+
| Type | Allocation Location | Best Use Case | Anti-Pattern Warning |
|
|
116
|
+
|---|---|---|---|
|
|
117
|
+
| **Direct Struct Field** (`u64`, `bool`, `CompactString`) | **Stack / Inlined** | Fixed-size metadata, IDs, small state objects. | Do not put arrays > 4KB direct on the stack; risks Tokio task stack overflow. |
|
|
118
|
+
| **`Box<T>`** | **Heap (Single Owner)** | Large payload buffers, recursive types, keeping Tokio `Future` state machine sizes small. | Do not use for small primitives like `Box<u32>` (adds pointer indirection for no benefit). |
|
|
119
|
+
| **`Arc<T>`** | **Heap (Thread-Safe Shared)** | Long-lived shared singletons (`reqwest::Client`, Redis pools, global caches). | Do not wrap tiny ephemeral data in `Arc`; atomic reference counting has non-zero CPU cost. |
|
|
120
|
+
| **`&'a T` / `&str`** | **Borrowed (0 Allocation)** | Reading data within a single request or lexical lifetime. | Do not force lifetimes onto structs that must live in async task boundaries (`'static` required). |
|
|
121
|
+
| **`Cow<'a, str>`** | **Dual (Borrowed or Heap)** | Data that is mostly read as-is, but occasionally requires normalization or escaping. | Do not use if the data is *always* mutated or *never* mutated. |
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## 4. Keeping Tokio `Future` State Machines Small
|
|
126
|
+
|
|
127
|
+
Every local variable held across an `.await` point becomes part of the generated compiler state machine struct:
|
|
128
|
+
|
|
129
|
+
```rust
|
|
130
|
+
// ❌ WRONG: Inflates Future size to >128KB!
|
|
131
|
+
async fn handle_request() {
|
|
132
|
+
let large_buffer = [0u8; 128 * 1024]; // 128 KB on the stack!
|
|
133
|
+
tokio::time::sleep(std::time::Duration::from_millis(10)).await; // Held across await!
|
|
134
|
+
process_buffer(&large_buffer);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ✅ CORRECT: Keep the Future footprint tiny (8 bytes pointer)
|
|
138
|
+
async fn handle_request() {
|
|
139
|
+
let large_buffer = vec![0u8; 128 * 1024].into_boxed_slice(); // Heap-allocated Box
|
|
140
|
+
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
|
141
|
+
process_buffer(&large_buffer);
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
## 5. Visibility & Encapsulation Discipline
|
|
148
|
+
|
|
149
|
+
Exposing public struct fields (`pub`) breaks encapsulation, prevents zero-cost invariants, and prevents memory layout optimizations.
|
|
150
|
+
|
|
151
|
+
### Rule 1: Scoped Visibility
|
|
152
|
+
Use the narrowest possible visibility modifier:
|
|
153
|
+
- **`pub(crate)`**: Visible anywhere inside the current crate, but hidden from external consumers.
|
|
154
|
+
- **`pub(super)`**: Visible only to the immediate parent module.
|
|
155
|
+
- **Private (no modifier)**: Default. Visible only within the declaring module.
|
|
156
|
+
- **`pub`**: Reserved strictly for the public public-facing API surface.
|
|
157
|
+
|
|
158
|
+
```rust
|
|
159
|
+
pub struct ServerConfig {
|
|
160
|
+
// ❌ WRONG: Blanket pub allows callers to invalidate invariants
|
|
161
|
+
// pub bind_address: String,
|
|
162
|
+
|
|
163
|
+
// ✅ CORRECT: Crate-internal read/write, external immutable access
|
|
164
|
+
pub(crate) bind_address: CompactString,
|
|
165
|
+
worker_threads: usize,
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
impl ServerConfig {
|
|
169
|
+
pub fn bind_address(&self) -> &str {
|
|
170
|
+
&self.bind_address
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Rule 2: The Newtype Pattern for Zero-Cost Invariants
|
|
176
|
+
Never pass raw primitive strings for domain identifiers (e.g. `user_id: String` vs `video_id: String`):
|
|
177
|
+
|
|
178
|
+
```rust
|
|
179
|
+
use compact_str::CompactString;
|
|
180
|
+
|
|
181
|
+
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
182
|
+
pub struct VideoId(pub(crate) CompactString);
|
|
183
|
+
|
|
184
|
+
impl VideoId {
|
|
185
|
+
pub fn new(raw: &str) -> Result<Self, AppError> {
|
|
186
|
+
if raw.len() < 3 || raw.len() > 32 {
|
|
187
|
+
return Err(AppError::Validation("Invalid VideoId length".into()));
|
|
188
|
+
}
|
|
189
|
+
Ok(Self(CompactString::new(raw)))
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
pub fn as_str(&self) -> &str {
|
|
193
|
+
&self.0
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
*Zero-Cost*: `VideoId` has the exact same memory layout and performance as `CompactString` (0 runtime overhead), but guarantees type safety at compile time.
|
|
198
|
+
|
|
199
|
+
---
|
|
200
|
+
|
|
201
|
+
## 6. Compile-Time Typestate Pattern
|
|
202
|
+
|
|
203
|
+
Enforce access permissions and valid state transitions at compile-time without storing runtime status enums or boolean flags:
|
|
204
|
+
|
|
205
|
+
```rust
|
|
206
|
+
use std::marker::PhantomData;
|
|
207
|
+
|
|
208
|
+
// Zero-sized state markers (0 bytes runtime overhead!)
|
|
209
|
+
pub struct Draft;
|
|
210
|
+
pub struct Published;
|
|
211
|
+
|
|
212
|
+
pub struct Article<State> {
|
|
213
|
+
title: Box<str>,
|
|
214
|
+
content: Box<str>,
|
|
215
|
+
_state: PhantomData<State>,
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
impl Article<Draft> {
|
|
219
|
+
pub fn new(title: &str, content: &str) -> Self {
|
|
220
|
+
Self {
|
|
221
|
+
title: title.into(),
|
|
222
|
+
content: content.into(),
|
|
223
|
+
_state: PhantomData,
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Permission transition: Can only publish a Draft
|
|
228
|
+
pub fn publish(self) -> Article<Published> {
|
|
229
|
+
Article {
|
|
230
|
+
title: self.title,
|
|
231
|
+
content: self.content,
|
|
232
|
+
_state: PhantomData,
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
impl Article<Published> {
|
|
238
|
+
// Only published articles have a URL method!
|
|
239
|
+
pub fn public_url(&self) -> String {
|
|
240
|
+
format!("/articles/{}", self.title)
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
---
|
|
246
|
+
|
|
247
|
+
## 7. Architecture Checklist
|
|
248
|
+
|
|
249
|
+
1. Are function arguments accepting borrowed references (`&str`, `&[T]`) instead of owned types (`String`, `Vec<T>`) whenever ownership transfer is unnecessary?
|
|
250
|
+
2. Has `.clone()` been audited and eliminated on hot paths?
|
|
251
|
+
3. Are large structs (>2KB) stored via `Box<T>` to keep Tokio `Future` sizes small?
|
|
252
|
+
4. Are struct fields kept private or scoped with `pub(crate)`?
|
|
253
|
+
5. Are domain primitives wrapped in zero-cost Newtypes to enforce validation invariants?
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# Profile-Guided Optimization (PGO) and Fast Hashers
|
|
2
|
+
|
|
3
|
+
Standard release builds (`cargo build --release`) optimize code based on static compiler heuristics. Profile-Guided Optimization (PGO) informs LLVM of the actual execution frequency of branches, loops, and function calls from real production workloads, boosting runtime throughput by 10% to 30% without changing a single line of application code.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. The PGO Workflow
|
|
8
|
+
|
|
9
|
+
1. **Instrument**: Build the binary with instrumentation hooks that record branch counters.
|
|
10
|
+
2. **Profile**: Run representative production-like workloads (load tests, stress benchmarks).
|
|
11
|
+
3. **Merge**: Combine profile counters with `llvm-profdata`.
|
|
12
|
+
4. **Optimize**: Rebuild using the merged profile data.
|
|
13
|
+
|
|
14
|
+
### Automated PGO Shell Pipeline
|
|
15
|
+
```bash
|
|
16
|
+
#!/bin/bash
|
|
17
|
+
set -e
|
|
18
|
+
|
|
19
|
+
PGO_DIR="/tmp/pgo-data"
|
|
20
|
+
rm -rf "$PGO_DIR"
|
|
21
|
+
mkdir -p "$PGO_DIR"
|
|
22
|
+
|
|
23
|
+
# Step 1: Instrumented Build
|
|
24
|
+
echo "Building instrumented binary..."
|
|
25
|
+
RUSTFLAGS="-Cprofile-generate=$PGO_DIR" cargo build --release
|
|
26
|
+
|
|
27
|
+
# Step 2: Run representative load
|
|
28
|
+
echo "Running profiling workloads..."
|
|
29
|
+
./target/release/my-backend --benchmark-mode &
|
|
30
|
+
PID=$!
|
|
31
|
+
sleep 1
|
|
32
|
+
# Execute realistic HTTP/socket benchmark
|
|
33
|
+
wrk -t4 -c100 -d30s http://localhost:8080/api/v1/bench
|
|
34
|
+
kill -SIGTERM $PID
|
|
35
|
+
wait $PID 2>/dev/null || true
|
|
36
|
+
|
|
37
|
+
# Step 3: Merge profile data
|
|
38
|
+
echo "Merging profile counters..."
|
|
39
|
+
llvm-profdata merge -o "$PGO_DIR/merged.profdata" "$PGO_DIR"
|
|
40
|
+
|
|
41
|
+
# Step 4: Rebuild fully optimized binary
|
|
42
|
+
echo "Compiling final PGO-optimized binary..."
|
|
43
|
+
RUSTFLAGS="-Cprofile-use=$PGO_DIR/merged.profdata -Cllvm-args=-pgo-warn-missing-function" \
|
|
44
|
+
cargo build --release
|
|
45
|
+
|
|
46
|
+
echo "Success! PGO binary located at target/release/my-backend"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## 2. Hasher Selection Matrix: SipHash vs `ahash` vs `FxHashMap`
|
|
52
|
+
|
|
53
|
+
`std::collections::HashMap` uses `SipHash-1-3` by default to defend against HashDoS algorithmic attacks. However, SipHash is 2x to 4x slower than non-cryptographic hashers. Choosing the correct hasher depends on key origin:
|
|
54
|
+
|
|
55
|
+
| Hasher | Crate | DoS-Resistant | Relative Speed | Ideal Use Case |
|
|
56
|
+
| :--- | :--- | :--- | :--- | :--- |
|
|
57
|
+
| **SipHash-1-3** | `std::collections` | Yes (Cryptographic) | Baseline (1x) | Untrusted external user input (headers, query params) |
|
|
58
|
+
| **`AHashMap`** | `ahash` | Yes (Per-process seed) | **2.5x faster** | General-purpose high-throughput replacement |
|
|
59
|
+
| **`FxHashMap`** | `rustc-hash` | No (Deterministic) | **4x faster** | Internal compiler IDs, integer keys, pointer handles |
|
|
60
|
+
|
|
61
|
+
```rust
|
|
62
|
+
use ahash::AHashMap;
|
|
63
|
+
use rustc_hash::FxHashMap;
|
|
64
|
+
|
|
65
|
+
// High-speed general-purpose map (safe for general web traffic)
|
|
66
|
+
pub type FastMap<K, V> = AHashMap<K, V>;
|
|
67
|
+
|
|
68
|
+
// Ultra-fast map for internal u32/u64 IDs (trusted keys only)
|
|
69
|
+
pub type InternalIdMap<V> = FxHashMap<u64, V>;
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## 3. Post-Link Binary Optimization with LLVM BOLT
|
|
75
|
+
|
|
76
|
+
For maximum instruction cache locality, combine PGO with LLVM BOLT (Binary Optimization and Layout Tool):
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
# Reorder basic blocks and layout functions by hotness
|
|
80
|
+
llvm-bolt target/release/my-backend \
|
|
81
|
+
-o target/release/my-backend.bolt \
|
|
82
|
+
-data=perf.data \
|
|
83
|
+
-reorder-blocks=ext-tsp \
|
|
84
|
+
-reorder-functions=hfsort
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## 4. Production Checklist
|
|
90
|
+
|
|
91
|
+
- [ ] Automated PGO script integrated into release CI pipeline.
|
|
92
|
+
- [ ] Replaced internal integer `HashMap` instances with `FxHashMap` or `AHashMap`.
|
|
93
|
+
- [ ] Preserved default `SipHash` on maps directly exposed to unbounded external user keys.
|
|
94
|
+
- [ ] Profile workloads match realistic traffic shapes rather than artificial micro-benchmarks.
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# Bounded Rate Limiting & Memory-Safe State Management
|
|
2
|
+
|
|
3
|
+
In concurrent backends, in-memory rate limiters that store client IP records without hard boundary caps will experience unbounded memory growth under distributed traffic spikes or DDoS conditions. High-efficiency systems require deterministic memory ceilings and active TTL eviction.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Bounded In-Memory Rate Limiting Architecture
|
|
8
|
+
|
|
9
|
+
This pattern uses `dashmap::DashMap` with **two levels of memory defense**:
|
|
10
|
+
1. A **background cleaner task** running every 30 seconds to evict expired IP windows.
|
|
11
|
+
2. An **emergency capacity ceiling sweep** (`BUCKET_MAX_SIZE = 50,000`) that runs when under heavy load, preventing the map from ever exceeding fixed RAM limits.
|
|
12
|
+
|
|
13
|
+
```rust
|
|
14
|
+
use dashmap::DashMap;
|
|
15
|
+
use std::sync::Arc;
|
|
16
|
+
use std::time::{Duration, Instant, SystemTime};
|
|
17
|
+
use tokio::time::sleep;
|
|
18
|
+
|
|
19
|
+
const WINDOW_MS: u128 = 15 * 60 * 1000; // 15 minutes window
|
|
20
|
+
const LIMIT_MAX: u32 = 50; // Max requests per window
|
|
21
|
+
const BUCKET_MAX_SIZE: usize = 50_000; // Hard cap on in-memory IP entries
|
|
22
|
+
|
|
23
|
+
#[derive(Clone, Debug)]
|
|
24
|
+
pub struct Counter {
|
|
25
|
+
pub count: u32,
|
|
26
|
+
pub reset_at: Instant,
|
|
27
|
+
pub reset_at_sys: SystemTime,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
#[derive(Clone)]
|
|
31
|
+
pub struct RateLimitState {
|
|
32
|
+
buckets: Arc<DashMap<String, Counter>>,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
impl RateLimitState {
|
|
36
|
+
pub fn new() -> Self {
|
|
37
|
+
let buckets = Arc::new(DashMap::new());
|
|
38
|
+
let buckets_clone = Arc::clone(&buckets);
|
|
39
|
+
|
|
40
|
+
// 1. Background Sweeper: Purges expired IP entries every 30 seconds
|
|
41
|
+
tokio::spawn(async move {
|
|
42
|
+
loop {
|
|
43
|
+
sleep(Duration::from_secs(30)).await;
|
|
44
|
+
let now = Instant::now();
|
|
45
|
+
buckets_clone.retain(|_, counter: &mut Counter| counter.reset_at > now);
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
Self { buckets }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
pub fn touch(&self, key: String) -> Counter {
|
|
53
|
+
let now_instant = Instant::now();
|
|
54
|
+
let now_sys = SystemTime::now();
|
|
55
|
+
|
|
56
|
+
// Check if an unexpired counter exists for this IP
|
|
57
|
+
if let Some(mut r) = self.buckets.get_mut(&key) {
|
|
58
|
+
if r.reset_at > now_instant {
|
|
59
|
+
r.count += 1;
|
|
60
|
+
return r.clone();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// 2. Emergency Bounded Ceiling: If bucket is saturated, sweep immediately
|
|
65
|
+
if self.buckets.len() >= BUCKET_MAX_SIZE {
|
|
66
|
+
self.buckets.retain(|_, counter| counter.reset_at > now_instant);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
let fresh = Counter {
|
|
70
|
+
count: 1,
|
|
71
|
+
reset_at: now_instant + Duration::from_millis(WINDOW_MS as u64),
|
|
72
|
+
reset_at_sys: now_sys + Duration::from_millis(WINDOW_MS as u64),
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// Only insert if within memory bounds
|
|
76
|
+
if self.buckets.len() < BUCKET_MAX_SIZE {
|
|
77
|
+
self.buckets.insert(key, fresh.clone());
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
fresh
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
## 2. Reverse Proxy IP Extraction Guard
|
|
88
|
+
|
|
89
|
+
Prevent IP spoofing while correctly detecting client IPs behind Cloudflare, Fly.io, or Vercel:
|
|
90
|
+
|
|
91
|
+
```rust
|
|
92
|
+
use axum::http::HeaderMap;
|
|
93
|
+
|
|
94
|
+
pub fn get_client_ip(headers: &HeaderMap) -> String {
|
|
95
|
+
// Trusted upstream provider headers
|
|
96
|
+
let trusted_ip_headers = [
|
|
97
|
+
"cf-connecting-ip",
|
|
98
|
+
"fly-client-ip",
|
|
99
|
+
"x-vercel-forwarded-for",
|
|
100
|
+
"x-client-ip"
|
|
101
|
+
];
|
|
102
|
+
|
|
103
|
+
for header in trusted_ip_headers {
|
|
104
|
+
if let Some(val) = headers.get(header).and_then(|v| v.to_str().ok()) {
|
|
105
|
+
let ip = val.split(',').next().unwrap_or("").trim();
|
|
106
|
+
if !ip.is_empty() {
|
|
107
|
+
return ip.to_string();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Fallback to standard x-forwarded-for or x-real-ip
|
|
113
|
+
headers
|
|
114
|
+
.get("x-forwarded-for")
|
|
115
|
+
.and_then(|h| h.to_str().ok())
|
|
116
|
+
.and_then(|s| s.split(',').next())
|
|
117
|
+
.map(|s| s.trim().to_string())
|
|
118
|
+
.unwrap_or_else(|| "127.0.0.1".to_string())
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## 3. Progressive Delay (Slow-Down) Before Hard Rate Limiting
|
|
125
|
+
|
|
126
|
+
Instead of an abrupt `429 Too Many Requests`, introduce progressive delays (`tokio::time::sleep`) to throttle aggressive scrapers smoothly:
|
|
127
|
+
|
|
128
|
+
```rust
|
|
129
|
+
const SLOW_DELAY_AFTER: u32 = 30;
|
|
130
|
+
const SLOW_DELAY_MS: u64 = 500;
|
|
131
|
+
const SLOW_MAX_DELAY_MS: u64 = 10_000;
|
|
132
|
+
|
|
133
|
+
pub async fn apply_progressive_delay(counter: &Counter) {
|
|
134
|
+
if counter.count > SLOW_DELAY_AFTER && counter.count <= LIMIT_MAX {
|
|
135
|
+
let over = (counter.count - SLOW_DELAY_AFTER) as u64;
|
|
136
|
+
let delay = std::cmp::min(over * SLOW_DELAY_MS, SLOW_MAX_DELAY_MS);
|
|
137
|
+
tokio::time::sleep(Duration::from_millis(delay)).await;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
```
|