@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,122 @@
|
|
|
1
|
+
# Adaptive Concurrency Limits and Load Shedding
|
|
2
|
+
|
|
3
|
+
Fixed rate limits and static thread pools break down when downstream resources (database connection pools, third-party microservices) degrade in latency. When response times increase from 10ms to 2 seconds, requests queue up in memory, memory consumption balloons, and the service crashes under cascading timeouts.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Little's Law and Dynamic Concurrency
|
|
8
|
+
|
|
9
|
+
Little's Law defines the relationship between concurrency ($L$), arrival rate ($\lambda$), and latency ($W$):
|
|
10
|
+
$$L = \lambda \times W$$
|
|
11
|
+
|
|
12
|
+
When system latency ($W$) doubles due to downstream pressure, the service must **reduce** allowed in-flight requests ($L$) to maintain stable memory and prevent queuing explosions.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## 2. Adaptive Concurrency Middleware with Tower
|
|
17
|
+
|
|
18
|
+
Instead of an arbitrary hardcoded limit (e.g. `10,000 requests`), use dynamic concurrency limits based on gradient feedback or Vegas algorithms:
|
|
19
|
+
|
|
20
|
+
```rust
|
|
21
|
+
use tower::limit::ConcurrencyLimit;
|
|
22
|
+
use tower::ServiceBuilder;
|
|
23
|
+
use axum::{routing::get, Router, http::StatusCode};
|
|
24
|
+
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
25
|
+
use std::sync::Arc;
|
|
26
|
+
|
|
27
|
+
#[derive(Clone)]
|
|
28
|
+
pub struct DynamicLoadShedder {
|
|
29
|
+
current_inflight: Arc<AtomicUsize>,
|
|
30
|
+
max_inflight_ceiling: usize,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
impl DynamicLoadShedder {
|
|
34
|
+
pub fn new(max_inflight_ceiling: usize) -> Self {
|
|
35
|
+
Self {
|
|
36
|
+
current_inflight: Arc::new(AtomicUsize::new(0)),
|
|
37
|
+
max_inflight_ceiling,
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
pub fn try_acquire(&self) -> Option<InFlightGuard> {
|
|
42
|
+
let current = self.current_inflight.fetch_add(1, Ordering::SeqCst);
|
|
43
|
+
if current >= self.max_inflight_ceiling {
|
|
44
|
+
self.current_inflight.fetch_sub(1, Ordering::SeqCst);
|
|
45
|
+
None // Over capacity: Shed load immediately
|
|
46
|
+
} else {
|
|
47
|
+
Some(InFlightGuard {
|
|
48
|
+
counter: Arc::clone(&self.current_inflight),
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
pub struct InFlightGuard {
|
|
55
|
+
counter: Arc<AtomicUsize>,
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
impl Drop for InFlightGuard {
|
|
59
|
+
fn drop(&mut self) {
|
|
60
|
+
self.counter.fetch_sub(1, Ordering::SeqCst);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## 3. Fast-Fail Load Shedding in Axum
|
|
68
|
+
|
|
69
|
+
Shed excess load immediately with `503 Service Unavailable` or `429 Too Many Requests` before allocating request bodies or queuing worker tasks:
|
|
70
|
+
|
|
71
|
+
```rust
|
|
72
|
+
use axum::{
|
|
73
|
+
middleware::{self, Next},
|
|
74
|
+
response::{IntoResponse, Response},
|
|
75
|
+
extract::{State, Request},
|
|
76
|
+
http::StatusCode,
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
pub async fn load_shedding_middleware(
|
|
80
|
+
State(shedder): State<DynamicLoadShedder>,
|
|
81
|
+
req: Request,
|
|
82
|
+
next: Next,
|
|
83
|
+
) -> Response {
|
|
84
|
+
match shedder.try_acquire() {
|
|
85
|
+
Some(_guard) => {
|
|
86
|
+
// Under capacity limit: proceed with processing
|
|
87
|
+
next.run(req).await
|
|
88
|
+
}
|
|
89
|
+
None => {
|
|
90
|
+
// Over capacity limit: Fast-fail to protect server memory & queues
|
|
91
|
+
(
|
|
92
|
+
StatusCode::SERVICE_UNAVAILABLE,
|
|
93
|
+
[("Retry-After", "2")],
|
|
94
|
+
"Server load limit exceeded. Please retry.",
|
|
95
|
+
).into_response()
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## 4. Upstream Backpressure & Graceful Degradation
|
|
104
|
+
|
|
105
|
+
Combine load shedding with priority tiers:
|
|
106
|
+
1. **Critical Path** (e.g., `/healthz`, `/api/v1/checkout`): Allowed with reserved headroom buffer.
|
|
107
|
+
2. **Non-Critical Path** (e.g., `/api/v1/analytics`, `/metrics`, background scans): Shed first when in-flight counts exceed 70% of ceiling.
|
|
108
|
+
|
|
109
|
+
```rust
|
|
110
|
+
pub fn is_sheddable_route(path: &str) -> bool {
|
|
111
|
+
!path.starts_with("/healthz") && !path.starts_with("/api/v1/checkout")
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## 5. Production Checklist
|
|
118
|
+
|
|
119
|
+
- [ ] Replaced static unbounded queues with bounded in-flight ceilings.
|
|
120
|
+
- [ ] Configured fast-fail `503 Service Unavailable` with `Retry-After` header before parsing bodies.
|
|
121
|
+
- [ ] Priority routes (checkout, health probes) bypass shedding guards.
|
|
122
|
+
- [ ] Drop guard ensures in-flight counters decrement even on unexpected panic or cancellation.
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# Headless-Free Anti-Bot Handling & Single-Flight Cookie Bootstrapping
|
|
2
|
+
|
|
3
|
+
Offloading anti-bot challenges, age verification gates, or dynamic cookies to headless browser instances (such as Chromium) consumes **300MB to 1GB of RAM per instance**, utterly defeating memory efficiency and low-latency throughput goals. In native high-performance Rust, these challenges are solved directly in code via single-flight synchronization and reverse-engineered cryptographic or mathematical algorithms.
|
|
4
|
+
|
|
5
|
+
This playbook demonstrates how to eliminate headless browsers entirely using:
|
|
6
|
+
1. **Algorithmic Challenge Solvers**: Reverse-engineering the challenge directly in Rust.
|
|
7
|
+
2. **Single-Flight Cookie Bootstrapping**: Using `Arc<RwLock<...>>` to ensure only one worker thread authenticates, while all concurrent requests wait and reuse the acquired cookie.
|
|
8
|
+
3. **Chunked Early-Break Response Streaming**: Reading only the header script without buffering full pages.
|
|
9
|
+
4. **Target Page Challenge Invalidation & Retry**: Automatically re-authenticating if an expired session token is rejected mid-flight.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 1. Single-Flight Cookie Cache with `RwLock`
|
|
14
|
+
|
|
15
|
+
Avoid the "thundering herd" problem where 100 concurrent inbound requests all trigger redundant authentication requests simultaneously:
|
|
16
|
+
|
|
17
|
+
```rust
|
|
18
|
+
use std::sync::Arc;
|
|
19
|
+
use std::time::{Duration, Instant};
|
|
20
|
+
use tokio::sync::RwLock;
|
|
21
|
+
|
|
22
|
+
#[derive(Clone)]
|
|
23
|
+
pub struct AuthService {
|
|
24
|
+
client: reqwest::Client,
|
|
25
|
+
// Holds the cached session cookie and the timestamp it was acquired
|
|
26
|
+
session_cookie: Arc<RwLock<Option<(String, Instant)>>>,
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
impl AuthService {
|
|
30
|
+
pub async fn get_valid_cookie(&self) -> Result<String, anyhow::Error> {
|
|
31
|
+
// 1. Fast path: Read lock check (non-blocking for concurrent readers)
|
|
32
|
+
{
|
|
33
|
+
let guard = self.session_cookie.read().await;
|
|
34
|
+
if let Some((cookie, timestamp)) = guard.as_ref() {
|
|
35
|
+
if timestamp.elapsed() < Duration::from_secs(3600) {
|
|
36
|
+
return Ok(cookie.clone());
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// 2. Slow path: Acquire write lock for single-flight bootstrapping
|
|
42
|
+
let mut guard = self.session_cookie.write().await;
|
|
43
|
+
|
|
44
|
+
// Double-check: Another thread might have acquired the cookie while we waited for the write lock
|
|
45
|
+
if let Some((cookie, timestamp)) = guard.as_ref() {
|
|
46
|
+
if timestamp.elapsed() < Duration::from_secs(3600) {
|
|
47
|
+
return Ok(cookie.clone());
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
tracing::info!("Bootstrapping session cookies via algorithmic challenge solver...");
|
|
52
|
+
let fresh_cookie = self.bootstrap_session_cookies().await?;
|
|
53
|
+
|
|
54
|
+
// Cache the newly resolved cookie
|
|
55
|
+
*guard = Some((fresh_cookie.clone(), Instant::now()));
|
|
56
|
+
|
|
57
|
+
// Release temporary heap pages
|
|
58
|
+
crate::util::trim_memory();
|
|
59
|
+
|
|
60
|
+
Ok(fresh_cookie)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## 2. Chunked Early-Break Streaming for Challenge Tokens
|
|
68
|
+
|
|
69
|
+
Do not download 2MB of HTML and ads when the challenge token is in the first `<script>` tag inside `<head>`:
|
|
70
|
+
|
|
71
|
+
```rust
|
|
72
|
+
use reqwest::Response;
|
|
73
|
+
|
|
74
|
+
pub async fn extract_challenge_script(mut res: Response) -> Result<String, anyhow::Error> {
|
|
75
|
+
let mut text = String::new();
|
|
76
|
+
|
|
77
|
+
// Stream 8KB chunks
|
|
78
|
+
while let Ok(Some(chunk)) = res.chunk().await {
|
|
79
|
+
if let Ok(s) = std::str::from_utf8(&chunk) {
|
|
80
|
+
text.push_str(s);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Break immediately once the target challenge block has arrived
|
|
84
|
+
if text.contains("challengeFunction") && text.contains("</script>") {
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Hard cap: Never read more than 64KB for a challenge token
|
|
89
|
+
if text.len() >= 65_536 {
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Explicitly drop response to release the TCP socket back to the pool
|
|
95
|
+
drop(res);
|
|
96
|
+
|
|
97
|
+
Ok(text)
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## 3. Detecting Challenges on Target Pages with Automatic Retry
|
|
104
|
+
|
|
105
|
+
If upstream invalidates the session cookie unexpectedly, invalidate the lock and perform one transparent retry:
|
|
106
|
+
|
|
107
|
+
```rust
|
|
108
|
+
impl AuthService {
|
|
109
|
+
pub async fn fetch_with_auto_reauth(&self, url: &str) -> Result<Vec<u8>, anyhow::Error> {
|
|
110
|
+
let cookie = self.get_valid_cookie().await?;
|
|
111
|
+
let res = self.client.get(url).header("Cookie", &cookie).send().await?;
|
|
112
|
+
let bytes = res.bytes().await?.to_vec();
|
|
113
|
+
|
|
114
|
+
// Check if the upstream returned the challenge page instead of data
|
|
115
|
+
if String::from_utf8_lossy(&bytes).contains("leastFactor") {
|
|
116
|
+
tracing::warn!("Session cookie invalidated by upstream. Re-authenticating...");
|
|
117
|
+
|
|
118
|
+
// Invalidate current cookie
|
|
119
|
+
{
|
|
120
|
+
let mut guard = self.session_cookie.write().await;
|
|
121
|
+
*guard = None;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Re-acquire fresh cookie
|
|
125
|
+
let fresh_cookie = self.get_valid_cookie().await?;
|
|
126
|
+
|
|
127
|
+
// Retry request
|
|
128
|
+
let retry_res = self.client.get(url).header("Cookie", fresh_cookie).send().await?;
|
|
129
|
+
let retry_bytes = retry_res.bytes().await?.to_vec();
|
|
130
|
+
|
|
131
|
+
crate::util::trim_memory();
|
|
132
|
+
return Ok(retry_bytes);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
crate::util::trim_memory();
|
|
136
|
+
Ok(bytes)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
```
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Arena Allocation and Bump Memory Architecture
|
|
2
|
+
|
|
3
|
+
In data transformation pipelines, HTML/JSON parsing trees, AST generation, and per-request lifecycles, applications often allocate thousands of small individual structs. Allocating and deallocating each object independently creates allocator overhead, heap fragmentation, and CPU cache misses.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. How Bump Allocation Works
|
|
8
|
+
|
|
9
|
+
An Arena / Bump Allocator (such as `bumpalo`) reserves a single contiguous chunk of memory. Allocating a new object simply advances ("bumps") an offset pointer:
|
|
10
|
+
- **Allocation Speed**: Pointer addition ($O(1)$) with zero locks and zero system calls.
|
|
11
|
+
- **Cache Locality**: Objects allocated sequentially sit next to each other in CPU L1/L2 cache lines.
|
|
12
|
+
- **Deallocation Speed**: The entire arena is reclaimed in a single operation ($O(1)$) by resetting the pointer (`bump.reset()`), bypassing individual `free()` system calls.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## 2. Request-Scoped Arena Allocation with `bumpalo`
|
|
17
|
+
|
|
18
|
+
Add `bumpalo` to `Cargo.toml`:
|
|
19
|
+
```toml
|
|
20
|
+
[dependencies]
|
|
21
|
+
bumpalo = { version = "3.16", features = ["collections"] }
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Use a bump arena for short-lived AST nodes or batch objects:
|
|
25
|
+
|
|
26
|
+
```rust
|
|
27
|
+
use bumpalo::Bump;
|
|
28
|
+
use bumpalo::collections::Vec as BumpVec;
|
|
29
|
+
|
|
30
|
+
pub struct AstNode<'a> {
|
|
31
|
+
pub tag: &'a str,
|
|
32
|
+
pub children: BumpVec<'a, &'a AstNode<'a>>,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
pub fn parse_syntax_tree_in_arena<'a>(input: &'a str, arena: &'a Bump) -> &'a AstNode<'a> {
|
|
36
|
+
// Allocates inside linear bump memory chunk
|
|
37
|
+
let root = arena.alloc(AstNode {
|
|
38
|
+
tag: "root",
|
|
39
|
+
children: BumpVec::new_in(arena),
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// Sub-allocations are trivial pointer advances
|
|
43
|
+
for token in input.split_whitespace() {
|
|
44
|
+
let child = arena.alloc(AstNode {
|
|
45
|
+
tag: token,
|
|
46
|
+
children: BumpVec::new_in(arena),
|
|
47
|
+
});
|
|
48
|
+
root.children.push(child);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
root
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
pub fn execute_batch_workload() {
|
|
55
|
+
let mut arena = Bump::with_capacity(64 * 1024); // 64KB arena
|
|
56
|
+
|
|
57
|
+
for batch_item in 0..10_000 {
|
|
58
|
+
let _tree = parse_syntax_tree_in_arena("item data tokens", &arena);
|
|
59
|
+
// Process _tree...
|
|
60
|
+
|
|
61
|
+
// RESET: Frees all allocated nodes instantly in O(1) without system calls
|
|
62
|
+
arena.reset();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## 3. When to Use Arena Allocation
|
|
70
|
+
|
|
71
|
+
| Use Arena Allocation (`bumpalo`) | Use Standard Heap Allocator |
|
|
72
|
+
| :--- | :--- |
|
|
73
|
+
| Request-scoped parsing (AST, DOM, GraphQL query trees) | Long-lived state surviving across multiple requests |
|
|
74
|
+
| Graph/tree algorithms with complex cross-references | Objects with differing, non-uniform lifecycles |
|
|
75
|
+
| Batch workers processing millions of ephemeral records | Shared state inside `Arc<RwLock<T>>` |
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## 4. Production Checklist
|
|
80
|
+
|
|
81
|
+
- [ ] Replaced per-node `Box::new()` in AST/tree parsing with `arena.alloc()`.
|
|
82
|
+
- [ ] Pre-allocated arena capacity (`Bump::with_capacity(bytes)`) matching average request size.
|
|
83
|
+
- [ ] Recycled arena per batch using `arena.reset()` to eliminate heap fragmentation.
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# Async Cancellation Safety & Graceful Task Drainage
|
|
2
|
+
|
|
3
|
+
In asynchronous Rust (Tokio), futures are driven to completion cooperatively. When an async operation is cancelled—such as when a client aborts an HTTP request, a timeout fires, or a branch loses the race in `tokio::select!`—the losing future is **immediately dropped** at its current `.await` point.
|
|
4
|
+
|
|
5
|
+
If the dropped future was executing a non-atomic operation (such as reading an exact number of bytes, sending a multi-step database transaction, or popping a job from a queue), state is permanently corrupted or lost.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. The Anatomy of a Cancellation Bug
|
|
10
|
+
|
|
11
|
+
Consider this naive timeout pattern:
|
|
12
|
+
|
|
13
|
+
```rust
|
|
14
|
+
// ❌ WRONG: Non-cancellation-safe data corruption
|
|
15
|
+
tokio::select! {
|
|
16
|
+
res = socket.read_exact(&mut header_buf) => {
|
|
17
|
+
// If read_exact reads 3 out of 8 bytes before timeout fires...
|
|
18
|
+
}
|
|
19
|
+
_ = tokio::time::sleep(Duration::from_millis(50)) => {
|
|
20
|
+
// ...The remaining 5 bytes are lost! Socket state is permanently desynchronized!
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
When `tokio::time::sleep` completes first, `socket.read_exact` is dropped. The 3 bytes already read from the OS buffer are discarded with the future. Any subsequent read on `socket` starts at byte 4, resulting in payload corruption.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 2. Cancellation Safety Reference Matrix
|
|
30
|
+
|
|
31
|
+
| Asynchronous Operation | Cancellation Safe? | Failure Mode if Cancelled |
|
|
32
|
+
|---|---|---|
|
|
33
|
+
| `tokio::time::sleep` | **YES** | Timer stops, no side effects. |
|
|
34
|
+
| `tokio::sync::mpsc::Receiver::recv` | **YES** | Item stays in queue or is returned; never lost. |
|
|
35
|
+
| `tokio::sync::broadcast::Receiver::recv` | **YES** | Message remains in ring buffer. |
|
|
36
|
+
| `tokio::io::AsyncReadExt::read` | **YES** | Bytes read are already in your buffer. |
|
|
37
|
+
| `tokio::io::AsyncReadExt::read_exact` | **NO** | Partial reads are discarded. |
|
|
38
|
+
| `tokio::io::AsyncWriteExt::write_all` | **NO** | Partial writes leave the recipient with corrupted data. |
|
|
39
|
+
| `tokio::sync::Mutex::lock` | **YES** | Waiter is removed from queue cleanly. |
|
|
40
|
+
| `deadpool::managed::Pool::get` | **YES** | Connection checkout is clean or cancelled. |
|
|
41
|
+
| Multi-step DB/Redis Transactions | **NO** | Intermediate states persist without commit. |
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## 3. Pattern: Making Unsafe Writes Safe
|
|
46
|
+
|
|
47
|
+
When sending framed payloads or executing multi-step writes that must not be interrupted mid-stream, encapsulate the operation in a dedicated task or decouple cancellation:
|
|
48
|
+
|
|
49
|
+
```rust
|
|
50
|
+
use tokio::io::AsyncWriteExt;
|
|
51
|
+
use tokio::sync::mpsc;
|
|
52
|
+
|
|
53
|
+
pub struct SafeWriter {
|
|
54
|
+
sender: mpsc::Sender<bytes::Bytes>,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
impl SafeWriter {
|
|
58
|
+
pub fn new<W: AsyncWriteExt + Unpin + Send + 'static>(mut writer: W) -> Self {
|
|
59
|
+
let (tx, mut rx) = mpsc::channel::<bytes::Bytes>(256);
|
|
60
|
+
|
|
61
|
+
// Dedicated writer task: CANNOT be cancelled by downstream HTTP client drops
|
|
62
|
+
tokio::spawn(async move {
|
|
63
|
+
while let Some(chunk) = rx.recv().await {
|
|
64
|
+
if let Err(e) = writer.write_all(&chunk).await {
|
|
65
|
+
tracing::error!("Background write error: {e}");
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
Self { sender: tx }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
pub async fn send_chunk(&self, chunk: bytes::Bytes) -> Result<(), AppError> {
|
|
75
|
+
self.sender.send(chunk).await.map_err(|_| AppError::Internal("Writer closed".into()))
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## 4. Graceful Task Drainage with `JoinSet` and `CancellationToken`
|
|
83
|
+
|
|
84
|
+
Never use unbounded `tokio::spawn` for background tasks without tracking their lifecycle. Fire-and-forget tasks get abruptly killed on SIGTERM, corrupting state and dropping in-flight writes.
|
|
85
|
+
|
|
86
|
+
Use **`tokio::task::JoinSet`** coupled with **`tokio_util::sync::CancellationToken`**:
|
|
87
|
+
|
|
88
|
+
```toml
|
|
89
|
+
# Cargo.toml
|
|
90
|
+
[dependencies]
|
|
91
|
+
tokio-util = "0.7"
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
```rust
|
|
95
|
+
use tokio::task::JoinSet;
|
|
96
|
+
use tokio_util::sync::CancellationToken;
|
|
97
|
+
use std::time::Duration;
|
|
98
|
+
|
|
99
|
+
pub struct WorkerPool {
|
|
100
|
+
token: CancellationToken,
|
|
101
|
+
tasks: JoinSet<()>,
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
impl WorkerPool {
|
|
105
|
+
pub fn new() -> Self {
|
|
106
|
+
Self {
|
|
107
|
+
token: CancellationToken::new(),
|
|
108
|
+
tasks: JoinSet::new(),
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
pub fn spawn_worker(&mut self, worker_id: u32) {
|
|
113
|
+
let cancel = self.token.clone();
|
|
114
|
+
self.tasks.spawn(async move {
|
|
115
|
+
loop {
|
|
116
|
+
tokio::select! {
|
|
117
|
+
_ = cancel.cancelled() => {
|
|
118
|
+
// 🛑 Clean shutdown signal received: finish atomic work and exit
|
|
119
|
+
tracing::info!(worker_id, "Worker gracefully draining...");
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
_ = tokio::time::sleep(Duration::from_millis(500)) => {
|
|
123
|
+
// Perform atomic work batch
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
pub async fn shutdown(mut self) {
|
|
131
|
+
// 1. Broadcast shutdown signal to all workers
|
|
132
|
+
self.token.cancel();
|
|
133
|
+
|
|
134
|
+
// 2. Wait for all workers to finish their current work (with timeout)
|
|
135
|
+
let drain_timeout = tokio::time::timeout(Duration::from_secs(10), async {
|
|
136
|
+
while let Some(res) = self.tasks.join_next().await {
|
|
137
|
+
if let Err(e) = res {
|
|
138
|
+
tracing::error!("Worker join error: {e}");
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
if drain_timeout.await.is_err() {
|
|
144
|
+
tracing::warn!("Shutdown timed out; aborting lingering background tasks");
|
|
145
|
+
self.tasks.shutdown().await;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
---
|
|
152
|
+
|
|
153
|
+
## 5. Cancellation Safety Checklist
|
|
154
|
+
|
|
155
|
+
1. Are all branches inside `tokio::select!` verified against the Cancellation Safety Matrix?
|
|
156
|
+
2. Are `read_exact` and `write_all` operations shielded from arbitrary drop cancellations?
|
|
157
|
+
3. Are background tasks tracked inside a `JoinSet` rather than detached `tokio::spawn` calls?
|
|
158
|
+
4. Does the shutdown handler broadcast a `CancellationToken` and drain background tasks cleanly before exit?
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
# Production Axum 0.8 Architecture & Tower Middleware
|
|
2
|
+
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
## 1. Project Directory Layout
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
src/
|
|
9
|
+
├── main.rs # Entrypoint, signal trapping, graceful shutdown
|
|
10
|
+
├── state.rs # Shared AppState (Client, Cache, Config)
|
|
11
|
+
├── config.rs # Environment loading via dotenvy
|
|
12
|
+
├── error.rs # Domain errors (thiserror) & Axum IntoResponse
|
|
13
|
+
├── util.rs # trim_memory() & formatting helpers
|
|
14
|
+
├── metrics.rs # Telemetry middleware & Prometheus export
|
|
15
|
+
├── routes/
|
|
16
|
+
│ ├── mod.rs # Router assembly & middleware stacking
|
|
17
|
+
│ ├── rest.rs # REST endpoint handlers
|
|
18
|
+
│ └── status.rs # Health check & system diagnostics
|
|
19
|
+
└── services/ # Business logic, scrapers, DB integration
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## 2. Server Entrypoint & Graceful Shutdown (`src/main.rs`)
|
|
25
|
+
|
|
26
|
+
```rust
|
|
27
|
+
use axum::Router;
|
|
28
|
+
use std::net::SocketAddr;
|
|
29
|
+
use std::sync::Arc;
|
|
30
|
+
use tokio::signal;
|
|
31
|
+
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
|
32
|
+
|
|
33
|
+
mod config;
|
|
34
|
+
mod error;
|
|
35
|
+
mod metrics;
|
|
36
|
+
mod routes;
|
|
37
|
+
mod state;
|
|
38
|
+
mod util;
|
|
39
|
+
|
|
40
|
+
#[tokio::main]
|
|
41
|
+
async fn main() -> anyhow::Result<()> {
|
|
42
|
+
dotenvy::dotenv().ok();
|
|
43
|
+
|
|
44
|
+
tracing_subscriber::registry()
|
|
45
|
+
.with(tracing_subscriber::EnvFilter::try_from_default_env()
|
|
46
|
+
.unwrap_or_else(|_| "info,app=debug".into()))
|
|
47
|
+
.with(tracing_subscriber::fmt::layer())
|
|
48
|
+
.init();
|
|
49
|
+
|
|
50
|
+
let cfg = config::Config::from_env()?;
|
|
51
|
+
let state = Arc::new(state::AppState::new(&cfg)?);
|
|
52
|
+
|
|
53
|
+
let app = routes::create_router(state);
|
|
54
|
+
|
|
55
|
+
let addr = SocketAddr::from(([0, 0, 0, 0], cfg.port));
|
|
56
|
+
tracing::info!("Server listening on http://{}", addr);
|
|
57
|
+
|
|
58
|
+
let listener = tokio::net::TcpListener::bind(addr).await?;
|
|
59
|
+
axum::serve(listener, app)
|
|
60
|
+
.with_graceful_shutdown(shutdown_signal())
|
|
61
|
+
.await?;
|
|
62
|
+
|
|
63
|
+
tracing::info!("Server shut down cleanly.");
|
|
64
|
+
Ok(())
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async fn shutdown_signal() {
|
|
68
|
+
let ctrl_c = async {
|
|
69
|
+
signal::ctrl_c().await.expect("Failed to install Ctrl+C handler");
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
#[cfg(unix)]
|
|
73
|
+
let terminate = async {
|
|
74
|
+
signal::unix::signal(signal::unix::SignalKind::terminate())
|
|
75
|
+
.expect("Failed to install SIGTERM handler")
|
|
76
|
+
.recv()
|
|
77
|
+
.await;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
#[cfg(not(unix))]
|
|
81
|
+
let terminate = std::future::pending::<()>();
|
|
82
|
+
|
|
83
|
+
tokio::select! {
|
|
84
|
+
_ = ctrl_c => tracing::info!("Received Ctrl+C, draining connections..."),
|
|
85
|
+
_ = terminate => tracing::info!("Received SIGTERM, draining connections..."),
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## 3. Centralized Domain Error Mapping (`src/error.rs`)
|
|
93
|
+
|
|
94
|
+
```rust
|
|
95
|
+
use axum::{
|
|
96
|
+
http::StatusCode,
|
|
97
|
+
response::{IntoResponse, Response},
|
|
98
|
+
Json,
|
|
99
|
+
};
|
|
100
|
+
use serde_json::json;
|
|
101
|
+
use thiserror::Error;
|
|
102
|
+
|
|
103
|
+
#[derive(Error, Debug)]
|
|
104
|
+
pub enum AppError {
|
|
105
|
+
#[error("Resource not found: {0}")]
|
|
106
|
+
NotFound(String),
|
|
107
|
+
|
|
108
|
+
#[error("Validation error: {0}")]
|
|
109
|
+
Validation(String),
|
|
110
|
+
|
|
111
|
+
#[error("Upstream service returned error status {status} for {url}")]
|
|
112
|
+
Upstream {
|
|
113
|
+
status: reqwest::StatusCode,
|
|
114
|
+
url: String,
|
|
115
|
+
},
|
|
116
|
+
|
|
117
|
+
#[error("Internal system error: {0}")]
|
|
118
|
+
Internal(String),
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
impl IntoResponse for AppError {
|
|
122
|
+
fn into_response(self) -> Response {
|
|
123
|
+
let (status, message) = match &self {
|
|
124
|
+
AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()),
|
|
125
|
+
AppError::Validation(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
|
|
126
|
+
AppError::Upstream { status, url } => {
|
|
127
|
+
tracing::warn!(%status, %url, "Upstream error encountered");
|
|
128
|
+
(StatusCode::BAD_GATEWAY, "Upstream service error".to_string())
|
|
129
|
+
}
|
|
130
|
+
AppError::Internal(err) => {
|
|
131
|
+
tracing::error!(%err, "Internal failure");
|
|
132
|
+
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error".to_string())
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
let body = Json(json!({
|
|
137
|
+
"success": false,
|
|
138
|
+
"error": message,
|
|
139
|
+
"status": status.as_u16(),
|
|
140
|
+
}));
|
|
141
|
+
|
|
142
|
+
(status, body).into_response()
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
```
|