@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,130 @@
|
|
|
1
|
+
# Zero-Allocation Error Architecture & Result Size Optimization
|
|
2
|
+
|
|
3
|
+
In high-throughput services, error handling is frequently overlooked as a source of memory bloat. Two primary hazards compromise performance:
|
|
4
|
+
1. **The `Result<T, E>` Stack Bloat**: The memory size of `Result<T, E>` is determined by `max(sizeof(T), sizeof(E)) + alignment`. A bloated error enum forces every single function call returning `Result` to allocate massive stack frames, even when the `Ok` branch is taken 99.9% of the time.
|
|
5
|
+
2. **Hot-Path Error Heap Churn**: Creating error instances using `format!` or `String::from` triggers heap allocations on every validation failure, rate limit breach, or missing parameter. Under high traffic or bot fuzzing, error generation alone degrades allocator performance.
|
|
6
|
+
|
|
7
|
+
This playbook documents how to construct lean, zero-allocation error hierarchies.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## 1. The Hidden Stack Cost of Large Error Enums
|
|
12
|
+
|
|
13
|
+
Consider this unoptimized domain error:
|
|
14
|
+
|
|
15
|
+
```rust
|
|
16
|
+
// ❌ WRONG: Bloats sizeof(AppError) to 128+ bytes!
|
|
17
|
+
pub enum BloatedError {
|
|
18
|
+
NotFound(&'static str), // 16 bytes
|
|
19
|
+
Validation(String), // 24 bytes
|
|
20
|
+
Database(diesel::result::Error), // 32 bytes
|
|
21
|
+
UpstreamNetwork(reqwest::Error), // 120+ bytes!
|
|
22
|
+
}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Because `UpstreamNetwork` is 120+ bytes:
|
|
26
|
+
- `std::mem::size_of::<BloatedError>()` is **~128 bytes**.
|
|
27
|
+
- Any function returning `Result<u32, BloatedError>` consumes **136 bytes on the stack** on every call frame!
|
|
28
|
+
- Deep call stacks multiply this footprint across thousands of concurrent Tokio tasks, increasing cache misses.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## 2. Boxing Rare Error Payloads
|
|
33
|
+
|
|
34
|
+
Errors from upstream libraries (e.g., `reqwest::Error`, `redis::RedisError`) are exceptional events. They should never dictate the baseline stack size of your domain `Result`.
|
|
35
|
+
|
|
36
|
+
**The Fix**: Box large or rare error variants:
|
|
37
|
+
|
|
38
|
+
```rust
|
|
39
|
+
// ✅ CORRECT: Compact Error Enum (sizeof <= 24 bytes)
|
|
40
|
+
#[derive(Debug, thiserror::Error)]
|
|
41
|
+
pub enum AppError {
|
|
42
|
+
#[error("Not Found: {0}")]
|
|
43
|
+
NotFound(&'static str), // 16 bytes
|
|
44
|
+
|
|
45
|
+
#[error("Validation Error: {0}")]
|
|
46
|
+
Validation(compact_str::CompactString), // 24 bytes (0 heap alloc for <=24B)
|
|
47
|
+
|
|
48
|
+
#[error("Rate Limit Exceeded")]
|
|
49
|
+
RateLimited, // 0 bytes
|
|
50
|
+
|
|
51
|
+
// 🚀 Box large errors: shrinks enum variant footprint to an 8-byte pointer!
|
|
52
|
+
#[error("Upstream HTTP Error: {0}")]
|
|
53
|
+
Upstream(Box<reqwest::Error>), // 8 bytes
|
|
54
|
+
|
|
55
|
+
#[error("Database Error: {0}")]
|
|
56
|
+
Database(Box<deadpool_redis::PoolError>), // 8 bytes
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
By boxing large variants, `std::mem::size_of::<AppError>()` drops from **128 bytes to 24 bytes**, reducing stack frame overhead by over **80%** across every function in the application.
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## 3. Eliminating Dynamic `format!` on Error Paths
|
|
65
|
+
|
|
66
|
+
Never format dynamic error strings on high-frequency error paths (e.g., input validation, authentication, rate limiting):
|
|
67
|
+
|
|
68
|
+
```rust
|
|
69
|
+
// ❌ WRONG: Allocates a new String on the heap on EVERY failed request
|
|
70
|
+
return Err(AppError::Validation(format!("Parameter '{}' is missing or invalid", key)));
|
|
71
|
+
|
|
72
|
+
// ✅ CORRECT: Zero-allocation static context or CompactString
|
|
73
|
+
use compact_str::format_compact;
|
|
74
|
+
|
|
75
|
+
// Path A: Pure static string (0 heap allocations)
|
|
76
|
+
return Err(AppError::NotFound("Video resource not found"));
|
|
77
|
+
|
|
78
|
+
// Path B: Dynamic string under 24 bytes (inlined on stack; 0 heap allocations)
|
|
79
|
+
return Err(AppError::Validation(format_compact!("Invalid ID: {id}")));
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
## 4. Zero-Allocation Axum `IntoResponse` Mapping
|
|
85
|
+
|
|
86
|
+
Map domain errors directly into HTTP responses without converting messages into dynamic JSON strings:
|
|
87
|
+
|
|
88
|
+
```rust
|
|
89
|
+
use axum::{
|
|
90
|
+
http::StatusCode,
|
|
91
|
+
response::{IntoResponse, Response},
|
|
92
|
+
Json,
|
|
93
|
+
};
|
|
94
|
+
use serde::Serialize;
|
|
95
|
+
|
|
96
|
+
#[derive(Serialize)]
|
|
97
|
+
struct ErrorResponseBody<'a> {
|
|
98
|
+
success: bool,
|
|
99
|
+
error: &'a str,
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
impl IntoResponse for AppError {
|
|
103
|
+
fn into_response(self) -> Response {
|
|
104
|
+
let (status, message) = match &self {
|
|
105
|
+
AppError::NotFound(msg) => (StatusCode::NOT_FOUND, *msg),
|
|
106
|
+
AppError::Validation(msg) => (StatusCode::BAD_REQUEST, msg.as_str()),
|
|
107
|
+
AppError::RateLimited => (StatusCode::TOO_MANY_REQUESTS, "Rate limit exceeded. Please slow down."),
|
|
108
|
+
AppError::Upstream(_) => (StatusCode::BAD_GATEWAY, "Upstream provider error"),
|
|
109
|
+
AppError::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "Internal persistence error"),
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
// Borrowed response body: zero string allocation during JSON serialization
|
|
113
|
+
let body = Json(ErrorResponseBody {
|
|
114
|
+
success: false,
|
|
115
|
+
error: message,
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
(status, body).into_response()
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## 5. Error Optimization Checklist
|
|
126
|
+
|
|
127
|
+
1. Has `std::mem::size_of::<AppError>()` been verified to be $\le 32$ bytes?
|
|
128
|
+
2. Are external library errors (`reqwest::Error`, `diesel::result::Error`) wrapped in `Box<...>`?
|
|
129
|
+
3. Are frequent error messages constructed using `&'static str` or `format_compact!` instead of standard `format!`?
|
|
130
|
+
4. Does `IntoResponse` serialize error payloads using borrowed `&str` references?
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# Zero-Copy Inter-Process Communication (IPC) and Shared Memory
|
|
2
|
+
|
|
3
|
+
When microservices or co-located processes (e.g., Rust backend with an Envoy sidecar, a Python ML inference engine, or a local daemon) communicate on the same physical host or Kubernetes pod, using TCP loopback (`127.0.0.1`) wastes CPU on network packetization, TCP checksums, and double-kernel buffer copies. Unix Domain Sockets (UDS) and memory-mapped shared files (`memmap2`) eliminate this overhead.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Unix Domain Sockets (UDS) vs TCP Loopback
|
|
8
|
+
|
|
9
|
+
| Metric | TCP Loopback (`127.0.0.1`) | Unix Domain Socket (UDS) |
|
|
10
|
+
| :--- | :--- | :--- |
|
|
11
|
+
| **Network Stack** | Full TCP/IP stack (routing, checksum, ACK) | Kernel socket buffer only (bypasses IP) |
|
|
12
|
+
| **Throughput** | ~25–35 GB/s | ~60–80 GB/s |
|
|
13
|
+
| **Memory Overhead** | Double socket buffer (send + recv queues) | Single-copy kernel page stream |
|
|
14
|
+
| **Security** | Open to all local processes on port | Governed by Linux file permissions |
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## 2. Axum over Unix Domain Sockets
|
|
19
|
+
|
|
20
|
+
Serve high-throughput HTTP/1.1 or HTTP/2 APIs over a local `.sock` file:
|
|
21
|
+
|
|
22
|
+
```rust
|
|
23
|
+
#[cfg(unix)]
|
|
24
|
+
use tokio::net::UnixListener;
|
|
25
|
+
use axum::{routing::get, Router};
|
|
26
|
+
use std::path::Path;
|
|
27
|
+
|
|
28
|
+
#[cfg(unix)]
|
|
29
|
+
pub async fn run_uds_server(socket_path: &str) -> Result<(), Box<dyn std::error::Error>> {
|
|
30
|
+
let path = Path::new(socket_path);
|
|
31
|
+
if path.exists() {
|
|
32
|
+
let _ = std::fs::remove_file(path); // Clean up stale socket file
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
let listener = UnixListener::bind(path)?;
|
|
36
|
+
println!("Server listening on UDS: {socket_path}");
|
|
37
|
+
|
|
38
|
+
let app = Router::new().route("/ping", get(|| async { "pong" }));
|
|
39
|
+
|
|
40
|
+
// Serve directly over UDS
|
|
41
|
+
axum::serve(listener, app).await?;
|
|
42
|
+
|
|
43
|
+
Ok(())
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## 3. Zero-Copy Shared Memory with `memmap2`
|
|
50
|
+
|
|
51
|
+
For transferring gigabyte-scale datasets (such as passing tensors to a Python process or streaming video frames) with zero heap copies, use memory-mapped shared files:
|
|
52
|
+
|
|
53
|
+
```rust
|
|
54
|
+
use memmap2::{MmapMut, MmapOptions};
|
|
55
|
+
use std::fs::OpenOptions;
|
|
56
|
+
|
|
57
|
+
pub struct SharedMemoryBuffer {
|
|
58
|
+
mmap: MmapMut,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
impl SharedMemoryBuffer {
|
|
62
|
+
pub fn create_or_open(path: &str, size_bytes: usize) -> Result<Self, std::io::Error> {
|
|
63
|
+
let file = OpenOptions::new()
|
|
64
|
+
.read(true)
|
|
65
|
+
.write(true)
|
|
66
|
+
.create(true)
|
|
67
|
+
.open(path)?;
|
|
68
|
+
|
|
69
|
+
file.set_len(size_bytes as u64)?;
|
|
70
|
+
|
|
71
|
+
let mmap = unsafe { MmapOptions::new().map_mut(&file)? };
|
|
72
|
+
|
|
73
|
+
Ok(Self { mmap })
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
pub fn write_slice_zero_copy(&mut self, offset: usize, data: &[u8]) -> Result<(), &'static str> {
|
|
77
|
+
if offset + data.len() > self.mmap.len() {
|
|
78
|
+
return Err("Buffer overflow: data exceeds shared memory bounds");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Copies directly into shared kernel page cache (0 application heap allocation)
|
|
82
|
+
self.mmap[offset..offset + data.len()].copy_from_slice(data);
|
|
83
|
+
Ok(())
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
pub fn read_slice(&self, offset: usize, len: usize) -> Option<&[u8]> {
|
|
87
|
+
self.mmap.get(offset..offset + len)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## 4. Production Checklist
|
|
95
|
+
|
|
96
|
+
- [ ] Replaced TCP loopback (`127.0.0.1`) with Unix Domain Sockets for sidecar / daemon communication.
|
|
97
|
+
- [ ] Stale socket files cleaned up on process startup before binding `UnixListener`.
|
|
98
|
+
- [ ] Large multi-megabyte inter-process transfers use memory-mapped files (`memmap2`) instead of JSON over HTTP.
|
|
99
|
+
- [ ] File permissions on socket files restricted to the designated service user group.
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# Zero-Copy Serde & Streaming Serialization
|
|
2
|
+
|
|
3
|
+
In web APIs, microservices, and scraper pipelines, JSON serialization and deserialization is the single largest consumer of CPU cycles and allocator bandwidth. The default pattern of deserializing into owned `String` fields forces thousands of tiny heap allocations per request, completely defeating the zero-cost promise of Rust.
|
|
4
|
+
|
|
5
|
+
This playbook documents how to eliminate allocation churn during serialization and achieve zero-copy JSON parsing.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. Zero-Copy Deserialization with `#[serde(borrow)]`
|
|
10
|
+
|
|
11
|
+
When deserializing a payload that is stored in an in-memory buffer (e.g., `bytes::Bytes`), there is no need to allocate new `String` objects on the heap. You can borrow string slices (`&'a str`) directly from the input buffer:
|
|
12
|
+
|
|
13
|
+
```toml
|
|
14
|
+
# Cargo.toml
|
|
15
|
+
[dependencies]
|
|
16
|
+
serde = { version = "1.0", features = ["derive"] }
|
|
17
|
+
serde_json = "1.0"
|
|
18
|
+
bytes = "1.7"
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```rust
|
|
22
|
+
use serde::Deserialize;
|
|
23
|
+
|
|
24
|
+
// ❌ WRONG: Allocates 4 separate heap strings per record
|
|
25
|
+
#[derive(Deserialize)]
|
|
26
|
+
pub struct NaiveRecord {
|
|
27
|
+
pub id: String,
|
|
28
|
+
pub title: String,
|
|
29
|
+
pub category: String,
|
|
30
|
+
pub author: String,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// ✅ CORRECT: ZERO heap allocations (borrows directly from the raw byte buffer)
|
|
34
|
+
#[derive(Deserialize)]
|
|
35
|
+
pub struct ZeroCopyRecord<'a> {
|
|
36
|
+
#[serde(borrow)]
|
|
37
|
+
pub id: &'a str,
|
|
38
|
+
#[serde(borrow)]
|
|
39
|
+
pub title: &'a str,
|
|
40
|
+
#[serde(borrow)]
|
|
41
|
+
pub category: &'a str,
|
|
42
|
+
#[serde(borrow)]
|
|
43
|
+
pub author: &'a str,
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Consumption Pattern:
|
|
48
|
+
```rust
|
|
49
|
+
pub fn parse_upstream_payload(raw_bytes: &[u8]) -> Result<ZeroCopyRecord<'_>, AppError> {
|
|
50
|
+
// serde_json::from_slice parses directly from bytes without double UTF-8 allocation
|
|
51
|
+
let record: ZeroCopyRecord = serde_json::from_slice(raw_bytes)
|
|
52
|
+
.map_err(|e| AppError::Validation(e.to_string()))?;
|
|
53
|
+
|
|
54
|
+
Ok(record)
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
> **Rule**: When parsing JSON from bytes, always prefer `serde_json::from_slice` over `std::str::from_utf8` + `serde_json::from_str`. `from_slice` validates UTF-8 and parses JSON in a single unified pass.
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## 2. Avoiding Dynamic `serde_json::Value`
|
|
63
|
+
|
|
64
|
+
`serde_json::Value` represents JSON as a dynamic recursive tree of enum nodes. Every key and string value in `serde_json::Value` is an allocated `String`, and every object is a `Map<String, Value>`.
|
|
65
|
+
|
|
66
|
+
Parsing a 1MB JSON document into `serde_json::Value` consumes **5MB to 8MB of RAM** and triggers tens of thousands of individual heap allocations.
|
|
67
|
+
|
|
68
|
+
```rust
|
|
69
|
+
// ❌ WRONG: Dynamic value causes massive allocator churn
|
|
70
|
+
let val: serde_json::Value = serde_json::from_slice(&bytes)?;
|
|
71
|
+
let title = val["data"]["item"]["title"].as_str().unwrap_or_default();
|
|
72
|
+
|
|
73
|
+
// ✅ CORRECT: Strongly typed minimal extraction struct
|
|
74
|
+
#[derive(Deserialize)]
|
|
75
|
+
struct MinimalItem<'a> {
|
|
76
|
+
#[serde(borrow)]
|
|
77
|
+
title: &'a str,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
#[derive(Deserialize)]
|
|
81
|
+
struct MinimalData<'a> {
|
|
82
|
+
#[serde(borrow)]
|
|
83
|
+
item: MinimalItem<'a>,
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
#[derive(Deserialize)]
|
|
87
|
+
struct MinimalWrapper<'a> {
|
|
88
|
+
#[serde(borrow)]
|
|
89
|
+
data: MinimalData<'a>,
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
let wrapper: MinimalWrapper = serde_json::from_slice(&bytes)?;
|
|
93
|
+
let title = wrapper.data.item.title; // 0 heap allocations!
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Serde automatically ignores all other fields in the payload without parsing or allocating them.
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## 3. Streaming Response Serialization (Zero Intermediate Allocation)
|
|
101
|
+
|
|
102
|
+
The typical Axum JSON response pattern:
|
|
103
|
+
```rust
|
|
104
|
+
// ❌ Allocates an intermediate String or Vec<u8> containing the full JSON payload
|
|
105
|
+
axum::Json(large_data)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
For large JSON payloads (e.g. returning 10,000 items), allocating a giant contiguous 10MB `String` stresses the allocator. Instead, stream the serialized chunks directly to the response socket using a reusable `bytes::BytesMut` buffer:
|
|
109
|
+
|
|
110
|
+
```rust
|
|
111
|
+
use axum::{
|
|
112
|
+
body::Body,
|
|
113
|
+
http::{header, HeaderMap, StatusCode},
|
|
114
|
+
response::{IntoResponse, Response},
|
|
115
|
+
};
|
|
116
|
+
use bytes::BytesMut;
|
|
117
|
+
|
|
118
|
+
pub fn stream_json_response<T: serde::Serialize>(data: &T) -> Result<Response, AppError> {
|
|
119
|
+
let mut buffer = BytesMut::with_capacity(32 * 1024);
|
|
120
|
+
let mut writer = (&mut buffer).writer();
|
|
121
|
+
|
|
122
|
+
// Serialize directly into the buffer writer
|
|
123
|
+
serde_json::to_writer(&mut writer, data)
|
|
124
|
+
.map_err(|e| AppError::Internal(e.to_string()))?;
|
|
125
|
+
|
|
126
|
+
let mut headers = HeaderMap::new();
|
|
127
|
+
headers.insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
|
|
128
|
+
|
|
129
|
+
Ok((StatusCode::OK, headers, Body::from(buffer.freeze())).into_response())
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
---
|
|
134
|
+
|
|
135
|
+
## 4. Hardware SIMD Acceleration for Giant Payloads
|
|
136
|
+
|
|
137
|
+
For systems ingesting massive JSON streams (> 50 MB/s), standard byte-by-byte deserializers hit CPU memory bus bottlenecks. Use **`simd-json`** to utilize AVX2/NEON vector instructions:
|
|
138
|
+
|
|
139
|
+
```toml
|
|
140
|
+
# Cargo.toml (Optional for heavy batch ingest pipelines)
|
|
141
|
+
[dependencies]
|
|
142
|
+
simd-json = "0.14"
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
```rust
|
|
146
|
+
// Parses inplace using SIMD vector instructions; up to 3x faster on x86_64
|
|
147
|
+
pub fn parse_with_simd(mut raw_bytes: Vec<u8>) -> Result<MyStruct, AppError> {
|
|
148
|
+
simd_json::from_slice(&mut raw_bytes).map_err(|e| AppError::Validation(e.to_string()))
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
---
|
|
153
|
+
|
|
154
|
+
## 5. Serde Performance Checklist
|
|
155
|
+
|
|
156
|
+
1. Are transient deserializers using `#[serde(borrow)]` with `&'a str` instead of `String`?
|
|
157
|
+
2. Has `serde_json::Value` been replaced with typed structs that extract only necessary fields?
|
|
158
|
+
3. Is `serde_json::from_slice` used directly on `&[u8]` buffers?
|
|
159
|
+
4. Are large outbound payloads serialized directly into reusable `BytesMut` writers?
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# Zero-Overhead Distributed Tracing and Observability
|
|
2
|
+
|
|
3
|
+
The `tracing` and `opentelemetry` crates provide world-class distributed observability in Rust. However, naive usage—such as using `#[instrument]` on hot inner loops, formatting dynamic strings into span fields, or performing synchronous logging on Tokio worker threads—can cause 20% to 40% CPU degradation and severe heap churn.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Compile-Time Static Level Filtering
|
|
8
|
+
|
|
9
|
+
Eliminate disabled trace levels completely from the compiled binary. If `trace!` and `debug!` statements are never enabled in production, remove their branching and metadata overhead at compile time in `Cargo.toml`:
|
|
10
|
+
|
|
11
|
+
```toml
|
|
12
|
+
[dependencies]
|
|
13
|
+
tracing = { version = "0.1", features = ["release_max_level_info"] }
|
|
14
|
+
log = { version = "0.4", features = ["release_max_level_info"] }
|
|
15
|
+
```
|
|
16
|
+
> With `release_max_level_info`, the compiler strips every `trace!` and `debug!` call from release builds, reducing binary size and eliminating runtime condition checks.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## 2. The `#[instrument]` Anti-Pattern on Hot Paths
|
|
21
|
+
|
|
22
|
+
### The Trap
|
|
23
|
+
Placing `#[instrument]` on functions called thousands of times per second allocates a `Span` struct, initializes span metadata, and registers enter/exit timestamps on every invocation:
|
|
24
|
+
|
|
25
|
+
```rust
|
|
26
|
+
// ANTI-PATTERN: Called 50,000 times per second in a parser or socket loop
|
|
27
|
+
#[tracing::instrument(skip(payload))]
|
|
28
|
+
pub fn parse_packet(payload: &[u8]) -> Result<Packet, ParseError> {
|
|
29
|
+
// Allocates Span and records timestamps on every packet!
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### The Solution: Selective Root Instrumentation
|
|
34
|
+
Only instrument top-level boundaries (HTTP route handlers, RPC entry points, message queue consumer messages). Use zero-allocation scalar fields inside:
|
|
35
|
+
|
|
36
|
+
```rust
|
|
37
|
+
// GOOD: Instrument top-level gateway request only
|
|
38
|
+
#[tracing::instrument(
|
|
39
|
+
name = "http_request",
|
|
40
|
+
skip(payload),
|
|
41
|
+
fields(
|
|
42
|
+
req_id = %req_id,
|
|
43
|
+
bytes = payload.len(), // Zero allocation integer primitive
|
|
44
|
+
)
|
|
45
|
+
)]
|
|
46
|
+
pub async fn handle_gateway_request(req_id: &str, payload: &[u8]) -> Response {
|
|
47
|
+
// Inner utility functions run without tracing overhead
|
|
48
|
+
let packet = parse_packet_fast(payload)?;
|
|
49
|
+
process(packet).await
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## 3. Non-Blocking Async Telemetry with `tracing-appender`
|
|
56
|
+
|
|
57
|
+
Writing logs or traces synchronously to `stdout` or disk blocks Tokio worker threads, stalling async event loops. Decouple logging onto a dedicated background worker thread with a non-blocking bounded queue:
|
|
58
|
+
|
|
59
|
+
```rust
|
|
60
|
+
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, fmt};
|
|
61
|
+
|
|
62
|
+
pub fn init_zero_overhead_tracing() -> tracing_appender::non_blocking::WorkerGuard {
|
|
63
|
+
// Create non-blocking stdout writer on dedicated background thread
|
|
64
|
+
let (non_blocking, guard) = tracing_appender::non_blocking(std::io::stdout());
|
|
65
|
+
|
|
66
|
+
let subscriber = tracing_subscriber::registry()
|
|
67
|
+
.with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")))
|
|
68
|
+
.with(
|
|
69
|
+
fmt::layer()
|
|
70
|
+
.with_writer(non_blocking)
|
|
71
|
+
.with_target(false)
|
|
72
|
+
.with_thread_ids(false) // Saves timestamp/ID formatting overhead
|
|
73
|
+
.compact(),
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
subscriber.init();
|
|
77
|
+
|
|
78
|
+
// MUST retain guard in main() until shutdown to flush remaining buffered logs
|
|
79
|
+
guard
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## 4. Zero-Allocation Span Fields
|
|
86
|
+
|
|
87
|
+
Avoid formatting dynamic strings into span fields (`format!("{}", user_id)`). Use native borrowing or scalar primitives:
|
|
88
|
+
|
|
89
|
+
```rust
|
|
90
|
+
use tracing::{info_span, Span};
|
|
91
|
+
|
|
92
|
+
pub fn record_transaction_span(account_id: u64, amount: u64) -> Span {
|
|
93
|
+
// Passes primitives directly to tracing subscriber (0 heap allocations)
|
|
94
|
+
info_span!(
|
|
95
|
+
"account_tx",
|
|
96
|
+
account.id = account_id,
|
|
97
|
+
tx.amount = amount,
|
|
98
|
+
)
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 5. Production Checklist
|
|
105
|
+
|
|
106
|
+
- [ ] Enabled `release_max_level_info` in `Cargo.toml` to strip debug spans in release builds.
|
|
107
|
+
- [ ] Removed all `#[instrument]` macros from loops, parser functions, and hot-path handlers.
|
|
108
|
+
- [ ] Wrapped `stdout` / file loggers in `tracing_appender::non_blocking` with dedicated `WorkerGuard`.
|
|
109
|
+
- [ ] Span fields avoid `format!` and use borrowed `&str` or numeric types (`u64`, `usize`).
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# Zero-Panic Architecture & Axum Router Layering
|
|
2
|
+
|
|
3
|
+
In high-throughput services, an unhandled panic on a Tokio worker thread drops the task, risks corrupting thread-local state, orphans synchronization locks, and degrades long-term process throughput. A robust production service must be mathematically panic-free at compile time.
|
|
4
|
+
|
|
5
|
+
This playbook documents the **Zero-Panic Policy**, router recursion management, and correct middleware layer ordering used in high-efficiency production services.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. Compile-Time Zero-Panic Enforcement
|
|
10
|
+
|
|
11
|
+
Enforce zero unhandled crashes at the compiler level across all targets:
|
|
12
|
+
|
|
13
|
+
### Top of `src/main.rs` and `src/lib.rs`
|
|
14
|
+
```rust
|
|
15
|
+
#![deny(clippy::unwrap_used, clippy::expect_used)]
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
When Clippy enforces this lint:
|
|
19
|
+
- Any developer (or AI agent) attempting to call `.unwrap()` or `.expect()` will fail compilation immediately.
|
|
20
|
+
- Forces explicit error conversion and bubbling using `?` or `.ok_or_else(...)`.
|
|
21
|
+
|
|
22
|
+
### Safe Idiom Replacements:
|
|
23
|
+
```rust
|
|
24
|
+
// ❌ WRONG: Panics if query parameter or header is missing
|
|
25
|
+
let id = link.split('=').nth(1).unwrap();
|
|
26
|
+
|
|
27
|
+
// ✅ CORRECT: Safe fallback with default or domain error
|
|
28
|
+
let id = link.split('=').nth(1).unwrap_or("None").to_string();
|
|
29
|
+
|
|
30
|
+
// ❌ WRONG: Panics if selector fails
|
|
31
|
+
let title = el.select(&SEL_TITLE).next().unwrap().text().collect();
|
|
32
|
+
|
|
33
|
+
// ✅ CORRECT: Functional Option combinators
|
|
34
|
+
let title = el
|
|
35
|
+
.select(&SEL_TITLE)
|
|
36
|
+
.next()
|
|
37
|
+
.map(|el| el.text().collect::<String>().trim().to_string())
|
|
38
|
+
.unwrap_or_else(|| "None".to_string());
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## 2. Macro Recursion Limit for Deeply Nested Routers
|
|
44
|
+
|
|
45
|
+
As an Axum application grows to dozens of endpoints with nested middleware layers (`.route_layer()`, `.layer()`, `.merge()`), the Rust compiler's default macro expansion depth is exceeded, causing compile errors:
|
|
46
|
+
`recursion limit reached while expanding the macro`
|
|
47
|
+
|
|
48
|
+
### Top of `src/main.rs`
|
|
49
|
+
```rust
|
|
50
|
+
#![recursion_limit = "512"]
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## 3. Strict Middleware Layer Execution Order
|
|
56
|
+
|
|
57
|
+
In Axum, middleware layers wrap handlers like an onion. **Layer ordering dictates execution order and memory safety**:
|
|
58
|
+
|
|
59
|
+
```rust
|
|
60
|
+
// 1. Core Service Routes
|
|
61
|
+
let scraper_routes = Router::<AppState>::new()
|
|
62
|
+
.route("/provider/get", get(provider_get))
|
|
63
|
+
.route("/provider/search", get(provider_search))
|
|
64
|
+
// INNER LAYERS: Executed closest to handler
|
|
65
|
+
.route_layer(axum::middleware::from_fn_with_state(state.clone(), slow_down_middleware))
|
|
66
|
+
.route_layer(axum::middleware::from_fn_with_state(state.clone(), rate_limiter_middleware))
|
|
67
|
+
// CORS LAYER: Permissive or strict headers
|
|
68
|
+
.layer(tower_http::cors::CorsLayer::permissive());
|
|
69
|
+
|
|
70
|
+
// 2. Assembly with State
|
|
71
|
+
let app = Router::new()
|
|
72
|
+
.merge(scraper_routes.with_state(state.clone()))
|
|
73
|
+
.route("/metrics", get(metrics_handler))
|
|
74
|
+
.route("/doc", get(doc_handler))
|
|
75
|
+
// OUTER LAYER: Telemetry must be outermost to capture ALL requests (including 404s)
|
|
76
|
+
.layer(axum::middleware::from_fn(telemetry_middleware))
|
|
77
|
+
// Fallback 404 handler
|
|
78
|
+
.fallback(not_found_handler);
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## 4. Zero-Disk Static Documentation Serving
|
|
84
|
+
|
|
85
|
+
Serving Swagger/Scalar OpenAPI documentation via dynamic filesystem reads wastes disk I/O and leaks file descriptors.
|
|
86
|
+
|
|
87
|
+
**Best Practice**: Embed documentation HTML templates at compile time using string literals:
|
|
88
|
+
|
|
89
|
+
```rust
|
|
90
|
+
use axum::response::{Html, IntoResponse};
|
|
91
|
+
|
|
92
|
+
const SCALAR_HTML: &str = r#"<!doctype html>
|
|
93
|
+
<html>
|
|
94
|
+
<head><title>API Reference</title></head>
|
|
95
|
+
<body>
|
|
96
|
+
<script id="api-reference" data-url="/openapi.json" src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
97
|
+
</body>
|
|
98
|
+
</html>"#;
|
|
99
|
+
|
|
100
|
+
pub async fn doc_handler() -> impl IntoResponse {
|
|
101
|
+
Html(SCALAR_HTML)
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
Zero disk I/O, zero runtime template engines, zero heap allocation.
|