@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,170 @@
|
|
|
1
|
+
# Hardware Resource Budgets, Concurrency Modeling & Loom Verification
|
|
2
|
+
|
|
3
|
+
## The Problem: Unbounded Resource Exhaustion & Flaky Concurrency Tests
|
|
4
|
+
|
|
5
|
+
Async frameworks like Tokio make it easy to spawn millions of tasks, but without upfront physical resource accounting, production services frequently collapse under load due to:
|
|
6
|
+
|
|
7
|
+
1. **Unbounded Channel & Buffer Growth**: An unexpected slow consumer causes in-memory queues to grow until the Linux OOM-killer terminates the process.
|
|
8
|
+
2. **Flaky Concurrency Tests**: Verifying multithreaded logic or custom lock-free atomics with `thread::sleep(Duration::from_millis(10))` provides false confidence; race conditions only trigger under specific OS thread scheduling permutations in production.
|
|
9
|
+
3. **Hidden Async Task Poll Latencies**: Tasks that accidentally perform CPU-heavy serialization or uninstrumented blocking I/O stall the Tokio cooperative scheduler.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 1. Upfront Physical Resource Budgeting
|
|
14
|
+
|
|
15
|
+
Before writing a single line of network code, define the **Worst-Case RSS Ceiling** mathematically:
|
|
16
|
+
|
|
17
|
+
$$\text{RSS}_{\text{max}} = (\text{Max Connections} \times \text{Buffer}_{\text{per\_conn}}) + \text{Queue Budgets} + \text{Cache Budgets} + \text{Arena Overhead}$$
|
|
18
|
+
|
|
19
|
+
### Production Resource Specification Table
|
|
20
|
+
|
|
21
|
+
| Resource Dimension | Strict Limit | Backpressure / Rejection Policy |
|
|
22
|
+
| :--- | :--- | :--- |
|
|
23
|
+
| **Concurrent TCP Connections** | 10,000 max | `tokio::net::TcpListener` gated via `tokio::sync::Semaphore(10_000)`. Immediate RST if saturated. |
|
|
24
|
+
| **Per-Connection Read Buffer** | 64 KB max (`bytes::BytesMut`) | If payload exceeds 64 KB, disconnect with HTTP 413 Payload Too Large. |
|
|
25
|
+
| **In-Flight Request Channel** | Bounded: 1,024 items | Use `mpsc::channel(1024)`. If full, return HTTP 503 Load Shedding. |
|
|
26
|
+
| **Global LRU Cache** | 256 MB max (`moka::future::Cache`) | Evicts LRU entries automatically; memory-bounded via weighted entries. |
|
|
27
|
+
| **Allocator Arena Overhead** | `MALLOC_ARENA_MAX=2` | Limits glibc per-thread arenas to 2, preventing phantom RSS bloat. |
|
|
28
|
+
|
|
29
|
+
### Calculated Worst-Case Footprint
|
|
30
|
+
|
|
31
|
+
$$\text{Active Network Memory} = 10{,}000 \times (64\text{ KB rx} + 64\text{ KB tx}) = 1.28\text{ GB}$$
|
|
32
|
+
$$\text{Total Safe RSS Ceiling} = 1.28\text{ GB} + 256\text{ MB cache} + 128\text{ MB runtime/stack} \approx 1.66\text{ GB}$$
|
|
33
|
+
|
|
34
|
+
Deploy Kubernetes limits with at least 25% safety headroom:
|
|
35
|
+
```yaml
|
|
36
|
+
resources:
|
|
37
|
+
requests:
|
|
38
|
+
memory: "512Mi"
|
|
39
|
+
cpu: "500m"
|
|
40
|
+
limits:
|
|
41
|
+
memory: "2Gi"
|
|
42
|
+
cpu: "2000m"
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## 2. Formal Concurrency Verification with Loom
|
|
48
|
+
|
|
49
|
+
Never test atomic state machines or custom synchronization primitives with random sleeps. Use **Loom** for deterministic execution-schedule permutation testing.
|
|
50
|
+
|
|
51
|
+
### Structuring Code for Loom and Standard Runtimes
|
|
52
|
+
|
|
53
|
+
Abstract synchronization types so that Loom replaces `std::sync` during test runs:
|
|
54
|
+
|
|
55
|
+
```rust
|
|
56
|
+
#[cfg(loom)]
|
|
57
|
+
mod sync {
|
|
58
|
+
pub use loom::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
|
59
|
+
pub use loom::sync::Arc;
|
|
60
|
+
pub use loom::thread;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
#[cfg(not(loom))]
|
|
64
|
+
mod sync {
|
|
65
|
+
pub use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
|
66
|
+
pub use std::sync::Arc;
|
|
67
|
+
pub use std::thread;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
use sync::*;
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Writing a Loom Exhaustive Permutation Test
|
|
74
|
+
|
|
75
|
+
Loom repeatedly intercepts thread context switches, atomic operations, and memory barriers to test every possible interleaving:
|
|
76
|
+
|
|
77
|
+
```rust
|
|
78
|
+
pub struct SpinLock {
|
|
79
|
+
locked: AtomicBool,
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
impl SpinLock {
|
|
83
|
+
pub fn new() -> Self {
|
|
84
|
+
Self { locked: AtomicBool::new(false) }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
pub fn try_lock(&self) -> bool {
|
|
88
|
+
// Atomic flag acquisition with Acquire semantics
|
|
89
|
+
!self.locked.swap(true, Ordering::Acquire)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
pub fn unlock(&self) {
|
|
93
|
+
// Release publication
|
|
94
|
+
self.locked.store(false, Ordering::Release);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
#[cfg(test)]
|
|
99
|
+
mod tests {
|
|
100
|
+
use super::*;
|
|
101
|
+
|
|
102
|
+
#[test]
|
|
103
|
+
#[cfg(loom)]
|
|
104
|
+
fn loom_verify_spinlock_mutual_exclusion() {
|
|
105
|
+
loom::model(|| {
|
|
106
|
+
let lock = Arc::new(SpinLock::new());
|
|
107
|
+
let lock2 = lock.clone();
|
|
108
|
+
|
|
109
|
+
let handle = loom::thread::spawn(move || {
|
|
110
|
+
if lock2.try_lock() {
|
|
111
|
+
// Critical section
|
|
112
|
+
lock2.unlock();
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
if lock.try_lock() {
|
|
117
|
+
// Critical section
|
|
118
|
+
lock.unlock();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
handle.join().unwrap();
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Run the model test with:
|
|
128
|
+
```bash
|
|
129
|
+
RUSTFLAGS="--cfg loom" cargo test --test loom_model --release
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
If an ordering is too weak (e.g. `Ordering::Relaxed` where `Ordering::Acquire` is required), Loom produces an exact execution trace proving the race condition.
|
|
133
|
+
|
|
134
|
+
---
|
|
135
|
+
|
|
136
|
+
## 3. Tokio Task Poll Diagnostics & Starvation Detection
|
|
137
|
+
|
|
138
|
+
In production async services, tasks that spend more than 1–2 milliseconds in a single `poll()` invocation cause latency jitter for other multiplexed futures.
|
|
139
|
+
|
|
140
|
+
### Enabling Tokio Runtime Tracing & Metrics
|
|
141
|
+
|
|
142
|
+
Configure the Tokio runtime to track task execution metrics in diagnostic builds:
|
|
143
|
+
|
|
144
|
+
```rust
|
|
145
|
+
#[cfg(feature = "tokio-console")]
|
|
146
|
+
pub fn init_runtime_diagnostics() {
|
|
147
|
+
console_subscriber::init();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
pub fn create_instrumented_runtime() -> tokio::runtime::Runtime {
|
|
151
|
+
tokio::runtime::Builder::new_multi_thread()
|
|
152
|
+
.enable_all()
|
|
153
|
+
.metrics_poll_count_histogram() // Track poll duration distributions
|
|
154
|
+
.build()
|
|
155
|
+
.expect("failed to build tokio runtime")
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### Inspecting Runtime Health with `tokio-console`
|
|
160
|
+
|
|
161
|
+
Run your service with `RUSTFLAGS="--cfg tokio_unstable"` and connect:
|
|
162
|
+
|
|
163
|
+
```bash
|
|
164
|
+
tokio-console http://127.0.0.1:6669
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Watch for:
|
|
168
|
+
1. **Long Poll Times**: Tasks showing poll durations > 1ms. Identify the offending function and offload it to `tokio::task::spawn_blocking` or `rayon`.
|
|
169
|
+
2. **High Busy/Idle Ratio**: Indicates that workers are saturated with computation rather than waiting on non-blocking I/O.
|
|
170
|
+
3. **Woken Without Progress**: Tasks scheduled frequently by poorly configured timers or channels without actual work ready.
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# Concurrency Primitives & Lock Contention Elimination
|
|
2
|
+
|
|
3
|
+
In multi-threaded asynchronous systems, synchronization primitives are a frequent source of hidden latency, CPU core throttling, and allocator churn. Developers commonly default to `tokio::sync::Mutex` indiscriminately or misuse standard library locks, causing thread pool deadlocks, excessive OS futex syscalls, and CPU cache line thrashing.
|
|
4
|
+
|
|
5
|
+
This playbook establishes the rules for selecting and tuning concurrency primitives for sub-microsecond synchronization.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. The Concurrency Selection Matrix
|
|
10
|
+
|
|
11
|
+
```text
|
|
12
|
+
Is the lock held across an `.await` boundary?
|
|
13
|
+
/ \
|
|
14
|
+
YES NO
|
|
15
|
+
/ \
|
|
16
|
+
Use `tokio::sync::Mutex` Is the access read-heavy (>95% reads)?
|
|
17
|
+
(Task-yielding async lock) / \
|
|
18
|
+
YES NO
|
|
19
|
+
/ \
|
|
20
|
+
Is state updated rarely? Is it a single numeric
|
|
21
|
+
/ \ counter or flag?
|
|
22
|
+
YES NO / \
|
|
23
|
+
/ \ YES NO
|
|
24
|
+
Use `arc_swap` Use `parking_lot` Use `Atomic*` Use `parking_lot`
|
|
25
|
+
(Wait-free reads) `RwLock` (Lock-free) `Mutex`
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## 2. In-Memory Synchronization: `parking_lot` vs `std::sync` vs `tokio::sync`
|
|
31
|
+
|
|
32
|
+
### The Hidden Penalty of `tokio::sync::Mutex`
|
|
33
|
+
- `tokio::sync::Mutex` is an **asynchronous lock**. Acquiring it requires heap allocation for task queue nodes and triggers Tokio task state swaps.
|
|
34
|
+
- **Rule**: If a critical section does not perform I/O and executes in $< 10\ \mu\text{s}$, **NEVER** use `tokio::sync::Mutex`.
|
|
35
|
+
|
|
36
|
+
### The `parking_lot` Advantage
|
|
37
|
+
`parking_lot` replaces standard library synchronization with spin-wait optimization and inline storage:
|
|
38
|
+
- `std::sync::Mutex`: Consumes **40 bytes** on Linux, relies directly on OS futexes.
|
|
39
|
+
- `parking_lot::Mutex`: Consumes **1 byte**, avoids syscalls for uncontended locks, and is immune to priority inversion.
|
|
40
|
+
|
|
41
|
+
```toml
|
|
42
|
+
# Cargo.toml
|
|
43
|
+
[dependencies]
|
|
44
|
+
parking_lot = "0.12"
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```rust
|
|
48
|
+
use parking_lot::{Mutex, RwLock};
|
|
49
|
+
|
|
50
|
+
pub struct SafeCache {
|
|
51
|
+
// 1-byte overhead, ultra-fast uncontended lock
|
|
52
|
+
metrics: Mutex<CacheMetrics>,
|
|
53
|
+
// Reader-writer lock optimized for concurrent lookups
|
|
54
|
+
entries: RwLock<HashMap<CompactString, CacheEntry>>,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
impl SafeCache {
|
|
58
|
+
pub fn record_hit(&self) {
|
|
59
|
+
// Fast synchronous lock: drops immediately, never held across .await
|
|
60
|
+
let mut m = self.metrics.lock();
|
|
61
|
+
m.hits += 1;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
> **CRITICAL WARNING**: Never hold any synchronous lock guard (`parking_lot::MutexGuard` or `std::sync::MutexGuard`) across an `.await` point. Doing so locks the underlying OS thread, starving Tokio worker threads.
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## 3. Wait-Free Read-Heavy State with `arc-swap`
|
|
71
|
+
|
|
72
|
+
When shared state (such as routing tables, rate-limit policies, or upstream configurations) is read hundreds of thousands of times per second but updated infrequently (e.g., via background polling or webhook), even an `RwLock` degrades performance due to atomic reader-count increment contention.
|
|
73
|
+
|
|
74
|
+
Use **`arc-swap`** for zero-lock, wait-free reads:
|
|
75
|
+
|
|
76
|
+
```toml
|
|
77
|
+
# Cargo.toml
|
|
78
|
+
[dependencies]
|
|
79
|
+
arc-swap = "1.7"
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
```rust
|
|
83
|
+
use arc_swap::ArcSwap;
|
|
84
|
+
use std::sync::Arc;
|
|
85
|
+
|
|
86
|
+
pub struct DynamicRouteConfig {
|
|
87
|
+
pub upstream_url: CompactString,
|
|
88
|
+
pub timeout_ms: u64,
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
pub struct GatewayState {
|
|
92
|
+
// Atomic pointer swap: readers never lock, writers atomically replace pointer
|
|
93
|
+
config: ArcSwap<DynamicRouteConfig>,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
impl GatewayState {
|
|
97
|
+
pub fn get_upstream(&self) -> Arc<DynamicRouteConfig> {
|
|
98
|
+
// Wait-free read: loads Arc pointer in sub-nanosecond time
|
|
99
|
+
self.config.load_full()
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
pub fn update_config(&self, new_config: DynamicRouteConfig) {
|
|
103
|
+
// Atomic store: replaces pointer, old readers safely drain via Arc
|
|
104
|
+
self.config.store(Arc::new(new_config));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
## 4. Lock-Free Counters & Atomic Memory Ordering
|
|
112
|
+
|
|
113
|
+
For concurrent metrics, IDs, and liveness flags, eliminate locks entirely using hardware atomics. Avoid the performance penalty of `Ordering::SeqCst` unless strict total ordering is mathematically required.
|
|
114
|
+
|
|
115
|
+
```rust
|
|
116
|
+
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
|
117
|
+
|
|
118
|
+
pub struct TelemetryCounters {
|
|
119
|
+
total_requests: AtomicU64,
|
|
120
|
+
active_connections: AtomicU64,
|
|
121
|
+
is_shutting_down: AtomicBool,
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
impl TelemetryCounters {
|
|
125
|
+
pub fn inc_request(&self) {
|
|
126
|
+
// Relaxed ordering: No cross-thread memory synchronization required.
|
|
127
|
+
// Increments local CPU cache without emitting expensive memory bus lock instructions.
|
|
128
|
+
self.total_requests.fetch_add(1, Ordering::Relaxed);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
pub fn mark_shutdown(&self) {
|
|
132
|
+
// Release ordering: Ensures all prior writes are visible to other threads
|
|
133
|
+
self.is_shutting_down.store(true, Ordering::Release);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
pub fn is_terminating(&self) -> bool {
|
|
137
|
+
// Acquire ordering: Synchronizes with the Release store
|
|
138
|
+
self.is_shutting_down.load(Ordering::Acquire)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### Memory Ordering Quick Reference:
|
|
144
|
+
| Ordering | Hardware Cost | Typical Use Case |
|
|
145
|
+
|---|---|---|
|
|
146
|
+
| **`Relaxed`** | Lowest (Single instruction) | Monotonic counters, Prometheus metrics, stats. |
|
|
147
|
+
| **`Acquire` / `Release`** | Low (Cache synchronization barrier) | Thread handoffs, termination flags, lock-free queues. |
|
|
148
|
+
| **`SeqCst`** | Highest (Full memory fence across all CPU cores) | Strict multi-variable consensus (rarely needed). |
|
|
149
|
+
|
|
150
|
+
---
|
|
151
|
+
|
|
152
|
+
## 5. Concurrency Audit Checklist
|
|
153
|
+
|
|
154
|
+
1. Is `tokio::sync::Mutex` used ONLY when lock guards must be held across `.await` points?
|
|
155
|
+
2. Are in-memory, synchronous locks using `parking_lot` instead of `std::sync`?
|
|
156
|
+
3. Are read-heavy configurations ($>95\%$ reads) decoupled using `ArcSwap`?
|
|
157
|
+
4. Are concurrent metrics using `Atomic*` with `Ordering::Relaxed`?
|
|
158
|
+
5. Has Clippy verified that no synchronous mutex guard crosses an `.await` boundary?
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# Docker Slimming & Build Context Hygiene: Achieving Sub-80MB Images
|
|
2
|
+
|
|
3
|
+
Achieving production efficiency requires minimizing **both runtime memory consumption (RSS) and physical Docker image size**. A bloated Docker image wastes registry bandwidth, slows CI/CD deployments, expands vulnerability attack surfaces, and invalidates build caches needlessly.
|
|
4
|
+
|
|
5
|
+
This playbook documents the exact multi-stage container recipe and `.dockerignore` discipline used in **Jandapress** and **Lustpress** to achieve **sub-80MB Debian runtime images** and instant build context transfers.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. Strict `.dockerignore` Discipline (Focus-Only Build Context)
|
|
10
|
+
|
|
11
|
+
Sending local build artifacts, documentation, or git history to the Docker daemon wastes gigabytes of upload bandwidth and breaks Docker layer caching whenever a non-code file changes.
|
|
12
|
+
|
|
13
|
+
### The Production `.dockerignore` Template
|
|
14
|
+
Place this at the root of your Rust repository:
|
|
15
|
+
|
|
16
|
+
```text
|
|
17
|
+
# 1. Local compiler build artifacts (Can be 2GB - 5GB!)
|
|
18
|
+
target
|
|
19
|
+
tools/**/target
|
|
20
|
+
|
|
21
|
+
# 2. VCS and CI/CD pipelines
|
|
22
|
+
.git
|
|
23
|
+
.github
|
|
24
|
+
.agent
|
|
25
|
+
.vscode
|
|
26
|
+
|
|
27
|
+
# 3. Documentation, licenses, and media clutter
|
|
28
|
+
*.md
|
|
29
|
+
**/*.md
|
|
30
|
+
LICENSE
|
|
31
|
+
resources
|
|
32
|
+
resources/**
|
|
33
|
+
|
|
34
|
+
# 4. Environment secrets and schemas (Never bake secrets into images!)
|
|
35
|
+
.env
|
|
36
|
+
.env.*
|
|
37
|
+
!.env.example
|
|
38
|
+
|
|
39
|
+
# 5. Legacy migration artifacts
|
|
40
|
+
legacy
|
|
41
|
+
node_modules
|
|
42
|
+
bun.lock
|
|
43
|
+
package.json
|
|
44
|
+
tsconfig.json
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Why This Matters:
|
|
48
|
+
- **Instant Context Transfer**: Transfers only source code (`src/`, `Cargo.toml`, `Cargo.lock`) to the daemon (under 2MB instead of 3GB+).
|
|
49
|
+
- **Cache Invalidation Protection**: Editing a `README.md`, bumping a workflow, or changing local test data **will not** invalidate your expensive `cargo build` layers.
|
|
50
|
+
- **Secret Leak Prevention**: Prevents developer `.env` files from ever leaking into intermediate Docker layers.
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## 2. Hardened Multi-Stage Build Recipe (Sub-80MB Final Image)
|
|
55
|
+
|
|
56
|
+
A single-stage Dockerfile retains `cargo`, `rustc`, `gcc`, `pkg-config`, and hundreds of megabytes of intermediate `.rlib` / `.o` objects, resulting in images exceeding **1.5GB**.
|
|
57
|
+
|
|
58
|
+
The two-stage multi-stage approach extracts **only** the stripped binary and runtime shared libraries:
|
|
59
|
+
|
|
60
|
+
```dockerfile
|
|
61
|
+
# ========================================================
|
|
62
|
+
# STAGE 1: Builder (Debian Bookworm glibc 2.36)
|
|
63
|
+
# ========================================================
|
|
64
|
+
FROM rust:1.96-slim-bookworm AS builder
|
|
65
|
+
|
|
66
|
+
# Install build-only toolchain dependencies
|
|
67
|
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
68
|
+
pkg-config \
|
|
69
|
+
libssl-dev \
|
|
70
|
+
&& rm -rf /var/lib/apt/lists/*
|
|
71
|
+
|
|
72
|
+
WORKDIR /usr/src/app
|
|
73
|
+
COPY . .
|
|
74
|
+
|
|
75
|
+
# Compile optimized release binary with binary stripping enabled
|
|
76
|
+
RUN cargo build --release
|
|
77
|
+
|
|
78
|
+
# ========================================================
|
|
79
|
+
# STAGE 2: Minimal Production Runtime (Sub-80MB)
|
|
80
|
+
# ========================================================
|
|
81
|
+
FROM debian:bookworm-slim
|
|
82
|
+
|
|
83
|
+
# Install only essential dynamic runtime libraries:
|
|
84
|
+
# 1. ca-certificates: Required for TLS/HTTPS verification in Reqwest
|
|
85
|
+
# 2. libssl3: Required for dynamic OpenSSL linking (matches libssl-dev from builder)
|
|
86
|
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
87
|
+
ca-certificates \
|
|
88
|
+
libssl3 \
|
|
89
|
+
&& rm -rf /var/lib/apt/lists/*
|
|
90
|
+
|
|
91
|
+
WORKDIR /app
|
|
92
|
+
|
|
93
|
+
# Copy ONLY the compiled binary from builder stage
|
|
94
|
+
COPY --from=builder /usr/src/app/target/release/app_binary /app/app_binary
|
|
95
|
+
|
|
96
|
+
# CRITICAL RUNTIME CONFIGURATION:
|
|
97
|
+
# 1. Bounded glibc arenas to eliminate multi-threaded RSS fragmentation
|
|
98
|
+
ENV MALLOC_ARENA_MAX=2
|
|
99
|
+
ENV PORT=3000
|
|
100
|
+
|
|
101
|
+
EXPOSE 3000
|
|
102
|
+
|
|
103
|
+
CMD ["/app/app_binary"]
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## 3. Four Rules for Minimal Image Footprint
|
|
109
|
+
|
|
110
|
+
| Rule | Implementation | Why / Savings |
|
|
111
|
+
| :--- | :--- | :--- |
|
|
112
|
+
| **1. Strip Debug Symbols** | `[profile.release]` with `strip = true` in `Cargo.toml` | Reduces compiled binary size from ~60MB down to ~12MB by stripping unneeded symbol tables. |
|
|
113
|
+
| **2. Clean APT Package Lists** | `rm -rf /var/lib/apt/lists/*` on every `apt-get` layer | Saves 30MB–50MB of cached package metadata in image layers. |
|
|
114
|
+
| **3. Avoid Recommended Packages** | `--no-install-recommends` on `apt-get install` | Prevents Debian from pulling in hundreds of megabytes of documentation, man pages, and optional daemons. |
|
|
115
|
+
| **4. Strict Codename Pairing** | `rust:1.xx-slim-bookworm` ➔ `debian:bookworm-slim` | Guarantees identical glibc 2.36 dynamic ABI without missing symbols or version mismatch crashes. |
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# Scraper & DOM Optimization Playbook: Cutting 80% Memory Bloat
|
|
2
|
+
|
|
3
|
+
Parsing full, unconstrained HTML documents (containing thousands of script tags, ads, comments, and footers) into an in-memory DOM tree allocates millions of transient AST nodes, severely stressing the memory allocator and bloating process RSS.
|
|
4
|
+
|
|
5
|
+
This playbook demonstrates the exact patterns used to achieve sub-50MB RSS memory baselines by pruning raw text strings before AST instantiation.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. Pattern A: Pre-Parse HTML Slicing
|
|
10
|
+
|
|
11
|
+
Never pass a full 5MB–10MB HTML page to `Html::parse_document` when target data is only in the first 20% of the page. Slicing the raw text string *before* parsing prevents the parser from generating thousands of unnecessary DOM nodes.
|
|
12
|
+
|
|
13
|
+
### Detail View vs Search / Related Pruning Strategies
|
|
14
|
+
|
|
15
|
+
```rust
|
|
16
|
+
use scraper::{Html, Selector};
|
|
17
|
+
use std::sync::LazyLock;
|
|
18
|
+
|
|
19
|
+
static SEL_SEARCH_WRAP: LazyLock<Selector> =
|
|
20
|
+
LazyLock::new(|| Selector::parse("div.wrap").unwrap());
|
|
21
|
+
static SEL_SEARCH_TITLE: LazyLock<Selector> =
|
|
22
|
+
LazyLock::new(|| Selector::parse("a[title]").unwrap());
|
|
23
|
+
|
|
24
|
+
pub fn parse_search_optimized(body: &[u8], url: &str) -> Result<Vec<String>, String> {
|
|
25
|
+
let html_str = String::from_utf8_lossy(body);
|
|
26
|
+
let is_related = url.contains("view_video.php");
|
|
27
|
+
|
|
28
|
+
// CRITICAL PRUNING BOUNDARIES:
|
|
29
|
+
// For search listings: prune at pagination or footer.
|
|
30
|
+
// For related videos: do not prune at pagination if comment pagination precedes the related video block.
|
|
31
|
+
let end_pos = if is_related {
|
|
32
|
+
html_str
|
|
33
|
+
.find("<footer")
|
|
34
|
+
.or_else(|| html_str.find("class=\"footer-wrap\""))
|
|
35
|
+
.unwrap_or(html_str.len())
|
|
36
|
+
} else {
|
|
37
|
+
html_str
|
|
38
|
+
.find("class=\"page_numbers\"")
|
|
39
|
+
.or_else(|| html_str.find("class=\"pagination\""))
|
|
40
|
+
.or_else(|| html_str.find("<footer"))
|
|
41
|
+
.or_else(|| html_str.find("class=\"footer-wrap\""))
|
|
42
|
+
.unwrap_or(html_str.len())
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// Parse ONLY the sliced substring:
|
|
46
|
+
let document = Html::parse_document(&html_str[..end_pos]);
|
|
47
|
+
|
|
48
|
+
let mut titles = Vec::new();
|
|
49
|
+
for el in document.select(&SEL_SEARCH_WRAP) {
|
|
50
|
+
if let Some(title_el) = el.select(&SEL_SEARCH_TITLE).next() {
|
|
51
|
+
if let Some(title) = title_el.value().attr("title") {
|
|
52
|
+
titles.push(title.to_string());
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// `document` drops immediately here, freeing all DOM tree nodes from RAM.
|
|
58
|
+
Ok(titles)
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## 2. Pattern B: Compile-Once Static Selectors (`LazyLock`)
|
|
65
|
+
|
|
66
|
+
Compiling CSS selector strings to AST on every request is CPU and memory inefficient. Use `std::sync::LazyLock` (native in modern Rust 1.80+):
|
|
67
|
+
|
|
68
|
+
```rust
|
|
69
|
+
use scraper::Selector;
|
|
70
|
+
use std::sync::LazyLock;
|
|
71
|
+
|
|
72
|
+
// Compiled exactly once during the entire runtime of the binary
|
|
73
|
+
static SEL_CANONICAL: LazyLock<Selector> =
|
|
74
|
+
LazyLock::new(|| Selector::parse("link[rel='canonical']").unwrap());
|
|
75
|
+
static SEL_OG_TITLE: LazyLock<Selector> =
|
|
76
|
+
LazyLock::new(|| Selector::parse("meta[property='og:title']").unwrap());
|
|
77
|
+
static SEL_OG_IMAGE: LazyLock<Selector> =
|
|
78
|
+
LazyLock::new(|| Selector::parse("meta[property='og:image']").unwrap());
|
|
79
|
+
static SEL_OG_DURATION: LazyLock<Selector> =
|
|
80
|
+
LazyLock::new(|| Selector::parse("meta[property='video:duration']").unwrap());
|
|
81
|
+
static SEL_VIEWS: LazyLock<Selector> =
|
|
82
|
+
LazyLock::new(|| Selector::parse("div.views > span.count").unwrap());
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
## 3. Pattern C: Zero-Allocation Byte Slice Parsing for JSON APIs
|
|
88
|
+
|
|
89
|
+
When scraping providers that offer undocumented or internal JSON endpoints (such as Eporner or Txxx in `lustpress`), **never** allocate an intermediate `String` from the network response.
|
|
90
|
+
|
|
91
|
+
Deserialize directly from `&[u8]` using `serde_json::from_slice`:
|
|
92
|
+
|
|
93
|
+
```rust
|
|
94
|
+
use serde::Deserialize;
|
|
95
|
+
|
|
96
|
+
#[derive(Deserialize)]
|
|
97
|
+
pub struct ApiResponse {
|
|
98
|
+
pub id: String,
|
|
99
|
+
pub title: Option<String>,
|
|
100
|
+
pub views: Option<u64>,
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
pub fn parse_direct_slice(bytes: &[u8]) -> Result<ApiResponse, serde_json::Error> {
|
|
104
|
+
// 0 intermediate String allocations; borrows directly from byte buffer
|
|
105
|
+
serde_json::from_slice(bytes)
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
## 4. Pattern D: Regression Unit Testing for Pruning Boundaries
|
|
112
|
+
|
|
113
|
+
Always provide mock HTML tests to verify that your string pruning logic does not prematurely chop valid content cards:
|
|
114
|
+
|
|
115
|
+
```rust
|
|
116
|
+
#[cfg(test)]
|
|
117
|
+
mod tests {
|
|
118
|
+
use super::*;
|
|
119
|
+
|
|
120
|
+
#[test]
|
|
121
|
+
fn test_search_pruning_boundary() {
|
|
122
|
+
let mock_html = r##"
|
|
123
|
+
<html>
|
|
124
|
+
<body>
|
|
125
|
+
<div class="wrap"><a title="Video 1"></a></div>
|
|
126
|
+
<div class="pagination">Page 1, 2, 3</div>
|
|
127
|
+
<div class="unneeded-content">Heavy comments and footer links</div>
|
|
128
|
+
<footer>Footer</footer>
|
|
129
|
+
</body>
|
|
130
|
+
</html>
|
|
131
|
+
"##;
|
|
132
|
+
|
|
133
|
+
let results = parse_search_optimized(mock_html.as_bytes(), "https://example.com/search")
|
|
134
|
+
.expect("Parsing should succeed");
|
|
135
|
+
assert_eq!(results.len(), 1);
|
|
136
|
+
assert_eq!(results[0], "Video 1");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
#[test]
|
|
140
|
+
fn test_related_pruning_with_comment_pagination() {
|
|
141
|
+
let mock_html = r##"
|
|
142
|
+
<html>
|
|
143
|
+
<body>
|
|
144
|
+
<div id="comments"><div class="pagination">Comment page 1</div></div>
|
|
145
|
+
<div class="wrap"><a title="Related Video 1"></a></div>
|
|
146
|
+
<footer>Footer</footer>
|
|
147
|
+
</body>
|
|
148
|
+
</html>
|
|
149
|
+
"##;
|
|
150
|
+
|
|
151
|
+
let results = parse_search_optimized(mock_html.as_bytes(), "https://example.com/view_video.php")
|
|
152
|
+
.expect("Parsing should succeed without truncation from comment pagination");
|
|
153
|
+
assert_eq!(results.len(), 1);
|
|
154
|
+
assert_eq!(results[0], "Related Video 1");
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
```
|