@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,108 @@
|
|
|
1
|
+
# SIMD Vectorization and Hardware-Accelerated Byte Operations
|
|
2
|
+
|
|
3
|
+
When processing high-volume text, network byte streams, binary protocols, or numeric arrays, standard scalar loops (`for b in slice`) underutilize modern CPU architectures. Modern x86_64 and ARM64 CPUs feature 128-bit, 256-bit, and 512-bit vector registers (AVX2, AVX-512, NEON) capable of evaluating 16 to 64 bytes per CPU cycle without allocating heap memory.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Zero-Allocation Fast Delimiter Searching with `memchr`
|
|
8
|
+
|
|
9
|
+
Standard byte scanning (`slice.iter().position(|&b| b == b'\n')`) checks bytes one by one. The `memchr` crate uses hand-tuned assembly and SIMD vector registers to scan 32 to 64 bytes in a single instruction:
|
|
10
|
+
|
|
11
|
+
```rust
|
|
12
|
+
use memchr::{memchr, memchr2, memmem};
|
|
13
|
+
|
|
14
|
+
pub fn find_http_header_end(raw_http: &[u8]) -> Option<usize> {
|
|
15
|
+
// Searches for \r\n\r\n using vectorized two-way substring matching
|
|
16
|
+
memmem::find(raw_http, b"\r\n\r\n")
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
pub fn parse_line_endings_fast(buffer: &[u8]) -> Vec<&[u8]> {
|
|
20
|
+
let mut lines = Vec::new();
|
|
21
|
+
let mut start = 0;
|
|
22
|
+
|
|
23
|
+
// memchr scans up to 64 bytes per instruction via AVX-512 / AVX2 / NEON
|
|
24
|
+
while let Some(pos) = memchr(b'\n', &buffer[start..]) {
|
|
25
|
+
let end = start + pos;
|
|
26
|
+
lines.push(&buffer[start..end]);
|
|
27
|
+
start = end + 1;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
if start < buffer.len() {
|
|
31
|
+
lines.push(&buffer[start..]);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
lines
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## 2. High-Throughput UTF-8 Validation with `simdutf8`
|
|
41
|
+
|
|
42
|
+
Standard `std::str::from_utf8` processes scalar byte sequences with branching state tables. The `simdutf8` crate accelerates UTF-8 validation up to 20 GB/s on modern CPUs by evaluating byte ranges in parallel:
|
|
43
|
+
|
|
44
|
+
```rust
|
|
45
|
+
use simdutf8::basic::from_utf8;
|
|
46
|
+
|
|
47
|
+
pub fn validate_request_payload_fast(raw_bytes: &[u8]) -> Result<&str, simdutf8::basic::Utf8Error> {
|
|
48
|
+
// Evaluates 16/32 bytes simultaneously using AVX2 or ARM NEON registers
|
|
49
|
+
from_utf8(raw_bytes)
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## 3. Portable SIMD for Numeric & Transformation Pipelines
|
|
56
|
+
|
|
57
|
+
When computing metrics, parsing delimited numbers, or masking WebSocket frame payloads, use portable SIMD or chunked vector intrinsics:
|
|
58
|
+
|
|
59
|
+
```rust
|
|
60
|
+
// Fast WebSocket frame unmasking (XOR 4-byte mask over arbitrary byte buffer)
|
|
61
|
+
pub fn unmask_websocket_payload(payload: &mut [u8], mask: [u8; 4]) {
|
|
62
|
+
// Construct 32-bit repeated pattern
|
|
63
|
+
let mask_u32 = u32::from_ne_bytes(mask);
|
|
64
|
+
let mask_u64 = ((mask_u32 as u64) << 32) | (mask_u32 as u64);
|
|
65
|
+
|
|
66
|
+
let (prefix, middle, suffix) = unsafe { payload.align_to_mut::<u64>() };
|
|
67
|
+
|
|
68
|
+
// 1. Process unaligned prefix scalar bytes
|
|
69
|
+
let mut mask_idx = 0;
|
|
70
|
+
for byte in prefix.iter_mut() {
|
|
71
|
+
*byte ^= mask[mask_idx % 4];
|
|
72
|
+
mask_idx += 1;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 2. Process aligned chunks 8 bytes at a time (64 bits per CPU op)
|
|
76
|
+
for word in middle.iter_mut() {
|
|
77
|
+
*word ^= mask_u64;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// 3. Process remaining scalar trailing bytes
|
|
81
|
+
mask_idx = (payload.len() - suffix.len()) % 4;
|
|
82
|
+
for byte in suffix.iter_mut() {
|
|
83
|
+
*byte ^= mask[mask_idx % 4];
|
|
84
|
+
mask_idx += 1;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## 4. Compiler Target Flags for Vectorization
|
|
92
|
+
|
|
93
|
+
Ensure the Rust compiler targets modern instruction sets in release builds by adding CPU target flags to `.cargo/config.toml`:
|
|
94
|
+
|
|
95
|
+
```toml
|
|
96
|
+
[target.'cfg(all(target_arch = "x86_64", target_os = "linux"))']
|
|
97
|
+
rustflags = ["-C", "target-cpu=x86-64-v3"] # Enables AVX, AVX2, BMI2, FMA
|
|
98
|
+
```
|
|
99
|
+
> Setting `target-cpu=x86-64-v3` enables the compiler to automatically vectorize loops into AVX2 instructions across your entire binary without writing manual assembly.
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## 5. Production Checklist
|
|
104
|
+
|
|
105
|
+
- [ ] Replaced scalar `.position()` with `memchr` or `memmem` on packet/string slicing.
|
|
106
|
+
- [ ] Switched high-throughput UTF-8 parsing to `simdutf8`.
|
|
107
|
+
- [ ] Configured `target-cpu=x86-64-v3` (or equivalent microarchitecture) in `.cargo/config.toml` for container deployment.
|
|
108
|
+
- [ ] Replaced scalar bit-twiddling on bulk payloads with 64-bit or vector aligned word slicing.
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# SQLx and Database Connection Pool Memory Optimization
|
|
2
|
+
|
|
3
|
+
Database queries and unmanaged connection pools are among the most frequent sources of sudden RSS spikes and out-of-memory (OOM) kills in long-running Rust backend services.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. The `.fetch_all()` Heap Explosion Trap
|
|
8
|
+
|
|
9
|
+
### The Problem
|
|
10
|
+
Calling `.fetch_all()` buffers the entire SQL result set into memory before deserializing rows into your target structs. When querying large tables, batch jobs, or audit logs, a single query can pull 50,000 to 500,000 rows, consuming hundreds of megabytes or gigabytes of heap RAM:
|
|
11
|
+
|
|
12
|
+
```rust
|
|
13
|
+
// ANTI-PATTERN: Pulls all 100,000 rows into heap memory at once
|
|
14
|
+
pub async fn export_users(pool: &PgPool) -> Result<Vec<User>, sqlx::Error> {
|
|
15
|
+
sqlx::query_as!(User, "SELECT id, email, created_at FROM users")
|
|
16
|
+
.fetch_all(pool) // DANGER: Unbounded heap allocation!
|
|
17
|
+
.await
|
|
18
|
+
}
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
### The Solution: Streaming with `.fetch()`
|
|
22
|
+
Use `.fetch()` to stream rows one by one asynchronously via `futures_util::StreamExt`. Memory consumption remains completely flat (<5MB) regardless of whether the table contains 1,000 rows or 10,000,000 rows.
|
|
23
|
+
|
|
24
|
+
```rust
|
|
25
|
+
use futures_util::StreamExt;
|
|
26
|
+
use sqlx::PgPool;
|
|
27
|
+
|
|
28
|
+
pub async fn stream_users_to_sink<W>(
|
|
29
|
+
pool: &PgPool,
|
|
30
|
+
mut sink: W,
|
|
31
|
+
) -> Result<(), Box<dyn std::error::Error>>
|
|
32
|
+
where
|
|
33
|
+
W: tokio::io::AsyncWrite + Unpin,
|
|
34
|
+
{
|
|
35
|
+
let mut rows = sqlx::query_as!(User, "SELECT id, email, created_at FROM users")
|
|
36
|
+
.fetch(pool); // Streams row-by-row with minimal buffer
|
|
37
|
+
|
|
38
|
+
while let Some(user_res) = rows.next().await {
|
|
39
|
+
let user = user_res?;
|
|
40
|
+
// Process or serialize individual user immediately
|
|
41
|
+
tokio::io::AsyncWriteExt::write_all(
|
|
42
|
+
&mut sink,
|
|
43
|
+
format!("{},{}\n", user.id, user.email).as_bytes(),
|
|
44
|
+
).await?;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
Ok(())
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## 2. Bounded Chunked Batching
|
|
54
|
+
|
|
55
|
+
When streaming individual rows causes excessive I/O transactions, batch them into strictly bounded chunks using `itertools` or custom slice chunking without reallocating vectors:
|
|
56
|
+
|
|
57
|
+
```rust
|
|
58
|
+
use futures_util::StreamExt;
|
|
59
|
+
use sqlx::PgPool;
|
|
60
|
+
|
|
61
|
+
pub async fn process_in_bounded_batches(
|
|
62
|
+
pool: &PgPool,
|
|
63
|
+
batch_size: usize,
|
|
64
|
+
) -> Result<(), sqlx::Error> {
|
|
65
|
+
let mut stream = sqlx::query_as!(User, "SELECT id, email, created_at FROM users")
|
|
66
|
+
.fetch(pool);
|
|
67
|
+
|
|
68
|
+
let mut batch = Vec::with_capacity(batch_size);
|
|
69
|
+
|
|
70
|
+
while let Some(row) = stream.next().await {
|
|
71
|
+
batch.push(row?);
|
|
72
|
+
if batch.len() >= batch_size {
|
|
73
|
+
flush_batch(&batch).await;
|
|
74
|
+
batch.clear(); // Retains allocated capacity, 0 re-allocations
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if !batch.is_empty() {
|
|
79
|
+
flush_batch(&batch).await;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
Ok(())
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async fn flush_batch(batch: &[User]) {
|
|
86
|
+
// Process bounded batch in-place
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## 3. Database Connection Pool Sizing Formula
|
|
93
|
+
|
|
94
|
+
### Sizing Myth vs Reality
|
|
95
|
+
Developers often assign `max_connections = 50` or `100` per instance. In a Kubernetes deployment with 20 pods, 20 pods × 100 connections = 2,000 connections to PostgreSQL. PostgreSQL forks a backend process for every connection, consuming 10–20MB of server RAM per idle connection and thrashing CPU cache.
|
|
96
|
+
|
|
97
|
+
### The PostgreSQL Optimal Sizing Formula
|
|
98
|
+
```text
|
|
99
|
+
max_connections = (cpu_cores * 2) + effective_spindle_count
|
|
100
|
+
```
|
|
101
|
+
For modern cloud SSD instances:
|
|
102
|
+
```text
|
|
103
|
+
Pool Size = (Available CPU Cores * 2) + 1
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
For a 4-core container:
|
|
107
|
+
- Set `max_connections(10)`
|
|
108
|
+
- Set `min_connections(2)`
|
|
109
|
+
- Configure aggressive idle reap timeouts:
|
|
110
|
+
|
|
111
|
+
```rust
|
|
112
|
+
use sqlx::postgres::{PgPoolOptions, PgConnectOptions};
|
|
113
|
+
use std::time::Duration;
|
|
114
|
+
|
|
115
|
+
pub async fn create_optimized_pool(database_url: &str) -> Result<sqlx::PgPool, sqlx::Error> {
|
|
116
|
+
PgPoolOptions::new()
|
|
117
|
+
.max_connections(10) // 10 connections can saturate 10,000 req/s in async Rust
|
|
118
|
+
.min_connections(2)
|
|
119
|
+
.acquire_timeout(Duration::from_secs(3))
|
|
120
|
+
.idle_timeout(Duration::from_secs(60))
|
|
121
|
+
.max_lifetime(Duration::from_secs(1800))
|
|
122
|
+
.connect(database_url)
|
|
123
|
+
.await
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
## 4. Prepared Statement Cache Containment
|
|
130
|
+
|
|
131
|
+
By default, SQLx caches prepared statements on each connection. If your application constructs dynamic SQL queries with variable clauses or filters, the statement cache can grow unboundedly, leaking memory over days of runtime.
|
|
132
|
+
|
|
133
|
+
### Enforce Statement Cache Limits
|
|
134
|
+
```rust
|
|
135
|
+
use sqlx::postgres::PgConnectOptions;
|
|
136
|
+
use std::str::FromStr;
|
|
137
|
+
|
|
138
|
+
pub fn configure_connect_options(database_url: &str) -> Result<PgConnectOptions, sqlx::Error> {
|
|
139
|
+
let mut opts = PgConnectOptions::from_str(database_url)?;
|
|
140
|
+
|
|
141
|
+
// Limit prepared statement cache per connection to prevent unbounded growth
|
|
142
|
+
opts = opts.statement_cache_capacity(256);
|
|
143
|
+
|
|
144
|
+
Ok(opts)
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
## 5. Production Checklist
|
|
151
|
+
|
|
152
|
+
- [ ] Replaced all `.fetch_all()` calls on unbounded tables with `.fetch()` streaming.
|
|
153
|
+
- [ ] Bounded chunk buffers use `.clear()` instead of re-instantiating `Vec::new()`.
|
|
154
|
+
- [ ] Database pool `max_connections` is capped according to core counts (typically 5–15 per pod).
|
|
155
|
+
- [ ] Set `acquire_timeout` to fail fast (<3s) rather than letting Tokio worker tasks queue up indefinitely.
|
|
156
|
+
- [ ] Hardened `statement_cache_capacity` on dynamic SQL workloads.
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
# Stack Inlining & Heap Allocator Churn Elimination
|
|
2
|
+
|
|
3
|
+
In high-throughput services and scrapers, indiscriminate use of `String` and `Vec<T>` inside Data Transfer Objects (DTOs), ASTs, and cache models causes thousands of tiny heap allocations and deallocations per second. This triggers CPU L1/L2 cache misses, increases glibc arena fragmentation, and unnecessarily inflates process RSS.
|
|
4
|
+
|
|
5
|
+
This playbook establishes the **Zero-Allocation Type Discipline** required for sub-50MB RSS baseline operations.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. The Hidden Cost of `std::string::String`
|
|
10
|
+
|
|
11
|
+
A standard Rust `String` consumes:
|
|
12
|
+
- **24 bytes on the stack** (8-byte pointer, 8-byte length, 8-byte capacity).
|
|
13
|
+
- **A separate dynamic heap allocation** storing the actual character bytes, often over-allocated due to growth factor heuristics.
|
|
14
|
+
|
|
15
|
+
```rust
|
|
16
|
+
// ❌ WRONG: Naive Model with 5 Heap Allocations per record
|
|
17
|
+
pub struct ItemRecord {
|
|
18
|
+
pub id: String, // Heap alloc for 8-character ID
|
|
19
|
+
pub title: String, // Heap alloc
|
|
20
|
+
pub duration: String, // Heap alloc for "14:20" (5 bytes!)
|
|
21
|
+
pub views: String, // Heap alloc for "1.4M" (4 bytes!)
|
|
22
|
+
pub status: String, // Heap alloc for "active" (6 bytes!)
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Under 1,000 requests per second returning 50 items each, this naive struct generates **250,000 heap allocations per second**.
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## 2. Inlining Short Strings with `compact_str`
|
|
31
|
+
|
|
32
|
+
For strings that are typically $\le 24$ bytes on 64-bit systems (UUIDs, IDs, durations, ratings, status codes, country codes), use **`compact_str::CompactString`**.
|
|
33
|
+
|
|
34
|
+
- **$\le 24$ bytes**: Stored **100% on the stack** directly inside the 24-byte footprint. **Zero heap allocation**.
|
|
35
|
+
- **$> 24$ bytes**: Gracefully falls back to a single heap allocation.
|
|
36
|
+
|
|
37
|
+
```toml
|
|
38
|
+
# Cargo.toml
|
|
39
|
+
[dependencies]
|
|
40
|
+
compact_str = { version = "0.8", features = ["serde"] }
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
```rust
|
|
44
|
+
// ✅ CORRECT: Zero-Heap Allocation for short metadata
|
|
45
|
+
use compact_str::CompactString;
|
|
46
|
+
|
|
47
|
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
|
48
|
+
pub struct ItemRecord {
|
|
49
|
+
pub id: CompactString, // 0 heap alloc (stored in stack)
|
|
50
|
+
pub duration: CompactString, // 0 heap alloc (stored in stack)
|
|
51
|
+
pub views: CompactString, // 0 heap alloc (stored in stack)
|
|
52
|
+
pub status: CompactString, // 0 heap alloc (stored in stack)
|
|
53
|
+
pub title: Box<str>, // Trimmed heap allocation (no excess capacity)
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## 3. Discarding Excess Capacity with `Box<str>`
|
|
60
|
+
|
|
61
|
+
When strings exceed 24 bytes and must live on the heap (such as article titles, descriptions, or URLs), never store them as `String` inside long-lived cache models or completed response records:
|
|
62
|
+
|
|
63
|
+
```rust
|
|
64
|
+
// ❌ String retains excess capacity buffer (24 bytes stack + heap buffer)
|
|
65
|
+
let title: String = parse_title();
|
|
66
|
+
|
|
67
|
+
// ✅ Box<str> shrinks stack size to 16 bytes (ptr + len) and shrinks heap to exact length
|
|
68
|
+
let title: Box<str> = parse_title().into_boxed_str();
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Memory Footprint Comparison:
|
|
72
|
+
| Type | Stack Size (64-bit) | Heap Allocation | Excess Capacity Kept? |
|
|
73
|
+
|---|---|---|---|
|
|
74
|
+
| `String` | 24 bytes | Heap | Yes (capacity padding) |
|
|
75
|
+
| `Box<str>` | 16 bytes | Heap | **No** (exact byte slice) |
|
|
76
|
+
| `CompactString` ($\le 24$B) | 24 bytes | **0 bytes** (inlined) | No |
|
|
77
|
+
| `Cow<'static, str>` | 24 bytes | **0 bytes** (if borrowed) | No |
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
81
|
+
## 4. Inlining Small Lists with `SmallVec`
|
|
82
|
+
|
|
83
|
+
Avoid allocating a `Vec` for small, bounded collections like tags, categories, or HTTP headers:
|
|
84
|
+
|
|
85
|
+
```toml
|
|
86
|
+
# Cargo.toml
|
|
87
|
+
[dependencies]
|
|
88
|
+
smallvec = { version = "1.13", features = ["serde"] }
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
```rust
|
|
92
|
+
use smallvec::SmallVec;
|
|
93
|
+
use compact_str::CompactString;
|
|
94
|
+
|
|
95
|
+
// Inlines up to 4 tags directly on the stack without allocating a Vec buffer
|
|
96
|
+
pub type InlineTags = SmallVec<[CompactString; 4]>;
|
|
97
|
+
|
|
98
|
+
#[derive(Debug, Clone, serde::Serialize)]
|
|
99
|
+
pub struct VideoMetadata {
|
|
100
|
+
pub id: CompactString,
|
|
101
|
+
pub title: Box<str>,
|
|
102
|
+
pub tags: InlineTags, // 0 heap allocations if <= 4 tags!
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## 5. Zero-Copy String Borrowing with `Cow<'a, str>`
|
|
109
|
+
|
|
110
|
+
When generating responses or transforming strings that may or may not need modification, use `std::borrow::Cow<'a, str>`:
|
|
111
|
+
|
|
112
|
+
```rust
|
|
113
|
+
use std::borrow::Cow;
|
|
114
|
+
|
|
115
|
+
pub fn normalize_slug(input: &str) -> Cow<'_, str> {
|
|
116
|
+
if input.contains(' ') {
|
|
117
|
+
// Only allocates heap when mutation is strictly necessary
|
|
118
|
+
Cow::Owned(input.replace(' ', "-"))
|
|
119
|
+
} else {
|
|
120
|
+
// Zero-allocation borrowed reference
|
|
121
|
+
Cow::Borrowed(input)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## 6. Checklist: Designing Memory-Optimal Structs
|
|
129
|
+
|
|
130
|
+
1. Are short strings ($\le 24$ bytes) typed as `CompactString`?
|
|
131
|
+
2. Are long immutable strings stored as `Box<str>` instead of `String`?
|
|
132
|
+
3. Are small collections ($\le 4$ items) stored as `SmallVec` instead of `Vec`?
|
|
133
|
+
4. Are constant headers or static error messages typed as `&'static str` or `Cow<'static, str>`?
|
|
134
|
+
5. Has `cargo check` verified that types serialize seamlessly with `serde`?
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# Streaming File I/O, Archival, and Compression
|
|
2
|
+
|
|
3
|
+
Loading entire files or large payloads into memory (`Vec<u8>`) during uploads, downloads, or report generation (CSV, JSON, Parquet) creates severe RSS spikes. Realizing extreme memory efficiency requires zero-copy streaming through chunked asynchronous buffers and streaming encoders.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. The In-Memory File Buffer Trap
|
|
8
|
+
|
|
9
|
+
### The Anti-Pattern
|
|
10
|
+
```rust
|
|
11
|
+
// ANTI-PATTERN: Loads entire 500MB file into heap memory
|
|
12
|
+
pub async fn download_and_compress(file_path: &str) -> Result<Vec<u8>, std::io::Error> {
|
|
13
|
+
let uncompressed = tokio::fs::read(file_path).await?; // 500MB RAM allocation!
|
|
14
|
+
let compressed = zstd::encode_all(&uncompressed[..], 3)?; // Another 100MB+ RAM allocation!
|
|
15
|
+
Ok(compressed)
|
|
16
|
+
}
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 2. Streaming Compression with `async-compression`
|
|
22
|
+
|
|
23
|
+
Pipe data chunk by chunk through `async-compression` using bounded chunk sizes:
|
|
24
|
+
|
|
25
|
+
```rust
|
|
26
|
+
use async_compression::tokio::write::ZstdEncoder;
|
|
27
|
+
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
|
28
|
+
|
|
29
|
+
pub async fn stream_compress_file(
|
|
30
|
+
src_path: &str,
|
|
31
|
+
dst_path: &str,
|
|
32
|
+
) -> Result<(), Box<dyn std::error::Error>> {
|
|
33
|
+
let mut reader = tokio::fs::File::open(src_path).await?;
|
|
34
|
+
let writer = tokio::fs::File::create(dst_path).await?;
|
|
35
|
+
|
|
36
|
+
// Wrap async writer in streaming Zstd encoder (level 3)
|
|
37
|
+
let mut encoder = ZstdEncoder::new(writer);
|
|
38
|
+
|
|
39
|
+
// Fixed 64KB stack/heap chunk buffer (constant memory usage)
|
|
40
|
+
let mut buffer = [0u8; 64 * 1024];
|
|
41
|
+
|
|
42
|
+
loop {
|
|
43
|
+
let bytes_read = reader.read(&mut buffer).await?;
|
|
44
|
+
if bytes_read == 0 {
|
|
45
|
+
break; // EOF
|
|
46
|
+
}
|
|
47
|
+
encoder.write_all(&buffer[..bytes_read]).await?;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
encoder.shutdown().await?;
|
|
51
|
+
Ok(())
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## 3. Streaming HTTP Responses in Axum
|
|
58
|
+
|
|
59
|
+
Stream large CSV exports or binary payloads directly from database/disk to the HTTP client using `axum::body::Body::from_stream`:
|
|
60
|
+
|
|
61
|
+
```rust
|
|
62
|
+
use axum::{
|
|
63
|
+
body::Body,
|
|
64
|
+
response::{IntoResponse, Response},
|
|
65
|
+
http::header,
|
|
66
|
+
};
|
|
67
|
+
use bytes::Bytes;
|
|
68
|
+
use tokio_stream::Stream;
|
|
69
|
+
|
|
70
|
+
pub async fn export_large_csv_stream() -> Response {
|
|
71
|
+
let stream = async_stream::stream! {
|
|
72
|
+
// Yield CSV headers
|
|
73
|
+
yield Ok::<Bytes, std::io::Error>(Bytes::from_static(b"id,username,email\n"));
|
|
74
|
+
|
|
75
|
+
// Yield rows chunk-by-chunk with flat memory
|
|
76
|
+
for i in 0..100_000 {
|
|
77
|
+
let row = format!("{i},user_{i},user_{i}@example.com\n");
|
|
78
|
+
yield Ok(Bytes::from(row));
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
Response::builder()
|
|
83
|
+
.header(header::CONTENT_TYPE, "text/csv")
|
|
84
|
+
.header(header::CONTENT_DISPOSITION, "attachment; filename=\"export.csv\"")
|
|
85
|
+
.body(Body::from_stream(stream))
|
|
86
|
+
.unwrap()
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## 4. Production Checklist
|
|
93
|
+
|
|
94
|
+
- [ ] Replaced all instances of `tokio::fs::read` on large files with `tokio::fs::File` and fixed chunk buffers (`64KB`).
|
|
95
|
+
- [ ] Switched in-memory compression (`zstd::encode_all`) to streaming encoders (`ZstdEncoder` / `GzipEncoder`).
|
|
96
|
+
- [ ] Configured HTTP download/export endpoints to return chunked `Body::from_stream`.
|
|
97
|
+
- [ ] Multipart file uploads stream directly to disk or S3 without intermediate RAM accumulation.
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
# Production Telemetry & Zero-Dependency Prometheus Metrics
|
|
2
|
+
|
|
3
|
+
Many Rust applications pull in bloated telemetry crates (`prometheus`, `opentelemetry`) that add megabytes to binary size and create subtle memory leaks through unconstrained label dimensions.
|
|
4
|
+
|
|
5
|
+
This playbook provides a **lightweight, zero-dependency Prometheus metrics exporter** that tracks OS process memory, Tokio scheduler health, event loop lag, and HTTP requests with strict cardinality containment.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. Single-Process PID-Filtered Sysinfo Collection
|
|
10
|
+
|
|
11
|
+
Calling `sysinfo::System::new_all()` or refreshing all system processes scans `/proc` for every PID on the machine, wasting CPU and memory.
|
|
12
|
+
|
|
13
|
+
**Best Practice**: Filter exclusively to the running process's own PID:
|
|
14
|
+
|
|
15
|
+
```rust
|
|
16
|
+
use std::sync::atomic::{AtomicU64, Ordering};
|
|
17
|
+
use std::time::Duration;
|
|
18
|
+
|
|
19
|
+
pub static METRICS_RSS: AtomicU64 = AtomicU64::new(0);
|
|
20
|
+
pub static METRICS_VSZ: AtomicU64 = AtomicU64::new(0);
|
|
21
|
+
pub static SYSTEM_TOTAL_MEM: AtomicU64 = AtomicU64::new(0);
|
|
22
|
+
pub static SYSTEM_USED_MEM: AtomicU64 = AtomicU64::new(0);
|
|
23
|
+
|
|
24
|
+
pub fn spawn_metrics_collector() {
|
|
25
|
+
tokio::spawn(async move {
|
|
26
|
+
let mut sys = sysinfo::System::new();
|
|
27
|
+
let pid = sysinfo::Pid::from(std::process::id() as usize);
|
|
28
|
+
|
|
29
|
+
loop {
|
|
30
|
+
tokio::time::sleep(Duration::from_secs(15)).await;
|
|
31
|
+
|
|
32
|
+
// 1. Actively trim freed glibc heap pages back to the Linux kernel
|
|
33
|
+
crate::util::trim_memory();
|
|
34
|
+
|
|
35
|
+
// 2. Measure Tokio Event Loop Lag
|
|
36
|
+
measure_event_loop_lag();
|
|
37
|
+
|
|
38
|
+
// 3. Refresh ONLY our own process, NOT the entire system process table!
|
|
39
|
+
sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), false);
|
|
40
|
+
sys.refresh_memory();
|
|
41
|
+
|
|
42
|
+
SYSTEM_TOTAL_MEM.store(sys.total_memory(), Ordering::Relaxed);
|
|
43
|
+
SYSTEM_USED_MEM.store(sys.used_memory(), Ordering::Relaxed);
|
|
44
|
+
|
|
45
|
+
if let Some(proc) = sys.process(pid) {
|
|
46
|
+
METRICS_RSS.store(proc.memory(), Ordering::Relaxed);
|
|
47
|
+
METRICS_VSZ.store(proc.virtual_memory(), Ordering::Relaxed);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## 2. Tokio Event Loop Lag Measurement
|
|
57
|
+
|
|
58
|
+
Event loop lag measures the delay between when an async task is scheduled and when a Tokio worker thread actually executes it. Elevated lag indicates synchronous blocking calls on the async reactor:
|
|
59
|
+
|
|
60
|
+
```rust
|
|
61
|
+
use std::sync::atomic::{AtomicU64, Ordering};
|
|
62
|
+
use std::time::Instant;
|
|
63
|
+
|
|
64
|
+
pub static METRICS_LAG: AtomicU64 = AtomicU64::new(0); // in microseconds
|
|
65
|
+
|
|
66
|
+
fn measure_event_loop_lag() {
|
|
67
|
+
let start = Instant::now();
|
|
68
|
+
tokio::spawn(async move {
|
|
69
|
+
let lag_micros = start.elapsed().as_micros() as u64;
|
|
70
|
+
METRICS_LAG.store(lag_micros, Ordering::Relaxed);
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## 3. Strict Label Cardinality Protection in Axum Middleware
|
|
78
|
+
|
|
79
|
+
Tracking endpoints like `/search?q=foo` or `/gallery/12345` creates an infinite number of unique labels in metric hash maps, causing gigabytes of RAM bloat.
|
|
80
|
+
|
|
81
|
+
Always normalize via `axum::extract::MatchedPath`:
|
|
82
|
+
|
|
83
|
+
```rust
|
|
84
|
+
use axum::{
|
|
85
|
+
body::Body,
|
|
86
|
+
extract::{MatchedPath, Request},
|
|
87
|
+
middleware::Next,
|
|
88
|
+
response::Response,
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
pub async fn telemetry_middleware(req: Request<Body>, next: Next) -> Response {
|
|
92
|
+
let raw_path = req.uri().path().to_string();
|
|
93
|
+
|
|
94
|
+
// Prevent /metrics endpoint from tracking itself
|
|
95
|
+
if raw_path == "/metrics" {
|
|
96
|
+
return next.run(req).await;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// STRICT route normalization: Only record matched templates (e.g. /pornhub/get),
|
|
100
|
+
// NEVER raw path or query params (?id=..., ?key=...) to prevent cardinality explosion.
|
|
101
|
+
let matched_path = req
|
|
102
|
+
.extensions()
|
|
103
|
+
.get::<MatchedPath>()
|
|
104
|
+
.map(|mp| mp.as_str().to_string())
|
|
105
|
+
.unwrap_or_else(|| {
|
|
106
|
+
if raw_path == "/" {
|
|
107
|
+
"/".to_string()
|
|
108
|
+
} else {
|
|
109
|
+
"/unmatched".to_string()
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
let method = req.method().to_string();
|
|
114
|
+
let start = std::time::Instant::now();
|
|
115
|
+
|
|
116
|
+
let res = next.run(req).await;
|
|
117
|
+
let elapsed = start.elapsed();
|
|
118
|
+
let status = res.status().as_u16().to_string();
|
|
119
|
+
|
|
120
|
+
// Safely record with finite, bounded label key
|
|
121
|
+
let key = format!("method=\"{method}\",path=\"{matched_path}\",status=\"{status}\"");
|
|
122
|
+
record_request(&key, elapsed);
|
|
123
|
+
|
|
124
|
+
// Release unmapped heap pages
|
|
125
|
+
crate::util::trim_memory();
|
|
126
|
+
|
|
127
|
+
res
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
## 4. Zero-Dependency Prometheus Spec 0.0.4 Exporter
|
|
134
|
+
|
|
135
|
+
Format metrics directly into a standard text payload without external crates:
|
|
136
|
+
|
|
137
|
+
```rust
|
|
138
|
+
use axum::response::IntoResponse;
|
|
139
|
+
|
|
140
|
+
pub async fn metrics_handler() -> impl IntoResponse {
|
|
141
|
+
let rss = METRICS_RSS.load(Ordering::Relaxed);
|
|
142
|
+
let vsz = METRICS_VSZ.load(Ordering::Relaxed);
|
|
143
|
+
let lag_secs = METRICS_LAG.load(Ordering::Relaxed) as f64 / 1_000_000.0;
|
|
144
|
+
|
|
145
|
+
let handle = tokio::runtime::Handle::current();
|
|
146
|
+
let tokio_metrics = handle.metrics();
|
|
147
|
+
let workers = tokio_metrics.num_workers();
|
|
148
|
+
let queue_depth = tokio_metrics.global_queue_depth();
|
|
149
|
+
|
|
150
|
+
let mut out = String::with_capacity(4096);
|
|
151
|
+
|
|
152
|
+
out.push_str("# HELP process_resident_set_size_bytes Total physical RAM used by the process\n");
|
|
153
|
+
out.push_str("# TYPE process_resident_set_size_bytes gauge\n");
|
|
154
|
+
out.push_str(&format!("process_resident_set_size_bytes {}\n\n", rss));
|
|
155
|
+
|
|
156
|
+
out.push_str("# HELP eventloop_lag_seconds Tokio scheduler delay for blocking detection\n");
|
|
157
|
+
out.push_str("# TYPE eventloop_lag_seconds gauge\n");
|
|
158
|
+
out.push_str(&format!("eventloop_lag_seconds {:.6}\n\n", lag_secs));
|
|
159
|
+
|
|
160
|
+
out.push_str("# HELP tokio_worker_threads Number of Tokio worker threads\n");
|
|
161
|
+
out.push_str("# TYPE tokio_worker_threads gauge\n");
|
|
162
|
+
out.push_str(&format!("tokio_worker_threads {}\n\n", workers));
|
|
163
|
+
|
|
164
|
+
out.push_str("# HELP tokio_global_queue_depth Global Tokio scheduler task queue depth\n");
|
|
165
|
+
out.push_str("# TYPE tokio_global_queue_depth gauge\n");
|
|
166
|
+
out.push_str(&format!("tokio_global_queue_depth {}\n\n", queue_depth));
|
|
167
|
+
|
|
168
|
+
([("Content-Type", "text/plain; version=0.0.4; charset=utf-8")], out)
|
|
169
|
+
}
|
|
170
|
+
```
|