@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,251 @@
|
|
|
1
|
+
# Extreme Memory & Runtime Efficiency in Real-Time WebSockets
|
|
2
|
+
|
|
3
|
+
In real-time communication systems (chat gateways, live sports feeds, financial tickers, and notification hubs), scaling to 50,000–500,000 concurrent long-lived WebSocket connections presents entirely different memory constraints than short-lived stateless REST APIs.
|
|
4
|
+
|
|
5
|
+
A naive WebSocket server consumes **100KB to 200KB of RAM per idle connection**—meaning 50,000 idle connections exhaust 5GB to 10GB of memory before processing a single payload.
|
|
6
|
+
|
|
7
|
+
This playbook documents the architecture required to achieve **< 4KB RSS per concurrent connection** and sub-millisecond zero-copy broadcast fan-out.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## 1. The Per-Socket Buffer Trap (The 100k Connection Dilemma)
|
|
12
|
+
|
|
13
|
+
By default, underlying WebSocket engines (such as `tungstenite` / `tokio-tungstenite`) configure generous internal buffer allocations for streaming frames:
|
|
14
|
+
- Default `write_buffer_size`: **128 KB**
|
|
15
|
+
- Default `max_frame_size`: **16 MB**
|
|
16
|
+
- Default `max_message_size`: **64 MB**
|
|
17
|
+
|
|
18
|
+
If 50,000 clients maintain active connections with default buffer sizes:
|
|
19
|
+
$$50,000 \times 128\ \text{KB} = \mathbf{6.4\ \text{GB of idle RAM allocated solely to internal socket buffers!}}$$
|
|
20
|
+
|
|
21
|
+
### The Extreme Efficiency Fix: Tuned `WebSocketConfig`
|
|
22
|
+
In Axum and Tungstenite, explicitly shrink frame limits and buffer pools during connection upgrades:
|
|
23
|
+
|
|
24
|
+
```rust
|
|
25
|
+
use axum::{
|
|
26
|
+
extract::ws::{WebSocket, WebSocketUpgrade},
|
|
27
|
+
response::IntoResponse,
|
|
28
|
+
};
|
|
29
|
+
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
|
|
30
|
+
|
|
31
|
+
pub async fn ws_handler(ws: WebSocketUpgrade) -> impl IntoResponse {
|
|
32
|
+
let mut config = WebSocketConfig::default();
|
|
33
|
+
|
|
34
|
+
// 🚀 RESTRICT WRITE BUFFER: 4KB is optimal for push events and chat frames
|
|
35
|
+
config.write_buffer_size = 4 * 1024; // Slashes RAM from 128KB to 4KB per socket!
|
|
36
|
+
config.max_frame_size = Some(64 * 1024); // 64KB max incoming frame
|
|
37
|
+
config.max_message_size = Some(128 * 1024); // 128KB max aggregate payload
|
|
38
|
+
config.accept_unmasked_frames = false;
|
|
39
|
+
|
|
40
|
+
ws.on_upgrade(move |socket| handle_socket(socket, config))
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
*Memory Impact*: Shrinks buffer allocation across 50,000 connections from **6.4 GB down to ~200 MB** (a **97% memory reduction**).
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## 2. Single-Task Bi-Directional Event Loop (Eliminating Task Doubling)
|
|
49
|
+
|
|
50
|
+
The common naive pattern spawns **two separate Tokio tasks per client**: one task dedicated to reading incoming frames, and a second task dedicated to writing outgoing frames:
|
|
51
|
+
- $50,000 \times 2 = \mathbf{100,000\ \text{concurrent Tokio tasks}}$ competing for scheduler slots and inflating executor memory.
|
|
52
|
+
|
|
53
|
+
Instead, merge both read and write streams into a **single cooperative task** using `tokio::select!`:
|
|
54
|
+
|
|
55
|
+
```rust
|
|
56
|
+
use axum::extract::ws::{Message, WebSocket};
|
|
57
|
+
use futures_util::{SinkExt, StreamExt};
|
|
58
|
+
use tokio::sync::mpsc;
|
|
59
|
+
use std::time::Duration;
|
|
60
|
+
|
|
61
|
+
pub async fn handle_socket(socket: WebSocket, _config: WebSocketConfig) {
|
|
62
|
+
let (mut ws_sink, mut ws_stream) = socket.split();
|
|
63
|
+
|
|
64
|
+
// Strictly bounded egress channel (16 messages deep per client)
|
|
65
|
+
let (tx, mut rx) = mpsc::channel::<Message>(16);
|
|
66
|
+
|
|
67
|
+
// Register sender with room / broadcast broker here...
|
|
68
|
+
|
|
69
|
+
loop {
|
|
70
|
+
tokio::select! {
|
|
71
|
+
// Branch 1: Handle incoming messages from the client
|
|
72
|
+
incoming = ws_stream.next() => {
|
|
73
|
+
match incoming {
|
|
74
|
+
Some(Ok(Message::Text(text))) => {
|
|
75
|
+
// Process client command (keep parsing zero-allocation!)
|
|
76
|
+
}
|
|
77
|
+
Some(Ok(Message::Ping(_))) => {
|
|
78
|
+
// Axum automatically queues Pong responses
|
|
79
|
+
}
|
|
80
|
+
Some(Ok(Message::Close(_))) | None => break,
|
|
81
|
+
_ => {}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Branch 2: Forward outgoing messages from the broadcast channel to the socket
|
|
86
|
+
outgoing = rx.recv() => {
|
|
87
|
+
match outgoing {
|
|
88
|
+
Some(msg) => {
|
|
89
|
+
if ws_sink.send(msg).await.is_err() {
|
|
90
|
+
break; // Client dropped connection or socket reset
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
None => break, // Channel closed by server broker
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Clean disconnection: automatic eviction from room registry occurs upon drop
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
## 3. Zero-Copy Broadcast Fan-Out with `bytes::Bytes`
|
|
106
|
+
|
|
107
|
+
In real-time broadcasting (pushing a stock price, breaking news, or game tick to 50,000 subscribers), naive code re-serializes or clones the string for every subscriber:
|
|
108
|
+
|
|
109
|
+
```rust
|
|
110
|
+
// ❌ NAIVE: 50,000 allocations per broadcast tick!
|
|
111
|
+
for client in &subscribers {
|
|
112
|
+
let json = serde_json::to_string(&data).unwrap(); // 50,000 HEAP ALLOCATIONS!
|
|
113
|
+
client.send(Message::Text(json)).await;
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### The Zero-Copy Pattern
|
|
118
|
+
Serialize the payload **once** into an atomic reference-counted `bytes::Bytes` slice. Cloning `Bytes` is an atomic pointer increment ($0$ heap allocations):
|
|
119
|
+
|
|
120
|
+
```rust
|
|
121
|
+
use bytes::Bytes;
|
|
122
|
+
use axum::extract::ws::Message;
|
|
123
|
+
|
|
124
|
+
pub struct BroadcastBroker {
|
|
125
|
+
// Channel sending pre-framed, zero-copy atomic slices
|
|
126
|
+
sender: tokio::sync::broadcast::Sender<Bytes>,
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
impl BroadcastBroker {
|
|
130
|
+
pub fn broadcast_event<T: serde::Serialize>(&self, event: &T) -> Result<(), AppError> {
|
|
131
|
+
// 1. Serialize payload EXACTLY ONCE into a reusable buffer
|
|
132
|
+
let mut buffer = bytes::BytesMut::with_capacity(512);
|
|
133
|
+
serde_json::to_writer((&mut buffer).writer(), event)
|
|
134
|
+
.map_err(|e| AppError::Internal(e.to_string()))?;
|
|
135
|
+
|
|
136
|
+
let payload: Bytes = buffer.freeze();
|
|
137
|
+
|
|
138
|
+
// 2. Broadcast single Bytes reference across all 50k subscribers
|
|
139
|
+
// Clones only the internal Arc pointer (0 heap allocation per client!)
|
|
140
|
+
let _ = self.sender.send(payload);
|
|
141
|
+
|
|
142
|
+
Ok(())
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## 4. Slow Consumer Defense & Poisoned Queue Isolation
|
|
150
|
+
|
|
151
|
+
If a single mobile client encounters cellular packet loss or stalls, an unconstrained broadcast channel will accumulate buffered messages. If left unchecked, that single slow consumer will inflate server memory until an Out-of-Memory (OOM) panic occurs.
|
|
152
|
+
|
|
153
|
+
### Backpressure Enforcement Rule:
|
|
154
|
+
Never use unbounded channels. Use bounded channels (`mpsc::channel(16)` or `32`), and use **`try_send()`**:
|
|
155
|
+
|
|
156
|
+
```rust
|
|
157
|
+
pub fn forward_to_subscriber(tx: &mpsc::Sender<Message>, msg: Message) -> bool {
|
|
158
|
+
match tx.try_send(msg) {
|
|
159
|
+
Ok(_) => true,
|
|
160
|
+
Err(mpsc::error::TrySendError::Full(_)) => {
|
|
161
|
+
// 🛑 CLIENT IS LAGGING BEHIND SERVER EGRESS:
|
|
162
|
+
// Terminate connection immediately to protect server RAM from ballooning
|
|
163
|
+
tracing::warn!("Disconnecting slow WebSocket consumer; egress queue full");
|
|
164
|
+
false
|
|
165
|
+
}
|
|
166
|
+
Err(mpsc::error::TrySendError::Closed(_)) => false,
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
## 5. Centralized Heartbeat Sweeper (Eliminating Timer Storms)
|
|
174
|
+
|
|
175
|
+
Spawning a dedicated `tokio::time::interval(Duration::from_secs(30))` for every single client creates 50,000 independent timer objects in the Tokio runtime wheel.
|
|
176
|
+
|
|
177
|
+
### Unified Timer Sweep Architecture
|
|
178
|
+
Store a single atomic timestamp (`AtomicU64` storing epoch seconds) in the client session state. A **single background worker** sweeps the connection pool every 15 seconds to terminate dead sockets:
|
|
179
|
+
|
|
180
|
+
```rust
|
|
181
|
+
use std::sync::atomic::{AtomicU64, Ordering};
|
|
182
|
+
use std::time::{SystemTime, UNIX_EPOCH};
|
|
183
|
+
|
|
184
|
+
pub struct ClientSession {
|
|
185
|
+
pub last_seen_epoch: AtomicU64,
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
impl ClientSession {
|
|
189
|
+
pub fn touch_heartbeat(&self) {
|
|
190
|
+
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
|
|
191
|
+
self.last_seen_epoch.store(now, Ordering::Relaxed);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
pub fn spawn_central_heartbeat_sweeper(sessions: Arc<DashMap<u64, Arc<ClientSession>>>) {
|
|
196
|
+
tokio::spawn(async move {
|
|
197
|
+
let mut interval = tokio::time::interval(Duration::from_secs(15));
|
|
198
|
+
loop {
|
|
199
|
+
interval.tick().await;
|
|
200
|
+
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
|
|
201
|
+
|
|
202
|
+
// Evict and drop sockets silent for > 60 seconds
|
|
203
|
+
sessions.retain(|_id, session| {
|
|
204
|
+
let last = session.last_seen_epoch.load(Ordering::Relaxed);
|
|
205
|
+
now.saturating_sub(last) < 60
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
---
|
|
213
|
+
|
|
214
|
+
## 6. Linux Kernel Socket Tuning for 100k+ Connections
|
|
215
|
+
|
|
216
|
+
On Linux deployment hosts running high-density WebSocket services, configure kernel TCP limits to prevent socket starvation:
|
|
217
|
+
|
|
218
|
+
### `/etc/sysctl.conf`
|
|
219
|
+
```ini
|
|
220
|
+
# Maximum number of open socket connections in listen queue
|
|
221
|
+
net.core.somaxconn = 65535
|
|
222
|
+
net.ipv4.tcp_max_syn_backlog = 65535
|
|
223
|
+
|
|
224
|
+
# Expand dynamic port range for outbound connections
|
|
225
|
+
net.ipv4.ip_local_port_range = 1024 65535
|
|
226
|
+
|
|
227
|
+
# Fast recycle of closed sockets in TIME_WAIT
|
|
228
|
+
net.ipv4.tcp_fin_timeout = 15
|
|
229
|
+
|
|
230
|
+
# Minimal TCP read/write buffer allocations (conserves kernel memory)
|
|
231
|
+
net.ipv4.tcp_rmem = 4096 87380 4194304
|
|
232
|
+
net.ipv4.tcp_wmem = 4096 16384 4194304
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### `/etc/security/limits.conf`
|
|
236
|
+
```text
|
|
237
|
+
# Expand file descriptor ceiling for server user
|
|
238
|
+
* soft nofile 1048576
|
|
239
|
+
* hard nofile 1048576
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
---
|
|
243
|
+
|
|
244
|
+
## 7. Real-Time Architecture Checklist
|
|
245
|
+
|
|
246
|
+
1. Has `WebSocketConfig.write_buffer_size` been tuned down to 4KB (eliminating the default 128KB per-socket waste)?
|
|
247
|
+
2. Are client read/write loops merged into a single task per connection using `tokio::select!`?
|
|
248
|
+
3. Is broadcast fan-out powered by `bytes::Bytes` to achieve zero-copy reference counting?
|
|
249
|
+
4. Are egress queues strictly bounded, dropping or disconnecting slow consumers via `try_send()`?
|
|
250
|
+
5. Are client heartbeats monitored using a single centralized timer sweep instead of per-socket timers?
|
|
251
|
+
6. Is `TCP_NODELAY` enabled to dispatch small push frames without Nagle algorithm buffering delays?
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
# Rust Redis Connection & Pooling Pitfalls: The 3-Hour Debugging Battle Scar
|
|
2
|
+
|
|
3
|
+
Connecting to Redis in asynchronous Rust (via `redis` and `deadpool-redis`) operates on lazy initialization semantics that differ significantly from synchronous drivers. Engineers frequently encounter silent connection failures, unverified lazy pools, feature flag mismatches, and credential parsing subtleties that surface only under production load.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. The 5 Traps That Break Redis in Rust
|
|
8
|
+
|
|
9
|
+
### Trap 1: The "Lazy Connection" Illusion
|
|
10
|
+
- Calling `redis::Client::open(url)` or `deadpool_redis::Config::create_pool(...)` **does not connect to Redis**. It only parses the string syntax!
|
|
11
|
+
- The server starts up, logs `"Redis client initialized"`, and appears healthy. Then, the first user request calls `pool.get().await`, times out, or fails silently.
|
|
12
|
+
- **The Fix**: Always run an active asynchronous `PING` check immediately during startup inside a spawned task.
|
|
13
|
+
|
|
14
|
+
### Trap 2: The `tokio-comp` Feature Flag Omission
|
|
15
|
+
- If you add `redis = "0.27"` without async runtime features, calling async commands fails to compile, or deadpool deadlocks Tokio threads.
|
|
16
|
+
- **The Fix**: Strictly require `tokio-comp`:
|
|
17
|
+
```toml
|
|
18
|
+
redis = { version = "0.27", features = ["tokio-comp"] }
|
|
19
|
+
deadpool-redis = "0.18" # or "0.23"
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
### Trap 3: Auth URL Formatting (`redis://` vs `rediss://`)
|
|
23
|
+
- Redis with password but no username requires an empty user before the colon:
|
|
24
|
+
`redis://:yourpassword@127.0.0.1:6379`
|
|
25
|
+
- If you write `redis://yourpassword@127.0.0.1:6379`, Redis interprets `yourpassword` as the username with NO password, causing `NOAUTH Authentication required`.
|
|
26
|
+
- Redis with ACL username:
|
|
27
|
+
`redis://username:yourpassword@127.0.0.1:6379`
|
|
28
|
+
- TLS-enabled Redis (AWS ElastiCache / Redis Cloud) **requires** `rediss://` and the `tls-rustls` feature in `redis`.
|
|
29
|
+
|
|
30
|
+
### Trap 4: Plaintext Password Leakage in Production Logs
|
|
31
|
+
- Printing the raw `REDIS_URL` in logs exposes production passwords.
|
|
32
|
+
- **The Fix**: Implement a deterministic URL masker that hides passwords while keeping scheme, host, and port visible.
|
|
33
|
+
|
|
34
|
+
### Trap 5: Hard Crashing on Redis Outages
|
|
35
|
+
- If Redis is down, an application should **degrade gracefully**, not crash or refuse all traffic.
|
|
36
|
+
- **The Fix**: Hybrid Cache Backend. Automatically fall back to bounded in-memory `moka` cache if Redis fails to connect.
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## 2. The Production-Tested Hybrid Cache Pattern (`jandapress`)
|
|
41
|
+
|
|
42
|
+
```rust
|
|
43
|
+
use deadpool_redis::{Config as RedisConfig, Pool, Runtime};
|
|
44
|
+
use moka::future::Cache as MokaCache;
|
|
45
|
+
use std::time::Duration;
|
|
46
|
+
use tracing::{info, warn};
|
|
47
|
+
|
|
48
|
+
#[derive(Clone)]
|
|
49
|
+
pub enum CacheBackend {
|
|
50
|
+
InMemory(MokaCache<String, Vec<u8>>),
|
|
51
|
+
Redis(Pool),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
#[derive(Clone)]
|
|
55
|
+
pub struct CacheManager {
|
|
56
|
+
backend: CacheBackend,
|
|
57
|
+
ttl: Duration,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/// Safely mask passwords in Redis connection strings before logging
|
|
61
|
+
pub fn mask_redis_url(url: &str) -> String {
|
|
62
|
+
if let Some(start_idx) = url.find("://") {
|
|
63
|
+
let scheme = &url[..start_idx + 3];
|
|
64
|
+
let rest = &url[start_idx + 3..];
|
|
65
|
+
if let Some(at_idx) = rest.find('@') {
|
|
66
|
+
let auth_part = &rest[..at_idx];
|
|
67
|
+
let host_part = &rest[at_idx..]; // "@host:port..."
|
|
68
|
+
if let Some(colon_idx) = auth_part.find(':') {
|
|
69
|
+
let username = &auth_part[..colon_idx];
|
|
70
|
+
return format!("{}{}:******{}", scheme, username, host_part);
|
|
71
|
+
} else {
|
|
72
|
+
return format!("{}******{}", scheme, host_part);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
url.to_string()
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
impl CacheManager {
|
|
80
|
+
pub fn new(redis_url: Option<&str>, expire_hours: u64) -> Self {
|
|
81
|
+
let ttl = Duration::from_secs(expire_hours * 3600);
|
|
82
|
+
|
|
83
|
+
let backend = if let Some(url) = redis_url {
|
|
84
|
+
info!("Initializing Redis cache backend with url: {}", mask_redis_url(url));
|
|
85
|
+
let mut cfg = RedisConfig::default();
|
|
86
|
+
cfg.url = Some(url.to_string());
|
|
87
|
+
cfg.connection = None;
|
|
88
|
+
|
|
89
|
+
// Runtime::Tokio1 is required for Tokio integration
|
|
90
|
+
match cfg.create_pool(Some(Runtime::Tokio1)) {
|
|
91
|
+
Ok(pool) => CacheBackend::Redis(pool),
|
|
92
|
+
Err(err) => {
|
|
93
|
+
warn!("Failed to create Redis pool: {:?}. Falling back to bounded In-Memory cache.", err);
|
|
94
|
+
Self::create_in_memory_backend(ttl)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
} else {
|
|
98
|
+
info!("No Redis URL provided. Initializing bounded In-Memory cache backend.");
|
|
99
|
+
Self::create_in_memory_backend(ttl)
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
Self { backend, ttl }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
fn create_in_memory_backend(ttl: Duration) -> CacheBackend {
|
|
106
|
+
// Strictly bounded to 1,000 entries to prevent memory growth leaks
|
|
107
|
+
let cache = MokaCache::builder()
|
|
108
|
+
.max_capacity(1000)
|
|
109
|
+
.time_to_live(ttl)
|
|
110
|
+
.build();
|
|
111
|
+
CacheBackend::InMemory(cache)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/// Actively verify Redis connection with an explicit PING command
|
|
115
|
+
pub async fn test_connection(&self) -> Result<(), String> {
|
|
116
|
+
match &self.backend {
|
|
117
|
+
CacheBackend::InMemory(_) => Ok(()),
|
|
118
|
+
CacheBackend::Redis(pool) => {
|
|
119
|
+
let mut conn = pool.get().await
|
|
120
|
+
.map_err(|e| format!("Failed to acquire connection from pool: {:?}", e))?;
|
|
121
|
+
|
|
122
|
+
let pong: String = redis::cmd("PING")
|
|
123
|
+
.query_async(&mut conn)
|
|
124
|
+
.await
|
|
125
|
+
.map_err(|e| format!("PING command failed: {:?}", e))?;
|
|
126
|
+
|
|
127
|
+
if pong == "PONG" {
|
|
128
|
+
Ok(())
|
|
129
|
+
} else {
|
|
130
|
+
Err(format!("Unexpected PING response: {}", pong))
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
pub async fn get(&self, key: &str) -> Option<Vec<u8>> {
|
|
137
|
+
match &self.backend {
|
|
138
|
+
CacheBackend::InMemory(cache) => cache.get(key).await,
|
|
139
|
+
CacheBackend::Redis(pool) => {
|
|
140
|
+
let mut conn = match pool.get().await {
|
|
141
|
+
Ok(c) => c,
|
|
142
|
+
Err(err) => {
|
|
143
|
+
warn!("Failed to get Redis connection from pool: {:?}", err);
|
|
144
|
+
return None;
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
let cmd = redis::cmd("GET").arg(key).query_async::<Option<Vec<u8>>>(&mut conn).await;
|
|
149
|
+
match cmd {
|
|
150
|
+
Ok(val) => val,
|
|
151
|
+
Err(err) => {
|
|
152
|
+
warn!("Redis GET error: {:?}", err);
|
|
153
|
+
None
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
pub async fn set(&self, key: &str, value: &[u8]) {
|
|
161
|
+
match &self.backend {
|
|
162
|
+
CacheBackend::InMemory(cache) => {
|
|
163
|
+
cache.insert(key.to_string(), value.to_vec()).await;
|
|
164
|
+
}
|
|
165
|
+
CacheBackend::Redis(pool) => {
|
|
166
|
+
let mut conn = match pool.get().await {
|
|
167
|
+
Ok(c) => c,
|
|
168
|
+
Err(err) => {
|
|
169
|
+
warn!("Failed to get Redis connection from pool: {:?}", err);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
let ttl_secs = self.ttl.as_secs();
|
|
175
|
+
let res: Result<(), redis::RedisError> = redis::cmd("SETEX")
|
|
176
|
+
.arg(key)
|
|
177
|
+
.arg(ttl_secs)
|
|
178
|
+
.arg(value)
|
|
179
|
+
.query_async(&mut conn)
|
|
180
|
+
.await;
|
|
181
|
+
|
|
182
|
+
if let Err(err) = res {
|
|
183
|
+
warn!("Redis SETEX error: {:?}", err);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
---
|
|
192
|
+
|
|
193
|
+
## 3. Asynchronous Non-Blocking Verification in `main.rs`
|
|
194
|
+
|
|
195
|
+
Never block server bootup on Redis. Verify connectivity asynchronously in the background so the HTTP server can start serving immediately while logging clear status:
|
|
196
|
+
|
|
197
|
+
```rust
|
|
198
|
+
if config.redis_url.is_some() {
|
|
199
|
+
let cache_clone = state.cache.clone();
|
|
200
|
+
tokio::spawn(async move {
|
|
201
|
+
match cache_clone.test_connection().await {
|
|
202
|
+
Ok(_) => tracing::info!("Redis cache connection verified successfully! Backend: Connected"),
|
|
203
|
+
Err(err) => tracing::warn!("Redis verification failed: {}. Falling back to In-Memory cache.", err),
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
## 4. Self-Hosted Redis Dockerfile for CI / Local Testing
|
|
212
|
+
|
|
213
|
+
When testing Redis integration locally or in GitHub Actions, avoid unauthenticated default Redis containers. Use a pinned lightweight Redis image with explicit auth:
|
|
214
|
+
|
|
215
|
+
```dockerfile
|
|
216
|
+
FROM redis:8-alpine AS redis
|
|
217
|
+
|
|
218
|
+
LABEL org.opencontainers.image.title="app-redis"
|
|
219
|
+
LABEL org.opencontainers.image.description="Dedicated Redis cache backend"
|
|
220
|
+
|
|
221
|
+
EXPOSE 6379
|
|
222
|
+
|
|
223
|
+
# Enforce explicit auth password matching app connection string
|
|
224
|
+
CMD ["redis-server", "--requirepass", "app_secret_password"]
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
**Matching `.env` String**:
|
|
228
|
+
```env
|
|
229
|
+
REDIS_URL=redis://:app_secret_password@127.0.0.1:6379
|
|
230
|
+
```
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# Reqwest Client & TCP Socket Pooling: Eliminating Network Memory Leaks
|
|
2
|
+
|
|
3
|
+
In native network services, instantiating an HTTP client per request creates new TCP connection pools, triggers repeated TLS handshakes, and leaks OS socket descriptors, resulting in severe memory bloat and eventual port exhaustion under load. In Rust, HTTP clients must be engineered as long-lived, bounded singletons.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. The Singleton Client Architecture
|
|
8
|
+
|
|
9
|
+
Always instantiate a **single `reqwest::Client`** at application startup, store it inside `Arc<AppState>`, and reuse it across all handlers and background tasks:
|
|
10
|
+
|
|
11
|
+
```rust
|
|
12
|
+
use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT};
|
|
13
|
+
use std::time::Duration;
|
|
14
|
+
|
|
15
|
+
pub fn create_shared_http_client(user_agent: &str) -> reqwest::Client {
|
|
16
|
+
let mut default_headers = HeaderMap::new();
|
|
17
|
+
default_headers.insert(
|
|
18
|
+
USER_AGENT,
|
|
19
|
+
HeaderValue::from_str(user_agent).unwrap_or_else(|_| HeaderValue::from_static("RustBackend/1.0")),
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
reqwest::Client::builder()
|
|
23
|
+
.default_headers(default_headers)
|
|
24
|
+
// 1. Connection Pool Bounding
|
|
25
|
+
.pool_idle_timeout(Duration::from_secs(90))
|
|
26
|
+
.pool_max_idle_per_host(10)
|
|
27
|
+
// 2. TCP Keepalive
|
|
28
|
+
.tcp_keepalive(Duration::from_secs(60))
|
|
29
|
+
// 3. Global Hard Timeout
|
|
30
|
+
.timeout(Duration::from_secs(15))
|
|
31
|
+
// 4. Native Compression (saves network memory buffers)
|
|
32
|
+
.gzip(true)
|
|
33
|
+
.deflate(true)
|
|
34
|
+
.build()
|
|
35
|
+
.expect("Failed to build shared HTTP client")
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## 2. Tiered Timeouts: Never Let Ancillary Calls Block Workers
|
|
42
|
+
|
|
43
|
+
A common mistake is using the same 15-second timeout for everything. If an ancillary request (like GeoIP lookup or third-party status probe) hangs, it pins the Tokio worker thread context for 15 seconds.
|
|
44
|
+
|
|
45
|
+
### The Jandapress Pattern:
|
|
46
|
+
Override timeouts on ancillary requests so they fail fast without impacting core traffic:
|
|
47
|
+
|
|
48
|
+
```rust
|
|
49
|
+
// Core Scraper Request (Needs longer timeout for large pages)
|
|
50
|
+
let body = client
|
|
51
|
+
.get(target_url)
|
|
52
|
+
.send() // Uses default 15s timeout
|
|
53
|
+
.await?;
|
|
54
|
+
|
|
55
|
+
// Ancillary Metadata Request (Must fail fast in 3 seconds!)
|
|
56
|
+
let location = match client
|
|
57
|
+
.get("https://ipwho.is/")
|
|
58
|
+
.timeout(Duration::from_secs(3)) // Explicit fast timeout
|
|
59
|
+
.send()
|
|
60
|
+
.await
|
|
61
|
+
{
|
|
62
|
+
Ok(res) if res.status().is_success() => parse_location(res).await,
|
|
63
|
+
_ => "Unknown".to_string(), // Fail gracefully without holding resources
|
|
64
|
+
};
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## 3. Selective Caching Policy (Preventing Cache Bloat)
|
|
70
|
+
|
|
71
|
+
Never cache responses blindly. Certain endpoints (such as `/random` galleries or ephemeral queries) produce infinite unique keys that flood your cache and evict hot entries:
|
|
72
|
+
|
|
73
|
+
```rust
|
|
74
|
+
pub async fn fetch_body(&self, url: &str) -> Result<Vec<u8>, AppError> {
|
|
75
|
+
// 1. Check cache first
|
|
76
|
+
if let Some(cached) = self.cache.get(url).await {
|
|
77
|
+
return Ok(cached);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// 2. EXCLUDE random / volatile endpoints from cache insertion!
|
|
81
|
+
if url.contains("/random") {
|
|
82
|
+
let res = self.client.get(url).send().await?;
|
|
83
|
+
return Ok(res.bytes().await?.to_vec());
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 3. Cache deterministic endpoints
|
|
87
|
+
let res = self.client.get(url).send().await?;
|
|
88
|
+
let bytes = res.bytes().await?.to_vec();
|
|
89
|
+
self.cache.set(url, &bytes).await;
|
|
90
|
+
|
|
91
|
+
Ok(bytes)
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## 4. Chunked Stream Early-Break (Socket Lifecycle Control)
|
|
98
|
+
|
|
99
|
+
When verifying challenge tokens or inspecting page headers, never read the full multi-megabyte body with `res.text().await`.
|
|
100
|
+
|
|
101
|
+
Stream chunks and explicitly drop the response:
|
|
102
|
+
|
|
103
|
+
```rust
|
|
104
|
+
use reqwest::Response;
|
|
105
|
+
|
|
106
|
+
pub async fn check_upstream_challenge(mut res: Response) -> Result<bool, reqwest::Error> {
|
|
107
|
+
let mut buffer = String::new();
|
|
108
|
+
|
|
109
|
+
while let Ok(Some(chunk)) = res.chunk().await {
|
|
110
|
+
if let Ok(s) = std::str::from_utf8(&chunk) {
|
|
111
|
+
buffer.push_str(s);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Target found early? Break immediately!
|
|
115
|
+
if buffer.contains("challenge_token") {
|
|
116
|
+
// Drop response immediately to return socket to pool
|
|
117
|
+
drop(res);
|
|
118
|
+
return Ok(true);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Safety cap: Never buffer more than 64KB for a verification check
|
|
122
|
+
if buffer.len() >= 65_536 {
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
drop(res);
|
|
128
|
+
Ok(false)
|
|
129
|
+
}
|
|
130
|
+
```
|