@sinkaroid/rust-shapeshift 1.0.12 → 1.0.13
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/README.md +8 -8
- package/package.json +6 -6
- package/skills/rust-shapeshift/SKILL.md +46 -33
- package/skills/rust-shapeshift/resources/adaptive_concurrency_and_load_shedding.md +9 -0
- package/skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md +9 -0
- package/skills/rust-shapeshift/resources/async_cancellation_safety_and_task_drainage.md +9 -0
- package/skills/rust-shapeshift/resources/axum_and_tower_architecture.md +21 -5
- package/skills/rust-shapeshift/resources/bounded_caching_and_pooling.md +15 -5
- package/skills/rust-shapeshift/resources/bounded_streaming_and_payload_guards.md +9 -0
- package/skills/rust-shapeshift/resources/bounds_check_elimination_and_zero_cost_memory.md +9 -0
- package/skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md +9 -0
- package/skills/rust-shapeshift/resources/collection_reuse_and_capacity_retention.md +9 -0
- package/skills/rust-shapeshift/resources/compiler_niche_optimizations_and_size_assertions.md +9 -0
- package/skills/rust-shapeshift/resources/concurrency_model_checking_and_resource_budgets.md +9 -0
- package/skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md +9 -0
- package/skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md +14 -18
- package/skills/rust-shapeshift/resources/dom_and_scraper_pruning.md +41 -14
- package/skills/rust-shapeshift/resources/enum_variant_boxing_and_stack_squashing.md +8 -0
- package/skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md +20 -1
- package/skills/rust-shapeshift/resources/grpc_tonic_and_http2_memory_tuning.md +9 -0
- package/skills/rust-shapeshift/resources/hidden_drop_offload_and_wcet_contracts.md +9 -0
- package/skills/rust-shapeshift/resources/hot_path_string_and_zero_cost_helpers.md +31 -18
- package/skills/rust-shapeshift/resources/instruction_cache_and_cold_path_outlining.md +9 -0
- package/skills/rust-shapeshift/resources/io_uring_and_zero_syscall_networking.md +8 -0
- package/skills/rust-shapeshift/resources/jemalloc_profiling_and_allocator_switch.md +9 -0
- package/skills/rust-shapeshift/resources/kubernetes_runtime_and_resource_containment.md +41 -29
- package/skills/rust-shapeshift/resources/lock_free_ring_buffers_and_disruptor.md +8 -0
- package/skills/rust-shapeshift/resources/memory_allocator_tuning.md +58 -33
- package/skills/rust-shapeshift/resources/memory_mapped_files_and_zero_copy_paging.md +8 -0
- package/skills/rust-shapeshift/resources/message_queue_and_stream_backpressure.md +8 -0
- package/skills/rust-shapeshift/resources/numa_architecture_and_hugepages.md +8 -0
- package/skills/rust-shapeshift/resources/numeric_safety_and_saturating_arithmetic.md +8 -0
- package/skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md +8 -0
- package/skills/rust-shapeshift/resources/profile_guided_optimization_and_fast_hashing.md +9 -0
- package/skills/rust-shapeshift/resources/rate_limiting_and_state.md +8 -0
- package/skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md +16 -7
- package/skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md +8 -0
- package/skills/rust-shapeshift/resources/redis_connection_and_caching_pitfalls.md +8 -0
- package/skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.md +22 -17
- package/skills/rust-shapeshift/resources/simd_vectorization_and_hardware_acceleration.md +8 -0
- package/skills/rust-shapeshift/resources/sqlx_and_database_pool_memory.md +8 -0
- package/skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md +8 -0
- package/skills/rust-shapeshift/resources/streaming_file_io_and_compression.md +8 -0
- package/skills/rust-shapeshift/resources/telemetry_and_metrics.md +15 -6
- package/skills/rust-shapeshift/resources/thread_per_core_and_shared_nothing.md +8 -0
- package/skills/rust-shapeshift/resources/tokio_thread_starvation_and_cpu_offload.md +11 -2
- package/skills/rust-shapeshift/resources/typestate_domain_proofs_and_buffer_recycling.md +8 -0
- package/skills/rust-shapeshift/resources/wasm_runtime_and_memory_sandboxing.md +8 -0
- package/skills/rust-shapeshift/resources/zero_allocation_error_architecture.md +8 -0
- package/skills/rust-shapeshift/resources/zero_copy_ipc_and_shared_memory.md +8 -0
- package/skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md +9 -0
- package/skills/rust-shapeshift/resources/zero_copy_zero_alloc_serialization_rkyv.md +8 -0
- package/skills/rust-shapeshift/resources/zero_cost_iterators_and_pipeline_inlining.md +8 -0
- package/skills/rust-shapeshift/resources/zero_cost_state_machines_and_enum_dispatch.md +8 -0
- package/skills/rust-shapeshift/resources/zero_overhead_distributed_tracing.md +8 -0
- package/skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md +8 -0
- package/skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md +8 -0
|
@@ -122,3 +122,11 @@ pub fn sort_latencies(latencies: &mut [f64]) {
|
|
|
122
122
|
3. Use `checked_*` for monetary balances, slice indexing math, and memory allocations.
|
|
123
123
|
4. Always use `TryFrom` for narrowing integer casts.
|
|
124
124
|
5. Sort floating-point metrics using `.sort_by(f64::total_cmp)`.
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
129
|
+
|
|
130
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
131
|
+
| :--- | :--- | :--- | :--- |
|
|
132
|
+
| **`saturating_*` / `checked_*` / `TryFrom` / `total_cmp`** | Eliminates wrap-around bugs, panic crashes, and silent `as` truncation | Slightly more verbose than `+` / `as`; `saturating_*` clamps instead of reporting overflow error | Use `checked_*`/`TryFrom` for money, lengths, and indices; `saturating_*` for counters/timers |
|
|
@@ -251,3 +251,11 @@ impl Article<Published> {
|
|
|
251
251
|
3. Are large structs (>2KB) stored via `Box<T>` to keep Tokio `Future` sizes small?
|
|
252
252
|
4. Are struct fields kept private or scoped with `pub(crate)`?
|
|
253
253
|
5. Are domain primitives wrapped in zero-cost Newtypes to enforce validation invariants?
|
|
254
|
+
|
|
255
|
+
---
|
|
256
|
+
|
|
257
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
258
|
+
|
|
259
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
260
|
+
| :--- | :--- | :--- | :--- |
|
|
261
|
+
| **Borrowing (`&str`, `Cow<'a, str>`) Over `.clone()`** | Eliminates redundant heap allocations and keeps `Future` sizes compact | Lifetimes propagate into structs/signatures; over-borrowing across `.await` requires `'static` or `Arc`/`Bytes` | Borrow by default in sync/helper functions; use `Arc<str>`/`Bytes` when shared across spawned async tasks |
|
|
@@ -92,3 +92,12 @@ llvm-bolt target/release/my-backend \
|
|
|
92
92
|
- [ ] Replaced internal integer `HashMap` instances with `FxHashMap` or `AHashMap`.
|
|
93
93
|
- [ ] Preserved default `SipHash` on maps directly exposed to unbounded external user keys.
|
|
94
94
|
- [ ] Profile workloads match realistic traffic shapes rather than artificial micro-benchmarks.
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
99
|
+
|
|
100
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
101
|
+
| :--- | :--- | :--- | :--- |
|
|
102
|
+
| **PGO + LLVM BOLT** | 10%–20% real CPU/I-cache speedup from real branch layout | Significantly slows CI build pipelines (2-stage build + representative load replay) | Use for mature CPU-bound production binaries; skip for rapid dev cycles or I/O-bound scrapers |
|
|
103
|
+
| **`FxHashMap` / `AHashMap`** | Much faster hashing for trusted integer/internal keys | **`FxHash` is NOT HashDoS-resistant** against attacker-controlled keys | Use `FxHashMap` only for trusted internal keys; keep `SipHash` (or `AHashMap`) for external user input |
|
|
@@ -138,3 +138,11 @@ pub async fn apply_progressive_delay(counter: &Counter) {
|
|
|
138
138
|
}
|
|
139
139
|
}
|
|
140
140
|
```
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
145
|
+
|
|
146
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
147
|
+
| :--- | :--- | :--- | :--- |
|
|
148
|
+
| **Bounded `DashMap` + 30s Sweeper** | Hard memory ceiling (`BUCKET_MAX_SIZE`) + zero Redis latency | Single-node state (not shared across multiple replicas); trusting unverified `X-Forwarded-For` allows IP spoofing | Use for single-instance protection with explicit trusted-proxy flag; use Redis for multi-replica global limits |
|
|
@@ -58,15 +58,14 @@ All unit and integration tests for HTML scrapers, DOM pruners, and streaming tex
|
|
|
58
58
|
|
|
59
59
|
### Fixture Curation Guidelines
|
|
60
60
|
|
|
61
|
-
1. **Capture Live Topography**:
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
```
|
|
61
|
+
1. **Capture Live Topography Without Repo Bloat or Secret Leaks**:
|
|
62
|
+
Inspect live production markup during test authoring (e.g. via curl or temporary scratch script), then distill it into **compact, trimmed real DOM snippets inline inside `#[cfg(test)]`**—avoid committing bloated raw `.html` files into `tests/fixtures/` unless the user explicitly asks for external offline fixture files.
|
|
63
|
+
> [!CAUTION]
|
|
64
|
+
> **Zero Sensitive Data Leak Rule**: Never commit real private API domains, internal hostnames, real proxy IPs/credentials, or `.env` values in tests, fixtures, or documentation. Always sanitize any host/IP in captured snippets with `example.com` or RFC 5737 test IPs (`203.0.113.0/24`).
|
|
66
65
|
2. **Preserve Authentic Structural Hierarchies**:
|
|
67
66
|
- Retain exact tag hierarchies, class names, and attribute namespaces (`data-*`, `rel`, `canonical`).
|
|
68
67
|
- Preserve adjacent bloat structures (recommendation carousels, related items, script tags, trackers) to exercise boundary pruning edge cases.
|
|
69
|
-
-
|
|
68
|
+
- Truncate repetitive repeating item rows (e.g., retain 2–3 cards rather than 50), while strictly preserving container boundaries and footer siblings.
|
|
70
69
|
|
|
71
70
|
---
|
|
72
71
|
|
|
@@ -374,5 +373,15 @@ Before completing any task touching HTML parsing, scraping, or string pruning, v
|
|
|
374
373
|
- [ ] **Real-World Fixture Topography**: Test fixtures mirror the exact class names, tag hierarchies, and data attributes of production targets.
|
|
375
374
|
- [ ] **Dual-Assertion Invariants**: Every pruning test verifies that target data is within the slice AND bloat is cleanly excluded.
|
|
376
375
|
- [ ] **Static Selector Alignment**: Selectors tested in unit suites match the exact `static SEL: LazyLock<Selector>` instances used in runtime code.
|
|
377
|
-
- [ ] **Zero-Downgrade Fallback**: Text slicing fast paths are paired with adaptive full-document fallbacks to
|
|
376
|
+
- [ ] **Zero-Downgrade Fallback**: Text slicing fast paths are paired with adaptive full-document fallbacks guarded by `pruned.len() < raw_html.len()` to prevent double-parsing unmodified HTML.
|
|
377
|
+
- [ ] **No Repo Bloat & Zero Leaks**: Prefer compact trimmed real DOM snippets inline in `#[cfg(test)]` over giant `.html` dumps, and verify zero private domains/IPs/credentials leak into fixtures or tests.
|
|
378
378
|
- [ ] **Architectural Integrity**: Never propose reverting memory optimizations when edge cases appear; implement resilient self-healing tiers.
|
|
379
|
+
|
|
380
|
+
---
|
|
381
|
+
|
|
382
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
383
|
+
|
|
384
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
385
|
+
| :--- | :--- | :--- | :--- |
|
|
386
|
+
| **Compact Inline Real DOM Snippets + Dual Assertions** | Tests real selectors & bloat boundaries with zero repo bloat and zero network flakiness | Must sanitize any private domain/IP/secret and update snippet if upstream layout radically changes | Default standard for parser/pruner unit tests; avoid giant `.html` dumps in git and never use `Card 1` placeholders |
|
|
387
|
+
| **Live-Fetch Integration Tests** | Always exercises current live upstream markup | Fails offline/CI under rate-limits, geo-blocks, or Cloudflare | Run optionally (`#[ignore]` or smoke test) alongside offline inline real-DOM unit tests |
|
|
@@ -249,3 +249,11 @@ net.ipv4.tcp_wmem = 4096 16384 4194304
|
|
|
249
249
|
4. Are egress queues strictly bounded, dropping or disconnecting slow consumers via `try_send()`?
|
|
250
250
|
5. Are client heartbeats monitored using a single centralized timer sweep instead of per-socket timers?
|
|
251
251
|
6. Is `TCP_NODELAY` enabled to dispatch small push frames without Nagle algorithm buffering delays?
|
|
252
|
+
|
|
253
|
+
---
|
|
254
|
+
|
|
255
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
256
|
+
|
|
257
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
258
|
+
| :--- | :--- | :--- | :--- |
|
|
259
|
+
| **4KB Buffers + Single-Task Loop + `Bytes` Broadcast** | Scales to 50k–500k concurrent sockets within tight RAM budgets | Drops/disconnects slow consumers on bounded egress queue; requires tuning if messages legitimately exceed 4KB | Use for high-density chat/ticker hubs; size buffer ceiling to real max frame size |
|
|
@@ -228,3 +228,11 @@ CMD ["redis-server", "--requirepass", "app_secret_password"]
|
|
|
228
228
|
```env
|
|
229
229
|
REDIS_URL=redis://:app_secret_password@127.0.0.1:6379
|
|
230
230
|
```
|
|
231
|
+
|
|
232
|
+
---
|
|
233
|
+
|
|
234
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
235
|
+
|
|
236
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
237
|
+
| :--- | :--- | :--- | :--- |
|
|
238
|
+
| **Async Startup `PING` + `Moka` Fallback + URL Masking** | Prevents boot freezes, survives Redis outages, and stops password leaks | In-memory fallback is per-pod and increases local RAM usage while Redis is down | Always use when Redis is optional/shared; keep `sanitize_url_credentials` shared across `REDIS_URL` & `PROXY_URL` |
|
|
@@ -21,18 +21,14 @@ pub fn create_shared_http_client(user_agent: &str) -> reqwest::Client {
|
|
|
21
21
|
|
|
22
22
|
reqwest::Client::builder()
|
|
23
23
|
.default_headers(default_headers)
|
|
24
|
-
// 1.
|
|
25
|
-
.pool_idle_timeout(Duration::from_secs(90))
|
|
26
|
-
.pool_max_idle_per_host(10)
|
|
27
|
-
// 2. TCP Keepalive
|
|
24
|
+
// 1. TCP Keepalive (prevents silent idle connection drops behind NAT/containers)
|
|
28
25
|
.tcp_keepalive(Duration::from_secs(60))
|
|
29
|
-
//
|
|
26
|
+
// 2. Global Hard Timeout (note: pool_idle_timeout(90s), gzip, deflate are reqwest defaults;
|
|
27
|
+
// keep pool_max_idle_per_host at reqwest's default unless FD/host limits demand a cap—
|
|
28
|
+
// clamping to 10 forces TCP+TLS handshakes on connection #11+ under burst concurrency)
|
|
30
29
|
.timeout(Duration::from_secs(15))
|
|
31
|
-
// 4. Native Compression (saves network memory buffers)
|
|
32
|
-
.gzip(true)
|
|
33
|
-
.deflate(true)
|
|
34
30
|
.build()
|
|
35
|
-
.
|
|
31
|
+
.unwrap_or_default()
|
|
36
32
|
}
|
|
37
33
|
```
|
|
38
34
|
|
|
@@ -68,22 +64,22 @@ let location = match client
|
|
|
68
64
|
|
|
69
65
|
## 3. Selective Caching Policy (Preventing Cache Bloat)
|
|
70
66
|
|
|
71
|
-
Never cache
|
|
67
|
+
Never cache or look up volatile endpoints blindly. Endpoints such as `/random` produce infinite unique outputs—checking `self.cache.get(url)` before checking `/random` wastes an entire Redis/Moka round-trip on a guaranteed cache miss:
|
|
72
68
|
|
|
73
69
|
```rust
|
|
74
70
|
pub async fn fetch_body(&self, url: &str) -> Result<Vec<u8>, AppError> {
|
|
75
|
-
// 1.
|
|
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!
|
|
71
|
+
// 1. EXCLUDE random / volatile endpoints BEFORE touching cache (saves Redis GET round-trip!)
|
|
81
72
|
if url.contains("/random") {
|
|
82
73
|
let res = self.client.get(url).send().await?;
|
|
83
74
|
return Ok(res.bytes().await?.to_vec());
|
|
84
75
|
}
|
|
85
76
|
|
|
86
|
-
//
|
|
77
|
+
// 2. Check cache for deterministic endpoints
|
|
78
|
+
if let Some(cached) = self.cache.get(url).await {
|
|
79
|
+
return Ok(cached);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// 3. Fetch and cache only successful deterministic responses
|
|
87
83
|
let res = self.client.get(url).send().await?;
|
|
88
84
|
let bytes = res.bytes().await?.to_vec();
|
|
89
85
|
self.cache.set(url, &bytes).await;
|
|
@@ -128,3 +124,12 @@ pub async fn check_upstream_challenge(mut res: Response) -> Result<bool, reqwest
|
|
|
128
124
|
Ok(false)
|
|
129
125
|
}
|
|
130
126
|
```
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
131
|
+
|
|
132
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
133
|
+
| :--- | :--- | :--- | :--- |
|
|
134
|
+
| **Singleton Client + `tcp_keepalive` (Default Pool Limit)** | Reuses sockets/TLS sessions and stops silent NAT drops without throttling burst concurrency | Unbounded idle pool can hold many sockets if talking to thousands of distinct hosts | Always share one client; **do not** clamp `pool_max_idle_per_host(10)` unless host FD caps require it |
|
|
135
|
+
| **Bypass Cache Lookup Before `/random`** | Eliminates wasted Redis/Moka `GET` round-trips on uncacheable routes | None for volatile endpoints | Always check `/random` exclusion before `self.cache.get(url)` |
|
|
@@ -106,3 +106,11 @@ rustflags = ["-C", "target-cpu=x86-64-v3"] # Enables AVX, AVX2, BMI2, FMA
|
|
|
106
106
|
- [ ] Switched high-throughput UTF-8 parsing to `simdutf8`.
|
|
107
107
|
- [ ] Configured `target-cpu=x86-64-v3` (or equivalent microarchitecture) in `.cargo/config.toml` for container deployment.
|
|
108
108
|
- [ ] Replaced scalar bit-twiddling on bulk payloads with 64-bit or vector aligned word slicing.
|
|
109
|
+
|
|
110
|
+
---
|
|
111
|
+
|
|
112
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
113
|
+
|
|
114
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
115
|
+
| :--- | :--- | :--- | :--- |
|
|
116
|
+
| **`memchr` / `simdutf8` / `target-cpu=x86-64-v3`** | Vectorizes scanning/UTF-8 validation 4x–10x faster than scalar loops | `target-cpu=x86-64-v3` **crashes with `SIGILL`** on older CPUs or ARM64 hosts! | Use portable `memchr`/`simdutf8` (runtime CPU dispatch) freely; only set `target-cpu` when target hardware is strictly known |
|
|
@@ -154,3 +154,11 @@ pub fn configure_connect_options(database_url: &str) -> Result<PgConnectOptions,
|
|
|
154
154
|
- [ ] Database pool `max_connections` is capped according to core counts (typically 5–15 per pod).
|
|
155
155
|
- [ ] Set `acquire_timeout` to fail fast (<3s) rather than letting Tokio worker tasks queue up indefinitely.
|
|
156
156
|
- [ ] Hardened `statement_cache_capacity` on dynamic SQL workloads.
|
|
157
|
+
|
|
158
|
+
---
|
|
159
|
+
|
|
160
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
161
|
+
|
|
162
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
163
|
+
| :--- | :--- | :--- | :--- |
|
|
164
|
+
| **`.fetch()` Row Streaming + Bounded Pool (`5–15`)** | Constant O(1) memory on large result sets and avoids DB connection exhaustion | Holding a streaming DB transaction open longer keeps locks/connections busy | Use `.fetch()` for large exports/reports; `.fetch_all()` is fine for small paginated queries (`LIMIT 20`) |
|
|
@@ -132,3 +132,11 @@ pub fn normalize_slug(input: &str) -> Cow<'_, str> {
|
|
|
132
132
|
3. Are small collections ($\le 4$ items) stored as `SmallVec` instead of `Vec`?
|
|
133
133
|
4. Are constant headers or static error messages typed as `&'static str` or `Cow<'static, str>`?
|
|
134
134
|
5. Has `cargo check` verified that types serialize seamlessly with `serde`?
|
|
135
|
+
|
|
136
|
+
---
|
|
137
|
+
|
|
138
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
139
|
+
|
|
140
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
141
|
+
| :--- | :--- | :--- | :--- |
|
|
142
|
+
| **`compact_str` / `SmallVec` / `Box<str>`** | Eliminates heap allocations for short strings (`<=24B`) and small lists | `SmallVec` bloats stack/enum size if inline capacity is too large; adds external crate types to public APIs | Use `CompactString` / `Box<str>` in internal high-volume structs; keep `String` in simple low-churn configs |
|
|
@@ -95,3 +95,11 @@ pub async fn export_large_csv_stream() -> Response {
|
|
|
95
95
|
- [ ] Switched in-memory compression (`zstd::encode_all`) to streaming encoders (`ZstdEncoder` / `GzipEncoder`).
|
|
96
96
|
- [ ] Configured HTTP download/export endpoints to return chunked `Body::from_stream`.
|
|
97
97
|
- [ ] Multipart file uploads stream directly to disk or S3 without intermediate RAM accumulation.
|
|
98
|
+
|
|
99
|
+
---
|
|
100
|
+
|
|
101
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
102
|
+
|
|
103
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
104
|
+
| :--- | :--- | :--- | :--- |
|
|
105
|
+
| **Chunked `tokio::fs` + `async-compression` Streams** | Compresses/serves multi-GB files in ~64KB RAM | Compression itself is CPU-heavy (can saturate cores under many concurrent streams) | Always stream large files/exports; never buffer whole blobs or run heavy sync compression on Tokio worker threads |
|
|
@@ -21,7 +21,7 @@ pub static METRICS_VSZ: AtomicU64 = AtomicU64::new(0);
|
|
|
21
21
|
pub static SYSTEM_TOTAL_MEM: AtomicU64 = AtomicU64::new(0);
|
|
22
22
|
pub static SYSTEM_USED_MEM: AtomicU64 = AtomicU64::new(0);
|
|
23
23
|
|
|
24
|
-
pub fn spawn_metrics_collector() {
|
|
24
|
+
pub fn spawn_metrics_collector(malloc_trim_enabled: bool) {
|
|
25
25
|
tokio::spawn(async move {
|
|
26
26
|
let mut sys = sysinfo::System::new();
|
|
27
27
|
let pid = sysinfo::Pid::from(std::process::id() as usize);
|
|
@@ -29,8 +29,10 @@ pub fn spawn_metrics_collector() {
|
|
|
29
29
|
loop {
|
|
30
30
|
tokio::time::sleep(Duration::from_secs(15)).await;
|
|
31
31
|
|
|
32
|
-
// 1.
|
|
33
|
-
|
|
32
|
+
// 1. Opt-in only: offload glibc heap trimming to blocking pool (never stall Tokio workers)
|
|
33
|
+
if malloc_trim_enabled {
|
|
34
|
+
let _ = tokio::task::spawn_blocking(crate::util::trim_memory).await;
|
|
35
|
+
}
|
|
34
36
|
|
|
35
37
|
// 2. Measure Tokio Event Loop Lag
|
|
36
38
|
measure_event_loop_lag();
|
|
@@ -121,9 +123,8 @@ pub async fn telemetry_middleware(req: Request<Body>, next: Next) -> Response {
|
|
|
121
123
|
let key = format!("method=\"{method}\",path=\"{matched_path}\",status=\"{status}\"");
|
|
122
124
|
record_request(&key, elapsed);
|
|
123
125
|
|
|
124
|
-
//
|
|
125
|
-
|
|
126
|
-
|
|
126
|
+
// NOTE: NEVER call libc::malloc_trim(0) inside per-request middleware!
|
|
127
|
+
// Doing so locks heap arenas and forces kernel page re-faults on every request.
|
|
127
128
|
res
|
|
128
129
|
}
|
|
129
130
|
```
|
|
@@ -168,3 +169,11 @@ pub async fn metrics_handler() -> impl IntoResponse {
|
|
|
168
169
|
([("Content-Type", "text/plain; version=0.0.4; charset=utf-8")], out)
|
|
169
170
|
}
|
|
170
171
|
```
|
|
172
|
+
|
|
173
|
+
---
|
|
174
|
+
|
|
175
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
176
|
+
|
|
177
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
178
|
+
| :--- | :--- | :--- | :--- |
|
|
179
|
+
| **Hand-Rolled Prometheus + `MatchedPath` + PID `sysinfo`** | Zero telemetry crate bloat and prevents unbounded metric label OOM | Manual text formatting can produce invalid Prometheus syntax if labels aren't escaped; **never call `malloc_trim` inside request middleware** | Use on memory-lean Axum services; gate optional `malloc_trim` behind `MALLOC_TRIM=true` + `spawn_blocking` |
|
|
@@ -147,3 +147,11 @@ async fn handle_connection_locally(mut socket: tokio::net::TcpStream) {
|
|
|
147
147
|
| **Tail Latency (p99.99)** | Millisecond-level jitter spikes | **Deterministic microsecond range** |
|
|
148
148
|
| **Core Scalability** | Diminishing returns past 32 cores | **Linear scaling up to 128+ cores** |
|
|
149
149
|
| **Memory Allocation** | Global allocator lock contention | Core-local arenas (zero lock contention) |
|
|
150
|
+
|
|
151
|
+
---
|
|
152
|
+
|
|
153
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
154
|
+
|
|
155
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
156
|
+
| :--- | :--- | :--- | :--- |
|
|
157
|
+
| **CPU-Pinned Thread-Per-Core + `SO_REUSEPORT`** | Near-linear scaling, >98% L1/L2 hit rate, zero work-stealing contention | **Severe head-of-line blocking** if one core gets a slow task; incompatible with standard `tokio::spawn` work-stealing ecosystem | Use for specialized shared-nothing network proxies/DBs (`monoio`/`glommio`); **skip** for general Axum/Reqwest microservices |
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Tokio is a **cooperative asynchronous runtime**, not a preemptive one. Unlike runtimes with preemptive schedulers that can interrupt long-running tasks, a Tokio worker thread executes an asynchronous task continuously until that task voluntarily yields control at an `.await` boundary.
|
|
4
4
|
|
|
5
|
-
If a worker thread runs heavy, synchronous CPU-bound logic (DOM parsing, large regex scans, decompression, or cryptography), that thread is **blocked**. The I/O reactor on that thread cannot process incoming TCP sockets, leading to severe latency spikes, socket timeouts, and degraded p99 metrics.
|
|
5
|
+
If a worker thread runs heavy, synchronous CPU-bound logic (DOM parsing, large regex scans, gzip/zstd payload compression/decompression, `libc::malloc_trim(0)`, or cryptography), that thread is **blocked**. The I/O reactor on that thread cannot process incoming TCP sockets, leading to severe latency spikes, socket timeouts, and degraded p99 metrics.
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -120,5 +120,14 @@ pub fn spawn_event_loop_monitor() {
|
|
|
120
120
|
|---|---|---|
|
|
121
121
|
| Network I/O (`reqwest`, `redis`, TCP) | `.await` | Tokio Worker Pool |
|
|
122
122
|
| Fast string slicing ($\le 100$ µs) | Direct inline execution | Tokio Worker Pool |
|
|
123
|
-
| Medium DOM / JSON parsing (
|
|
123
|
+
| Medium DOM / JSON parsing or cache compression (>16 KiB) | `tokio::task::spawn_blocking` | Tokio Blocking Pool |
|
|
124
|
+
| Opt-in periodic `libc::malloc_trim(0)` (`MALLOC_TRIM=true`) | `tokio::task::spawn_blocking` (never per-request) | Tokio Blocking Pool |
|
|
124
125
|
| Massive batch CPU calculations | `rayon` inside `spawn_blocking` | Rayon Work-Stealing Pool |
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
130
|
+
|
|
131
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
132
|
+
| :--- | :--- | :--- | :--- |
|
|
133
|
+
| **`tokio::task::spawn_blocking` / `rayon` Offload** | Keeps I/O reactor responsive and prevents health-check/p99 starvation | Thread handoff + owned data move (`'static`) adds ~microseconds overhead (counterproductive for tiny <100µs work) | Offload heavy DOM parses, sync compression (>16 KiB), and opt-in `malloc_trim`; keep tiny string slices inline |
|
|
@@ -252,3 +252,11 @@ impl Drop for PooledBuffer {
|
|
|
252
252
|
```
|
|
253
253
|
|
|
254
254
|
With `PooledBuffer`, frames borrow preallocated buffers and return them to the lock-free pool on drop without involving the OS heap allocator.
|
|
255
|
+
|
|
256
|
+
---
|
|
257
|
+
|
|
258
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
259
|
+
|
|
260
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
261
|
+
| :--- | :--- | :--- | :--- |
|
|
262
|
+
| **Affine Typestates & Constructive Domain Types** | Eliminates runtime state bugs and redundant checks at zero runtime cost | More generic type parameters/boilerplate in signatures | Use for critical protocol/auth lifecycles and validated IDs; keep simple enums for straightforward CRUD |
|
|
@@ -112,3 +112,11 @@ pub fn inspect_guest_memory(
|
|
|
112
112
|
- [ ] Enabled `epoch_interruption(true)` or fuel metering on the `Engine`.
|
|
113
113
|
- [ ] Watchdog task terminates runaway execution after deadline.
|
|
114
114
|
- [ ] Zero-copy host reads directly access `memory.data()` bounds without vector cloning.
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
119
|
+
|
|
120
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
121
|
+
| :--- | :--- | :--- | :--- |
|
|
122
|
+
| **Wasmtime `ResourceLimiter` + Epoch Interruption** | Hard-caps untrusted guest linear RAM and stops infinite loops | Engine compilation + guest instantiation adds baseline memory & startup latency | Use when running untrusted user plugins; skip for trusted internal Rust code |
|
|
@@ -128,3 +128,11 @@ impl IntoResponse for AppError {
|
|
|
128
128
|
2. Are external library errors (`reqwest::Error`, `diesel::result::Error`) wrapped in `Box<...>`?
|
|
129
129
|
3. Are frequent error messages constructed using `&'static str` or `format_compact!` instead of standard `format!`?
|
|
130
130
|
4. Does `IntoResponse` serialize error payloads using borrowed `&str` references?
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
135
|
+
|
|
136
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
137
|
+
| :--- | :--- | :--- | :--- |
|
|
138
|
+
| **Boxed Rare Errors + `&'static str` Messages** | Shrinks `Result<T, E>` on every happy-path return and prevents `format!` churn | Adds 1 heap alloc only when the rare boxed error actually triggers | Always keep `size_of::<AppError>() <= 32B` on hot request paths |
|
|
@@ -97,3 +97,11 @@ impl SharedMemoryBuffer {
|
|
|
97
97
|
- [ ] Stale socket files cleaned up on process startup before binding `UnixListener`.
|
|
98
98
|
- [ ] Large multi-megabyte inter-process transfers use memory-mapped files (`memmap2`) instead of JSON over HTTP.
|
|
99
99
|
- [ ] File permissions on socket files restricted to the designated service user group.
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
104
|
+
|
|
105
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
106
|
+
| :--- | :--- | :--- | :--- |
|
|
107
|
+
| **Unix Domain Sockets (UDS) / `memmap2` IPC** | Bypasses TCP/IP stack overhead and serialization copies on local host | Same-host only (cannot scale across separate containers/nodes without shared volume/network); Windows UDS ergonomics differ | Use for co-located Linux sidecars/daemons; use TCP/gRPC for distributed services |
|
|
@@ -157,3 +157,12 @@ pub fn parse_with_simd(mut raw_bytes: Vec<u8>) -> Result<MyStruct, AppError> {
|
|
|
157
157
|
2. Has `serde_json::Value` been replaced with typed structs that extract only necessary fields?
|
|
158
158
|
3. Is `serde_json::from_slice` used directly on `&[u8]` buffers?
|
|
159
159
|
4. Are large outbound payloads serialized directly into reusable `BytesMut` writers?
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
|
|
163
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
164
|
+
|
|
165
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
166
|
+
| :--- | :--- | :--- | :--- |
|
|
167
|
+
| **`#[serde(borrow)]` + `from_slice` + `BytesMut`** | Zero intermediate `String` allocs during deserialization | **Fails to borrow** if JSON string contains escaped characters (`"`, `
|
|
168
|
+
`) unless typed as `Cow<'a, str>` | Always use `Cow<'a, str>` (not bare `&'a str`) with `#[serde(borrow)]` on JSON; use `from_slice` directly on `&[u8]` |
|
|
@@ -133,3 +133,11 @@ impl BinaryFrameHeader {
|
|
|
133
133
|
- Always run validation (`rkyv::access` or `zerocopy::FromBytes::ref_from_prefix`) before reading archived structs to ensure buffer bounds and alignment invariants hold. Never use unchecked transmutes.
|
|
134
134
|
3. **Cache Storage**:
|
|
135
135
|
- For high-concurrency Redis or RocksDB caches, store byte payloads encoded with `rkyv`. Workers retrieve the bytes and inspect cached structs with **zero deserialization CPU cost and zero heap memory duplication**.
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
140
|
+
|
|
141
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
142
|
+
| :--- | :--- | :--- | :--- |
|
|
143
|
+
| **`rkyv` / `zerocopy` Binary Framing** | 0ns in-place access directly from `&[u8]` without deserialization heap allocs | Binary format (not human-readable JSON), strict alignment/versioning coupling between writer and reader | Use for internal Redis caches, IPC, and binary protocols; keep JSON/`serde` for public HTTP REST APIs |
|
|
@@ -119,3 +119,11 @@ pub fn ingest_records(target: &mut Vec<u32>, source: impl IntoIterator<Item = u3
|
|
|
119
119
|
2. In hot worker loops, use `buffer.drain(..)` or `buffer.clear()` to reuse pre-allocated capacity.
|
|
120
120
|
3. Return `impl Iterator<Item = T>` instead of `Box<dyn Iterator<Item = T>>`.
|
|
121
121
|
4. Prefer iterators over manual indexing (`for i in 0..slice.len()`) to automatically eliminate bounds checks (`BCE`).
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
126
|
+
|
|
127
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
128
|
+
| :--- | :--- | :--- | :--- |
|
|
129
|
+
| **Lazy `impl Iterator` + `.drain()`** | Eliminates intermediate `Vec` allocations and unlocks loop fusion | Deeply chained iterators can slightly slow debug compiles or obscure complex control flow | Default to lazy iterators over `.collect()` intermediates; materialize only when shared or indexed |
|
|
@@ -160,3 +160,11 @@ impl SecureGatewayConnection<Authenticated> {
|
|
|
160
160
|
- Never use runtime flags like `is_authenticated: bool` or `state: u8` when states can be modeled statically via typestates. Compile-time states have **zero runtime memory footprint and zero branch misprediction penalty**.
|
|
161
161
|
3. **Static Size Verification**:
|
|
162
162
|
- Verify that enum variants are balanced using `static_assertions::assert_type_size!`. If one variant is significantly larger (>128 bytes), box only that rare variant to keep the main enum discriminant compact on the stack.
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
167
|
+
|
|
168
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
169
|
+
| :--- | :--- | :--- | :--- |
|
|
170
|
+
| **`enum_dispatch` vs `Box<dyn Trait>`** | Eliminates vtable indirection and enables inlining | Closed set of variants (cannot register external runtime plugins); enum size equals largest variant unless boxed | Use for known closed sets of providers/states; keep `dyn Trait` for open plugin systems or I-cache cold paths |
|
|
@@ -107,3 +107,11 @@ pub fn record_transaction_span(account_id: u64, amount: u64) -> Span {
|
|
|
107
107
|
- [ ] Removed all `#[instrument]` macros from loops, parser functions, and hot-path handlers.
|
|
108
108
|
- [ ] Wrapped `stdout` / file loggers in `tracing_appender::non_blocking` with dedicated `WorkerGuard`.
|
|
109
109
|
- [ ] Span fields avoid `format!` and use borrowed `&str` or numeric types (`u64`, `usize`).
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
114
|
+
|
|
115
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
116
|
+
| :--- | :--- | :--- | :--- |
|
|
117
|
+
| **`release_max_level_info` + `non_blocking` Appender** | Zero runtime cost for stripped debug spans and avoids stdout blocking on Tokio workers | Debug/trace logs cannot be toggled dynamically in release builds; `non_blocking` can drop logs if `WorkerGuard` drops early or queue fills | Use `non_blocking` for high-QPS logging; skip `release_max_level_info` if ops teams need runtime `RUST_LOG=debug` in prod |
|
|
@@ -102,3 +102,11 @@ pub async fn doc_handler() -> impl IntoResponse {
|
|
|
102
102
|
}
|
|
103
103
|
```
|
|
104
104
|
Zero disk I/O, zero runtime template engines, zero heap allocation.
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
109
|
+
|
|
110
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
111
|
+
| :--- | :--- | :--- | :--- |
|
|
112
|
+
| **`#![deny(clippy::unwrap_used, clippy::expect_used)]`** | Prevents worker thread panics and `panic = "abort"` process crashes | Requires explicit `match` / `ok_or` handling (use `cfg_attr(not(test), deny(...))` so tests stay ergonomic) | Enforce on all production server crates; keep `LazyLock` static selectors explicit or helper-wrapped |
|
|
@@ -154,3 +154,11 @@ Every external crate introduced can bring hidden threads, global statics, or bac
|
|
|
154
154
|
- [ ] Idle RSS verified with `ps -o rss -p $(pgrep <bin>)` to be **sub-megabyte (down to ~50KB in continuous production)**.
|
|
155
155
|
- [ ] Static `musl` binary produced with `x86_64-unknown-linux-musl`.
|
|
156
156
|
- [ ] Ephemeral sockets closed immediately after processing (`Connection: close`).
|
|
157
|
+
|
|
158
|
+
---
|
|
159
|
+
|
|
160
|
+
## Trade-Offs: Pros, Cons & When to Skip
|
|
161
|
+
|
|
162
|
+
| Technique / Pattern | Pros | Cons / Regression Risk | When to Use vs Skip |
|
|
163
|
+
| :--- | :--- | :--- | :--- |
|
|
164
|
+
| **Koburi Pattern (`std::net` + `musl`)** | Sub-megabyte (~50KB–1MB) RSS, zero async runtime, tiny static binary | **Cannot multiplex thousands of slow concurrent I/O clients** without thread-per-connection explosion; `musl` lacks `malloc_trim` | Ideal for low-QPS sidecars, monitors, and CLI daemons; **skip** for public APIs, WebSockets, or high-concurrency scrapers |
|