@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,105 @@
|
|
|
1
|
+
# Bounded Caching, Client Pooling & Telemetry Cardinality
|
|
2
|
+
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
## 1. Bounded In-Memory Caching with `moka`
|
|
6
|
+
|
|
7
|
+
Dynamic languages often store caches in plain objects or maps (`const cache = {}`), which grow without bounds until the process crashes with Out-Of-Memory (OOM).
|
|
8
|
+
|
|
9
|
+
In Rust, use `moka::future::Cache` to enforce hard memory and eviction bounds:
|
|
10
|
+
|
|
11
|
+
```rust
|
|
12
|
+
use moka::future::Cache;
|
|
13
|
+
use std::time::Duration;
|
|
14
|
+
|
|
15
|
+
#[derive(Clone)]
|
|
16
|
+
pub struct CacheService {
|
|
17
|
+
// Stores raw responses bounded by count and time
|
|
18
|
+
cache: Cache<String, Vec<u8>>,
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
impl CacheService {
|
|
22
|
+
pub fn new() -> Self {
|
|
23
|
+
let cache = Cache::builder()
|
|
24
|
+
// Strict bound: never hold more than 10,000 entries
|
|
25
|
+
.max_capacity(10_000)
|
|
26
|
+
// Time to live: entries expire after 1 hour
|
|
27
|
+
.time_to_live(Duration::from_secs(3600))
|
|
28
|
+
// Time to idle: entries unaccessed for 15 mins are evicted
|
|
29
|
+
.time_to_idle(Duration::from_secs(900))
|
|
30
|
+
.build();
|
|
31
|
+
|
|
32
|
+
Self { cache }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
pub async fn get(&self, key: &str) -> Option<Vec<u8>> {
|
|
36
|
+
self.cache.get(key).await
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
pub async fn set(&self, key: &str, val: Vec<u8>) {
|
|
40
|
+
self.cache.insert(key.to_string(), val).await;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## 2. Singleton `reqwest::Client` in Shared State
|
|
48
|
+
|
|
49
|
+
Creating `reqwest::Client` per-request leaks sockets, wastes TLS handshakes, and bloats memory. Instantiate one client in `AppState` and share it via `Arc`:
|
|
50
|
+
|
|
51
|
+
```rust
|
|
52
|
+
use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT};
|
|
53
|
+
use std::time::Duration;
|
|
54
|
+
|
|
55
|
+
pub fn build_http_client(user_agent: &str) -> reqwest::Client {
|
|
56
|
+
let mut headers = HeaderMap::new();
|
|
57
|
+
headers.insert(USER_AGENT, HeaderValue::from_str(user_agent).unwrap());
|
|
58
|
+
|
|
59
|
+
reqwest::Client::builder()
|
|
60
|
+
.default_headers(headers)
|
|
61
|
+
.pool_idle_timeout(Duration::from_secs(90))
|
|
62
|
+
.pool_max_idle_per_host(10)
|
|
63
|
+
.tcp_keepalive(Duration::from_secs(60))
|
|
64
|
+
.timeout(Duration::from_secs(15))
|
|
65
|
+
.gzip(true)
|
|
66
|
+
.deflate(true)
|
|
67
|
+
.build()
|
|
68
|
+
.expect("Failed to build HTTP client")
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## 3. Protecting Against Metric Cardinality Explosion
|
|
75
|
+
|
|
76
|
+
When exporting Prometheus metrics, tracking dynamic paths like `/search?q=rust&user=123` creates a new hashmap entry for every unique URL, quickly causing gigabytes of RAM usage.
|
|
77
|
+
|
|
78
|
+
Use `axum::extract::MatchedPath` to strictly normalize route templates:
|
|
79
|
+
|
|
80
|
+
```rust
|
|
81
|
+
use axum::{body::Body, extract::MatchedPath, http::Request, middleware::Next, response::Response};
|
|
82
|
+
|
|
83
|
+
pub async fn telemetry_middleware(req: Request<Body>, next: Next) -> Response {
|
|
84
|
+
let method = req.method().to_string();
|
|
85
|
+
let raw_path = req.uri().path().to_string();
|
|
86
|
+
|
|
87
|
+
// Prevent /metrics endpoint from tracking itself
|
|
88
|
+
if raw_path == "/metrics" {
|
|
89
|
+
return next.run(req).await;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// STRICT route normalization: Only record matched templates (e.g. /video/:id)
|
|
93
|
+
// NEVER record query strings or raw parameters!
|
|
94
|
+
let matched_path = req
|
|
95
|
+
.extensions()
|
|
96
|
+
.get::<MatchedPath>()
|
|
97
|
+
.map(|mp| mp.as_str().to_string())
|
|
98
|
+
.unwrap_or_else(|| "/unmatched".to_string());
|
|
99
|
+
|
|
100
|
+
let label_key = format!("method=\"{method}\",path=\"{matched_path}\"");
|
|
101
|
+
// Increment metric counter safely bounded by finite routes...
|
|
102
|
+
|
|
103
|
+
next.run(req).await
|
|
104
|
+
}
|
|
105
|
+
```
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# Bounded Streaming & Memory Exhaustion Guards
|
|
2
|
+
|
|
3
|
+
One of the most insidious causes of production out-of-memory (OOM) crashes in backend services is **unbounded payload buffering**. Calling `res.text().await`, `res.bytes().await`, or accepting unconstrained incoming POST bodies forces the process to allocate contiguous heap memory matching the entire payload size.
|
|
4
|
+
|
|
5
|
+
If an upstream provider returns a 50MB error page, a decompression bomb, or an infinite chunked HTTP stream, a single request can consume hundreds of megabytes of RAM that glibc may not immediately return to the operating system.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. Guarding Inbound Axum Requests
|
|
10
|
+
|
|
11
|
+
Never allow incoming HTTP request bodies to allocate unbounded memory. Axum provides `DefaultBodyLimit` to reject oversized payloads at the socket layer before they reach handlers:
|
|
12
|
+
|
|
13
|
+
```rust
|
|
14
|
+
use axum::{
|
|
15
|
+
extract::DefaultBodyLimit,
|
|
16
|
+
routing::post,
|
|
17
|
+
Router,
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
pub fn configure_payload_limits(app: Router) -> Router {
|
|
21
|
+
app
|
|
22
|
+
// Enforce a strict global limit (e.g., 64KB for standard JSON APIs)
|
|
23
|
+
.layer(DefaultBodyLimit::max(64 * 1024))
|
|
24
|
+
// Or override for specific file-upload endpoints:
|
|
25
|
+
// .route("/upload", post(upload_handler).layer(DefaultBodyLimit::max(10 * 1024 * 1024)))
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## 2. Bounded Upstream Response Consumption
|
|
32
|
+
|
|
33
|
+
When fetching data from third-party APIs or external websites, never buffer the entire response blindly. Use `futures_util::StreamExt` to read the response stream with a hard byte ceiling:
|
|
34
|
+
|
|
35
|
+
```rust
|
|
36
|
+
use bytes::{Bytes, BytesMut};
|
|
37
|
+
use futures_util::StreamExt;
|
|
38
|
+
use reqwest::Response;
|
|
39
|
+
|
|
40
|
+
const MAX_SCRAPE_BYTES: usize = 512 * 1024; // 512 KB ceiling
|
|
41
|
+
|
|
42
|
+
pub async fn read_bounded_body(res: Response) -> Result<Bytes, AppError> {
|
|
43
|
+
// 1. Verify Content-Length header early if available
|
|
44
|
+
if let Some(len) = res.content_length() {
|
|
45
|
+
if len > MAX_SCRAPE_BYTES as u64 {
|
|
46
|
+
return Err(AppError::PayloadTooLarge(format!(
|
|
47
|
+
"Upstream payload exceeds maximum allowance: {len} bytes"
|
|
48
|
+
)));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// 2. Stream chunks with hard byte accumulator
|
|
53
|
+
let mut stream = res.bytes_stream();
|
|
54
|
+
let mut buffer = BytesMut::with_capacity(32 * 1024); // Start lean with 32KB
|
|
55
|
+
|
|
56
|
+
while let Some(chunk_result) = stream.next().await {
|
|
57
|
+
let chunk = chunk_result.map_err(|e| AppError::Upstream(e.to_string()))?;
|
|
58
|
+
|
|
59
|
+
if buffer.len() + chunk.len() > MAX_SCRAPE_BYTES {
|
|
60
|
+
// Cut the socket immediately: prevents downloading massive payloads
|
|
61
|
+
return Err(AppError::PayloadTooLarge(
|
|
62
|
+
"Upstream response exceeded 512KB threshold during streaming".into(),
|
|
63
|
+
));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
buffer.extend_from_slice(&chunk);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
Ok(buffer.freeze())
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## 3. Early-Break Streaming for Fast Parsing
|
|
76
|
+
|
|
77
|
+
When extracting metadata from the beginning of an HTML document or stream, stop reading the HTTP stream as soon as the target content is found:
|
|
78
|
+
|
|
79
|
+
```rust
|
|
80
|
+
pub async fn read_until_delimiter(res: Response, delimiter: &str) -> Result<String, AppError> {
|
|
81
|
+
let mut stream = res.bytes_stream();
|
|
82
|
+
let mut accumulated = String::with_capacity(16 * 1024);
|
|
83
|
+
|
|
84
|
+
while let Some(chunk_res) = stream.next().await {
|
|
85
|
+
let chunk = chunk_res.map_err(|e| AppError::Upstream(e.to_string()))?;
|
|
86
|
+
let text = String::from_utf8_lossy(&chunk);
|
|
87
|
+
accumulated.push_str(&text);
|
|
88
|
+
|
|
89
|
+
// Terminate download early as soon as the header/target section is captured
|
|
90
|
+
if accumulated.contains(delimiter) {
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if accumulated.len() > MAX_SCRAPE_BYTES {
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
Ok(accumulated)
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
## 4. Zero-Copy Media Proxying via `Body::from_stream`
|
|
106
|
+
|
|
107
|
+
When proxying images, video streams, or binary assets, **do not read the bytes into memory**. Stream them directly from the upstream `reqwest` response into the downstream `axum` response body:
|
|
108
|
+
|
|
109
|
+
```rust
|
|
110
|
+
use axum::{
|
|
111
|
+
body::Body,
|
|
112
|
+
http::{header, HeaderMap, StatusCode},
|
|
113
|
+
response::{IntoResponse, Response as AxumResponse},
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
pub async fn proxy_asset_handler(
|
|
117
|
+
client: reqwest::Client,
|
|
118
|
+
target_url: &str,
|
|
119
|
+
) -> Result<AxumResponse, AppError> {
|
|
120
|
+
let upstream_res = client.get(target_url).send().await.map_err(AppError::from)?;
|
|
121
|
+
|
|
122
|
+
let status = StatusCode::from_u16(upstream_res.status().as_u16())
|
|
123
|
+
.unwrap_or(StatusCode::BAD_GATEWAY);
|
|
124
|
+
|
|
125
|
+
let mut headers = HeaderMap::new();
|
|
126
|
+
if let Some(content_type) = upstream_res.headers().get(header::CONTENT_TYPE) {
|
|
127
|
+
headers.insert(header::CONTENT_TYPE, content_type.clone());
|
|
128
|
+
}
|
|
129
|
+
if let Some(cache_control) = upstream_res.headers().get(header::CACHE_CONTROL) {
|
|
130
|
+
headers.insert(header::CACHE_CONTROL, cache_control.clone());
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Direct zero-copy pipe: bytes flow from network socket to client socket
|
|
134
|
+
let body = Body::from_stream(upstream_res.bytes_stream());
|
|
135
|
+
|
|
136
|
+
Ok((status, headers, body).into_response())
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
## 5. Security & Stability Checklist
|
|
143
|
+
|
|
144
|
+
1. Is `DefaultBodyLimit` applied globally across all Axum routes?
|
|
145
|
+
2. Are all third-party HTTP streams guarded with a byte accumulator ceiling?
|
|
146
|
+
3. Does proxying use `Body::from_stream` rather than buffering in a `Vec<u8>`?
|
|
147
|
+
4. Are oversized responses aborted immediately at the TCP stream level without downloading remainder bytes?
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Bounds Check Elimination (BCE) and Zero-Cost Memory Patterns
|
|
2
|
+
|
|
3
|
+
Rust guarantees memory safety by verifying slice boundaries at runtime. In latency-sensitive hot loops (such as byte parsing, cryptography, hashing, and numeric calculation), runtime bounds checking introduces hidden conditional branches that prevent the compiler from generating vectorized SIMD instructions.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Bounds Check Elimination (BCE)
|
|
8
|
+
|
|
9
|
+
### The Anti-Pattern
|
|
10
|
+
Indexed iteration forces Rust to generate branch checks on every loop iteration:
|
|
11
|
+
|
|
12
|
+
```rust
|
|
13
|
+
// ANTI-PATTERN: Emits bounds check on every index access
|
|
14
|
+
pub fn sum_pairs(a: &[f64], b: &[f64]) -> f64 {
|
|
15
|
+
let mut sum = 0.0;
|
|
16
|
+
for i in 0..a.len() {
|
|
17
|
+
sum += a[i] * b[i]; // Rust generates a panic branch check for b[i]!
|
|
18
|
+
}
|
|
19
|
+
sum
|
|
20
|
+
}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### The Solution: Length-Proving Iterators
|
|
24
|
+
Using `.zip()`, `.chunks_exact()`, or a single up-front slice assertion allows LLVM to mathematically prove that bounds cannot be exceeded, stripping all runtime checks:
|
|
25
|
+
|
|
26
|
+
```rust
|
|
27
|
+
// OPTIMIZED: Zero bounds checks emitted in assembly
|
|
28
|
+
pub fn sum_pairs_bce(a: &[f64], b: &[f64]) -> f64 {
|
|
29
|
+
// Proves length to LLVM up front
|
|
30
|
+
assert!(a.len() == b.len(), "Slices must have equal lengths");
|
|
31
|
+
|
|
32
|
+
a.iter()
|
|
33
|
+
.zip(b.iter())
|
|
34
|
+
.map(|(&x, &y)| x * y)
|
|
35
|
+
.sum()
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Chunked Vectorization with `.chunks_exact()`
|
|
40
|
+
When processing fixed-size byte groups, `.chunks_exact()` guarantees slice sizes to LLVM at compile time:
|
|
41
|
+
|
|
42
|
+
```rust
|
|
43
|
+
pub fn process_4byte_words(bytes: &[u8]) {
|
|
44
|
+
let chunks = bytes.chunks_exact(4);
|
|
45
|
+
let remainder = chunks.remainder();
|
|
46
|
+
|
|
47
|
+
for chunk in chunks {
|
|
48
|
+
// LLVM knows chunk is EXACTLY 4 bytes: 0 runtime bounds checks!
|
|
49
|
+
let word = u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
|
|
50
|
+
process_word(word);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
for &byte in remainder {
|
|
54
|
+
process_single_byte(byte);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## 2. Eliminating the "Zeroing Tax" with `MaybeUninit`
|
|
62
|
+
|
|
63
|
+
Writing `let mut buffer = vec![0u8; 65536];` forces the CPU to write 65,536 zero bytes to RAM. When the buffer is immediately passed to a socket or disk read (`stream.read(&mut buffer)`), those zeroes are overwritten within microseconds, wasting CPU bandwidth.
|
|
64
|
+
|
|
65
|
+
### Use Uninitialized Capacity Safely
|
|
66
|
+
Use `bytes::BytesMut` or `std::mem::MaybeUninit` to allocate without zeroing memory:
|
|
67
|
+
|
|
68
|
+
```rust
|
|
69
|
+
use bytes::BytesMut;
|
|
70
|
+
|
|
71
|
+
pub fn allocate_socket_read_buffer(capacity: usize) -> BytesMut {
|
|
72
|
+
// Allocates memory without paying the zero-initialization tax
|
|
73
|
+
BytesMut::with_capacity(capacity)
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## 3. Extracting Fields with `std::mem::take` and `std::mem::replace`
|
|
80
|
+
|
|
81
|
+
When transitioning state in an `&mut self` method, cloning fields to satisfy the borrow checker wastes heap allocations:
|
|
82
|
+
|
|
83
|
+
```rust
|
|
84
|
+
pub struct Session {
|
|
85
|
+
pub buffer: Vec<u8>,
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
impl Session {
|
|
89
|
+
pub fn flush_and_reset(&mut self) -> Vec<u8> {
|
|
90
|
+
// std::mem::take replaces self.buffer with Vec::new() (0 alloc)
|
|
91
|
+
// and returns the original buffer with its allocated capacity!
|
|
92
|
+
std::mem::take(&mut self.buffer)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
---
|
|
98
|
+
|
|
99
|
+
## 4. Fixed-Capacity Stack Arrays with `ArrayVec`
|
|
100
|
+
|
|
101
|
+
When a vector has a known maximum size (e.g. up to 16 tags or 8 IP addresses), do not allocate on the heap. Use `ArrayVec` to keep all elements directly on the stack:
|
|
102
|
+
|
|
103
|
+
```rust
|
|
104
|
+
use arrayvec::ArrayVec;
|
|
105
|
+
|
|
106
|
+
pub fn collect_local_headers() -> ArrayVec<&'static str, 8> {
|
|
107
|
+
let mut headers = ArrayVec::<&'static str, 8>::new();
|
|
108
|
+
headers.push("Content-Type");
|
|
109
|
+
headers.push("Authorization");
|
|
110
|
+
// Memory is 100% stack-allocated: 0 heap pointer indirection
|
|
111
|
+
headers
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## 5. Production Checklist
|
|
118
|
+
|
|
119
|
+
- [ ] Replaced indexed slice access (`slice[i]`) with `.iter()`, `.zip()`, or `.chunks_exact()`.
|
|
120
|
+
- [ ] Eliminated zero-fill buffers (`vec![0; N]`) on network/file read targets.
|
|
121
|
+
- [ ] Used `std::mem::take` or `std::mem::replace` to avoid cloning during struct state shifts.
|
|
122
|
+
- [ ] Substituted small fixed-bound heap vectors with stack-allocated `ArrayVec`.
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# Cache-Line Alignment, Struct Layout & False Sharing Elimination
|
|
2
|
+
|
|
3
|
+
In high-concurrency systems running on multi-core processors, extreme efficiency depends on how hardware interacts with CPU caches (L1/L2/L3) and memory buses. Poor struct design causes two major performance drains:
|
|
4
|
+
1. **Struct Padding Bloat**: Memory wasted on unused alignment bytes across millions of cache/struct instances.
|
|
5
|
+
2. **False Sharing (Cache-Line Bouncing)**: Independent CPU cores invalidating each other's L1 cache lines when mutating adjacent variables, collapsing multi-core scalability by up to 80%.
|
|
6
|
+
|
|
7
|
+
This playbook details the hardware-level layout optimizations needed to eliminate these bottlenecks.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## 1. Struct Field Ordering & Padding Elimination
|
|
12
|
+
|
|
13
|
+
Rust aligns struct fields according to their natural boundary (e.g., an 8-byte `u64` must reside at a memory address divisible by 8). When fields of varying sizes are declared haphazardly, the compiler must insert invisible **padding bytes**.
|
|
14
|
+
|
|
15
|
+
### Bad vs Optimal Layout:
|
|
16
|
+
```rust
|
|
17
|
+
// ❌ UNOPTIMIZED: Consumes 24 bytes due to padding gaps
|
|
18
|
+
pub struct UnoptimizedRecord {
|
|
19
|
+
pub active: bool, // 1 byte + 7 BYTES PADDING
|
|
20
|
+
pub id: u64, // 8 bytes
|
|
21
|
+
pub flags: u8, // 1 byte + 7 BYTES PADDING
|
|
22
|
+
} // Total: 24 bytes!
|
|
23
|
+
|
|
24
|
+
// ✅ OPTIMIZED: Consumes 16 bytes (33% memory reduction)
|
|
25
|
+
pub struct OptimizedRecord {
|
|
26
|
+
pub id: u64, // 8 bytes (offset 0)
|
|
27
|
+
pub active: bool, // 1 byte (offset 8)
|
|
28
|
+
pub flags: u8, // 1 byte (offset 9)
|
|
29
|
+
// + 6 bytes trailing padding (offset 10..16)
|
|
30
|
+
} // Total: 16 bytes!
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
If an in-memory cache stores 1,000,000 items, the unoptimized layout wastes **8 Megabytes of RAM** entirely on dead padding bytes.
|
|
34
|
+
|
|
35
|
+
### The Struct Ordering Rule
|
|
36
|
+
Always declare struct fields in descending order of alignment size:
|
|
37
|
+
1. **8-byte types**: `u64`, `i64`, `f64`, pointers, `usize`, `Box<T>`, `Arc<T>`
|
|
38
|
+
2. **4-byte types**: `u32`, `i32`, `f32`, `char`
|
|
39
|
+
3. **2-byte types**: `u16`, `i16`
|
|
40
|
+
4. **1-byte types**: `u8`, `i8`, `bool`
|
|
41
|
+
5. **Zero-sized types**: `PhantomData<T>`
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## 2. Eliminating Multi-Threaded False Sharing
|
|
46
|
+
|
|
47
|
+
Modern 64-bit processors (x86_64 and ARM64) do not fetch single bytes from RAM; they fetch **64-byte cache lines**.
|
|
48
|
+
|
|
49
|
+
When two threads running on Core 0 and Core 1 update two independent atomic counters located within the same 64-byte cache line:
|
|
50
|
+
```text
|
|
51
|
+
[ Core 0: writes counter_a ] ---> [ 64-Byte Cache Line ] <--- [ Core 1: writes counter_b ]
|
|
52
|
+
|
|
|
53
|
+
💥 CACHE INVALIDATION STORM (False Sharing)
|
|
54
|
+
Both cores fight over ownership of the single 64-byte line!
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Throughput plummets as CPU cores stall waiting for memory bus synchronization.
|
|
58
|
+
|
|
59
|
+
### The Fix: `#[repr(align(64))]`
|
|
60
|
+
|
|
61
|
+
Pad hot, concurrently mutated variables so that each variable resides on its own dedicated 64-byte cache line:
|
|
62
|
+
|
|
63
|
+
```rust
|
|
64
|
+
use std::sync::atomic::{AtomicU64, Ordering};
|
|
65
|
+
|
|
66
|
+
// Force compiler to align struct to a full 64-byte hardware cache line boundary
|
|
67
|
+
#[repr(align(64))]
|
|
68
|
+
pub struct CachePaddedCounter {
|
|
69
|
+
pub value: AtomicU64,
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
impl CachePaddedCounter {
|
|
73
|
+
pub const fn new(initial: u64) -> Self {
|
|
74
|
+
Self {
|
|
75
|
+
value: AtomicU64::new(initial),
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Multi-worker telemetry struct immune to false sharing
|
|
81
|
+
pub struct WorkerStats {
|
|
82
|
+
// Each worker counter is isolated on its own independent cache line
|
|
83
|
+
pub worker_0_processed: CachePaddedCounter,
|
|
84
|
+
pub worker_1_processed: CachePaddedCounter,
|
|
85
|
+
pub worker_2_processed: CachePaddedCounter,
|
|
86
|
+
pub worker_3_processed: CachePaddedCounter,
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
impl WorkerStats {
|
|
90
|
+
pub fn record_job(&self, worker_id: usize) {
|
|
91
|
+
match worker_id {
|
|
92
|
+
0 => self.worker_0_processed.value.fetch_add(1, Ordering::Relaxed),
|
|
93
|
+
1 => self.worker_1_processed.value.fetch_add(1, Ordering::Relaxed),
|
|
94
|
+
2 => self.worker_2_processed.value.fetch_add(1, Ordering::Relaxed),
|
|
95
|
+
3 => self.worker_3_processed.value.fetch_add(1, Ordering::Relaxed),
|
|
96
|
+
_ => {}
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 3. Representation Attributes Reference
|
|
105
|
+
|
|
106
|
+
| Attribute | Purpose | Safe in Production? |
|
|
107
|
+
|---|---|---|
|
|
108
|
+
| `#[repr(Rust)]` | Default. Compiler may reorder fields arbitrarily to minimize padding. | **YES** |
|
|
109
|
+
| `#[repr(C)]` | Enforces exact C-ABI layout and declaration order. Essential for FFI or exact struct layout audits. | **YES** |
|
|
110
|
+
| `#[repr(transparent)]` | Guarantees single-field struct has identical memory layout and ABI as its inner type (Newtype pattern). | **YES** |
|
|
111
|
+
| `#[repr(align(N))]` | Sets minimum alignment boundary (e.g., `align(64)` for cache lines). | **YES** |
|
|
112
|
+
| `#[repr(packed)]` | Removes all padding bytes. | **CAUTION**: Unaligned field access causes CPU hardware faults or severe instruction penalties on ARM. Avoid unless required by hardware protocols. |
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## 4. Hardware Alignment Checklist
|
|
117
|
+
|
|
118
|
+
1. Are high-volume cached structs ordered from largest alignment (8B) to smallest (1B)?
|
|
119
|
+
2. Has `std::mem::size_of::<T>()` been audited against theoretical minimum field sizes?
|
|
120
|
+
3. Are multi-threaded hot atomic counters padded to 64 bytes using `#[repr(align(64))]`?
|
|
121
|
+
4. Are `Newtype` wrappers marked with `#[repr(transparent)]`?
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# Compiler Niche Optimizations and Static Size Assertions
|
|
2
|
+
|
|
3
|
+
Memory bloat often occurs invisibly inside struct definitions and enum layouts. Adding a single field or choosing primitive types naively can double a struct's memory footprint due to alignment padding, wasting tens or hundreds of megabytes across large collections.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Niche Optimization via `NonZero*`
|
|
8
|
+
|
|
9
|
+
In standard Rust, wrapping a primitive type inside `Option<T>` requires an enum discriminant tag:
|
|
10
|
+
|
|
11
|
+
```rust
|
|
12
|
+
use std::mem::size_of;
|
|
13
|
+
|
|
14
|
+
// Standard u64: 8 bytes
|
|
15
|
+
// Option<u64>: 16 bytes! (1 byte tag + 7 bytes alignment padding)
|
|
16
|
+
assert_eq!(size_of::<u64>(), 8);
|
|
17
|
+
assert_eq!(size_of::<Option<u64>>(), 16); // 100% space bloat!
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
If an array stores 10,000,000 instances of `Option<u64>`, **80 megabytes of memory is wasted on empty padding**.
|
|
21
|
+
|
|
22
|
+
### The Solution: Unlock the Niche
|
|
23
|
+
When zero is an invalid or unrepresented state (e.g. database IDs, non-zero counts, socket file descriptors), use `std::num::NonZeroU64`. The Rust compiler uses the zero bit-pattern (`0x00...`) to represent `None`, requiring **zero extra bytes**:
|
|
24
|
+
|
|
25
|
+
```rust
|
|
26
|
+
use std::num::NonZeroU64;
|
|
27
|
+
use std::mem::size_of;
|
|
28
|
+
|
|
29
|
+
// Option<NonZeroU64> is EXACTLY 8 bytes (0 byte tag overhead)
|
|
30
|
+
assert_eq!(size_of::<Option<NonZeroU64>>(), 8);
|
|
31
|
+
|
|
32
|
+
#[derive(Clone, Copy)]
|
|
33
|
+
pub struct AccountRecord {
|
|
34
|
+
pub account_id: NonZeroU64,
|
|
35
|
+
pub secondary_id: Option<NonZeroU64>, // 8 bytes instead of 16
|
|
36
|
+
pub balance: u64,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Total struct size: 24 bytes (instead of 32 or 40 bytes)
|
|
40
|
+
const _: () = assert!(size_of::<AccountRecord>() == 24);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## 2. Compile-Time Size Assertions (`const _: () = assert!(...)`)
|
|
46
|
+
|
|
47
|
+
When teams evolve a codebase, someone may unintentionally add a field (e.g. a `String` or `Vec`) to a core event or packet struct. Static size assertions cause the build to fail immediately in CI if a struct exceeds its memory budget:
|
|
48
|
+
|
|
49
|
+
```rust
|
|
50
|
+
pub struct TelemetryPacket {
|
|
51
|
+
pub timestamp: u64,
|
|
52
|
+
pub metric_id: u32,
|
|
53
|
+
pub value: f32,
|
|
54
|
+
pub flags: u8,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Compile error triggers if any field addition or reordering changes the size!
|
|
58
|
+
const _: () = assert!(
|
|
59
|
+
std::mem::size_of::<TelemetryPacket>() == 24,
|
|
60
|
+
"TelemetryPacket size changed! Verify memory impact before updating assertion."
|
|
61
|
+
);
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
## 3. Allocation Buffer Reuse via `.clone_from()`
|
|
67
|
+
|
|
68
|
+
Calling `dest = src.clone()` inside loops drops `dest`'s allocated heap memory and requests a brand new allocation from the OS allocator:
|
|
69
|
+
|
|
70
|
+
```rust
|
|
71
|
+
// ANTI-PATTERN: Allocator thrashing inside loops
|
|
72
|
+
let mut buffer = String::with_capacity(1024);
|
|
73
|
+
for record in records {
|
|
74
|
+
buffer = record.data.clone(); // Drops old buffer, allocates new memory!
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// BEST PRACTICE: Reuses existing capacity with 0 heap allocations
|
|
78
|
+
let mut buffer = String::with_capacity(1024);
|
|
79
|
+
for record in records {
|
|
80
|
+
buffer.clone_from(&record.data); // Copies bytes directly into existing capacity
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## 4. `Box<[T]>` (16 Bytes) vs `Vec<T>` (24 Bytes)
|
|
87
|
+
|
|
88
|
+
`Vec<T>` maintains three words on the stack: `ptr` (pointer to heap), `cap` (capacity), and `len` (current length) = 24 bytes on 64-bit platforms.
|
|
89
|
+
|
|
90
|
+
When a collection is immutable and will not grow further (e.g., config tables, parsed query tokens, static payloads), convert it to a boxed slice via `.into_boxed_slice()`:
|
|
91
|
+
|
|
92
|
+
```rust
|
|
93
|
+
use std::mem::size_of;
|
|
94
|
+
|
|
95
|
+
assert_eq!(size_of::<Vec<u8>>(), 24);
|
|
96
|
+
assert_eq!(size_of::<Box<[u8]>>(), 16); // Saves 8 bytes per slice!
|
|
97
|
+
|
|
98
|
+
pub struct ImmutableConfig {
|
|
99
|
+
pub name: Box<str>, // 16 bytes (vs 24-byte String)
|
|
100
|
+
pub allowed_ips: Box<[u32]>, // 16 bytes (vs 24-byte Vec<u32>)
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
## 5. `#[cold]` CPU Instruction Cache Isolation
|
|
107
|
+
|
|
108
|
+
Errors and emergency fallbacks execute infrequently. Marking fallback functions with `#[cold]` instructs LLVM to relocate their compiled machine code out of the CPU's primary L1 instruction cache lines, keeping the CPU cache clear for the hot path:
|
|
109
|
+
|
|
110
|
+
```rust
|
|
111
|
+
#[cold]
|
|
112
|
+
#[inline(never)]
|
|
113
|
+
fn handle_unlikely_reconnection_error(err: std::io::Error) {
|
|
114
|
+
tracing::error!("Rare reconnection error: {err}");
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
## 6. Production Checklist
|
|
121
|
+
|
|
122
|
+
- [ ] Replaced `Option<u32/u64>` with `Option<NonZeroU32/NonZeroU64>` across core record types.
|
|
123
|
+
- [ ] Added `const _: () = assert!(size_of::<T>() == N)` to all structs stored in millions of instances.
|
|
124
|
+
- [ ] Switched loop assignments to `.clone_from()` to prevent allocator thrashing.
|
|
125
|
+
- [ ] Converted immutable vectors and strings to `Box<[T]>` and `Box<str>`.
|
|
126
|
+
- [ ] Tagged rare error recovery routines with `#[cold]`.
|