@sinkaroid/rust-shapeshift 1.0.7 → 1.0.8
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
CHANGED
|
@@ -27,10 +27,17 @@ Before selecting libraries, AI agents must determine both the operating mode and
|
|
|
27
27
|
## Production Engineering References
|
|
28
28
|
|
|
29
29
|
> [!IMPORTANT]
|
|
30
|
+
> **The Real-World Testing & Anti-Hallucination Mandate**:
|
|
31
|
+
> AI agents consistently fail in production by authoring synthetic, hallucinated unit tests (`<div class="item">Card 1</div>`) that pass 100% green while proving nothing and masking critical bugs.
|
|
32
|
+
> **All ingestion, scraping, and parsing code MUST be validated using real production fixtures and dual-assertion invariants.** Consult [`real_world_testing_and_dom_fixtures.md`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md) as the mandatory primary testing specification.
|
|
30
33
|
>
|
|
31
34
|
> Before blindly reaching for `tokio` or `axum`, evaluate your workload archetype. A multi-threaded async executor burns 10MB–40MB of idle RSS on thread pools and queues your workload doesn't need. For low-QPS daemons, monitoring sidecars, or CLI utilities, adopt [The Koburi Pattern](skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md) with synchronous blocking I/O, `musl` static linking, and ephemeral sockets to achieve sub-megabyte memory usage.
|
|
32
35
|
|
|
33
|
-
All
|
|
36
|
+
All 58 deep-dive reference guides are located in [`skills/rust-shapeshift/resources`](skills/rust-shapeshift/resources)
|
|
37
|
+
|
|
38
|
+
### Real-World Testing & Verification (Anti-Hallucination Standard)
|
|
39
|
+
|
|
40
|
+
- [`Real-World Testing & DOM Fixtures`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md): Eliminating disconnected synthetic mocks, enforcing the Law of Real DOM Fixtures, dual-assertion invariants (positive extraction + negative bloat severance), and zero-downgrade adaptive self-healing fallbacks.
|
|
34
41
|
|
|
35
42
|
### Memory, Stack & Allocator Optimization
|
|
36
43
|
|
|
@@ -143,14 +150,14 @@ Automatically primes:
|
|
|
143
150
|
Install and follow this skill from https://github.com/sinkaroid/rust-shapeshift
|
|
144
151
|
```
|
|
145
152
|
|
|
146
|
-
Your agent will automatically clone, index, and apply the
|
|
153
|
+
Your agent will automatically clone, index, and apply the 58 production engineering references to your current workspace.
|
|
147
154
|
|
|
148
155
|
---
|
|
149
156
|
|
|
150
157
|
### Native CLI Commands
|
|
151
158
|
|
|
152
159
|
```bash
|
|
153
|
-
rust-shapeshift list # Print all
|
|
160
|
+
rust-shapeshift list # Print all 58 production reference guides and descriptions
|
|
154
161
|
rust-shapeshift audit # Scan current Rust project for memory anti-patterns
|
|
155
162
|
rust-shapeshift mcp # Start Model Context Protocol (MCP) server over stdio
|
|
156
163
|
rust-shapeshift init # Configure agent skill in current directory
|
|
@@ -187,11 +194,16 @@ Or using native binary:
|
|
|
187
194
|
```
|
|
188
195
|
|
|
189
196
|
#### Available MCP Tools
|
|
190
|
-
- `audit_memory_antipatterns`: Scans current workspace for memory bloat, missing `MALLOC_ARENA_MAX`, unoptimized release profile,
|
|
197
|
+
- `audit_memory_antipatterns`: Scans current workspace for memory bloat, missing `MALLOC_ARENA_MAX`, unoptimized release profile, locks across `.await`, and synthetic test fixtures.
|
|
191
198
|
- `inspect_struct_layout`: Computes exact field alignment, wasted padding bytes, optimal reordering, and cache-line false sharing hazards.
|
|
192
199
|
- `calculate_hardware_budget`: Computes worst-case RSS and maximum safe concurrent connections without triggering Linux OOMKilled (Exit Code 137).
|
|
193
|
-
- `explain_recipe`: Retrieves targeted zero-cost implementation snippets and principles from the
|
|
200
|
+
- `explain_recipe`: Retrieves targeted zero-cost implementation snippets and principles from the 58 production guides on-demand.
|
|
194
201
|
- `scaffold_archetype`: Generates verified boilerplates for minimal daemons (`koburi_daemon`), Axum gateways (`axum_gateway`), or zero-copy pipelines (`zero_copy_pipeline`).
|
|
202
|
+
- `verify_test_fixtures`: Audits test suites and fixtures against the Anti-Hallucination Real DOM Standard, detecting synthetic placeholders and missing dual assertions.
|
|
203
|
+
- `profile_future_size`: Analyzes enum variants and future frames, detecting oversized variants (>128B) and generating `Box<T>` stack-squashing recommendations with compile-time assertions.
|
|
204
|
+
- `check_cancellation_safety`: Scans async code and `tokio::select!` branches for drop-hazard operations (`read_exact`, partial writes, lock contention across await).
|
|
205
|
+
- `optimize_serde_zero_copy`: Transforms owned serde payloads (`String`, `Vec<u8>`) into zero-copy borrowed structs (`&'a str`, `Cow<'a, str>`, `#[serde(borrow)]`) to eliminate deserialization heap churn.
|
|
206
|
+
- `generate_hardened_docker`: Generates production-hardened, non-root multi-stage Dockerfiles (<65MB) with Debian Bookworm C-ABI parity, symbol stripping, and `MALLOC_ARENA_MAX=2` memory guarding.
|
|
195
207
|
|
|
196
208
|
|
|
197
209
|
## Legal
|
package/package.json
CHANGED
|
@@ -26,11 +26,11 @@
|
|
|
26
26
|
"license": "MIT",
|
|
27
27
|
"name": "@sinkaroid/rust-shapeshift",
|
|
28
28
|
"optionalDependencies": {
|
|
29
|
-
"@sinkaroid/rust-shapeshift-darwin-arm64": "1.0.
|
|
30
|
-
"@sinkaroid/rust-shapeshift-darwin-x64": "1.0.
|
|
31
|
-
"@sinkaroid/rust-shapeshift-linux-arm64": "1.0.
|
|
32
|
-
"@sinkaroid/rust-shapeshift-linux-x64": "1.0.
|
|
33
|
-
"@sinkaroid/rust-shapeshift-win32-x64": "1.0.
|
|
29
|
+
"@sinkaroid/rust-shapeshift-darwin-arm64": "1.0.8",
|
|
30
|
+
"@sinkaroid/rust-shapeshift-darwin-x64": "1.0.8",
|
|
31
|
+
"@sinkaroid/rust-shapeshift-linux-arm64": "1.0.8",
|
|
32
|
+
"@sinkaroid/rust-shapeshift-linux-x64": "1.0.8",
|
|
33
|
+
"@sinkaroid/rust-shapeshift-win32-x64": "1.0.8"
|
|
34
34
|
},
|
|
35
35
|
"publishConfig": {
|
|
36
36
|
"access": "public"
|
|
@@ -43,5 +43,5 @@
|
|
|
43
43
|
"build": "cargo build --release",
|
|
44
44
|
"test": "node bin/rust-shapeshift.js --help"
|
|
45
45
|
},
|
|
46
|
-
"version": "1.0.
|
|
46
|
+
"version": "1.0.8"
|
|
47
47
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: rust-shapeshift
|
|
3
3
|
author: "@sinkaroid"
|
|
4
|
-
version: "1.0.
|
|
4
|
+
version: "1.0.8"
|
|
5
5
|
repository: "https://github.com/sinkaroid"
|
|
6
6
|
description: Master modern Rust (1.80+ / 2024 Edition) specialized in extreme memory and runtime efficiency. Expert in transforming backend services from any runtime into lean, production-grade Rust with Axum 0.8 as canonical reference architecture while remaining fully stack-adaptable (Actix Web, Salvo, Loco, std::net). Eliminates hundreds of MBs of RSS bloat via framework selection, allocator tuning, DOM pruning, zero-copy parsing, and bounded concurrency. Use PROACTIVELY for Rust architecture, concurrent systems, debugging ownership/deadlocks, or performance profiling.
|
|
7
7
|
metadata:
|
|
@@ -11,6 +11,11 @@ metadata:
|
|
|
11
11
|
|
|
12
12
|
# Rust Shapeshift: Extreme Memory & Runtime Systems Engineering
|
|
13
13
|
|
|
14
|
+
> [!IMPORTANT]
|
|
15
|
+
> **Mandatory Real-World Testing Directive (Anti-Hallucination Standard)**:
|
|
16
|
+
> Autonomous AI agents are **strictly prohibited** from writing unit tests with synthetic, hallucinated placeholders (`<div class="item">Card 1</div>`, generic `.main-content`). All parsing, ingestion, pruning, and serialization logic **MUST** execute against authentic production fixtures with dual-assertion invariants (positive extraction of runtime types via static selectors + negative severance of memory bloat). When optimizations face boundary edge-cases, agents **MUST NEVER** propose reverting optimizations; agents must engineer zero-downgrade adaptive self-healing fallbacks.
|
|
17
|
+
> **Primary Testing Specification**: [`real_world_testing_and_dom_fixtures.md`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md)
|
|
18
|
+
|
|
14
19
|
You are an expert Rust systems architect and concurrency engineer specialized in **maximum memory efficiency and runtime throughput**. You turn bloated, memory-leaking backend services into lean, rock-solid Rust binaries that run indefinitely within tight RSS constraints (<50MB baseline), and architect greenfield native Rust services engineered from day one for zero-cost performance.
|
|
15
20
|
|
|
16
21
|
---
|
|
@@ -73,17 +78,19 @@ When project constraints or user requirements dictate an alternative framework b
|
|
|
73
78
|
|
|
74
79
|
## Instructions
|
|
75
80
|
|
|
76
|
-
1. **
|
|
81
|
+
1. **Enforce Real-World Testing & Production Fixtures (Zero Synthetic Mocks)**:
|
|
82
|
+
Prioritize grounding all parsing, ingestion, and optimization tests in authentic production fixtures ([`real_world_testing_and_dom_fixtures.md`](skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md)). Enforce dual assertions (positive extraction of essential fields via static `LazyLock` selectors + negative severance of bloat). Never author synthetic placeholder mocks, and never propose reverting optimizations when boundary edge-cases arise.
|
|
83
|
+
2. **Classify Operating Mode**:
|
|
77
84
|
- **Mode A (The Shapeshifter / Migration)**: Translating existing services from other stacks into idiomatic Rust without carrying over garbage-collection anti-patterns (DOM retention, unbounded hash maps, per-request client allocations).
|
|
78
85
|
- **Mode B (The Native Architect / Greenfield)**: Designing native Rust services from scratch using modern 1.80+ / 2024 Edition idioms, native async traits, stack-inlining discipline, and sub-50MB RSS targets.
|
|
79
|
-
|
|
86
|
+
3. **Classify Project Archetype & Framework Decision**:
|
|
80
87
|
- **Archetype A (High-Throughput / High-Density Gateway)**: High QPS, WebSocket clusters (50k–500k), gRPC, Tokio multi-thread runtime. Framework selected via [`framework_and_stack_selection_matrix.md`](skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md) (Axum 0.8 as default reference, or Actix Web / Salvo / Loco). Target: <50MB–100MB bounded ceiling.
|
|
81
88
|
- **Archetype B (Sub-Megabyte Minimalist Daemon / Sidecar - The Koburi Pattern)**: Low QPS, polling intervals, container monitors, CLI sidecars. **DO NOT use Tokio, Axum, or async executors**. Use pure `std::net` / `UnixStream` with synchronous blocking I/O, static `musl` linking (`x86_64-unknown-linux-musl`), zero dependencies, and ephemeral on-demand sockets. Target: **sub-megabyte (<1MB, down to ~50KB idle RSS)**.
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
89
|
+
4. **Clarify Constraints**: Define the target memory budget (RSS), concurrency requirements, and deployment environment (Docker/Kubernetes/Linux).
|
|
90
|
+
5. **Choose Architecture & Crates**: Select lean crates suited to the archetype. Never pull in Tokio or connection pools for simple polling daemons.
|
|
91
|
+
6. **Configure Release Profiles**: Ensure `Cargo.toml` specifies `lto = "fat"`, `panic = "abort"`, `codegen-units = 1`, and `strip = "symbols"`.
|
|
92
|
+
7. **Implement with Memory & Concurrency Guards**: Apply pre-parse DOM slicing, glibc arena limits or musl static linking, bounded state, and cancellation-safe async branches.
|
|
93
|
+
8. **Verify & Profile**: Write unit tests with real fixtures, run `cargo clippy -- -D warnings`, and verify zero-cost properties.
|
|
87
94
|
|
|
88
95
|
---
|
|
89
96
|
|
|
@@ -98,13 +105,25 @@ Master modern Rust (1.80+ / 2024 Edition) features, advanced type system mechani
|
|
|
98
105
|
### Active MCP Tool Capabilities (Optional Stdio Server)
|
|
99
106
|
|
|
100
107
|
When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-shapeshift mcp`), AI agents can directly invoke active memory and runtime tools:
|
|
101
|
-
- `audit_memory_antipatterns`: Automatically scans workspace files for glibc arena traps (`MALLOC_ARENA_MAX=2`), unoptimized release profiles,
|
|
108
|
+
- `audit_memory_antipatterns`: Automatically scans workspace files for glibc arena traps (`MALLOC_ARENA_MAX=2`), unoptimized release profiles, synchronous locks across `.await`, and synthetic test fixtures.
|
|
102
109
|
- `inspect_struct_layout`: Computes struct padding bytes, alignment boundaries, field reordering, and cache-line false-sharing hazards.
|
|
103
110
|
- `calculate_hardware_budget`: Computes worst-case RSS ceilings and safe per-connection buffers to prevent Linux OOMKilled (Exit Code 137).
|
|
104
|
-
- `explain_recipe`: Queries the
|
|
111
|
+
- `explain_recipe`: Queries the 58 production engineering references on-demand, returning targeted snippets without bloating context window.
|
|
105
112
|
- `scaffold_archetype`: Generates verified boilerplates for Koburi minimal daemons (<1MB), Axum 0.8 gateways, or zero-copy pipelines.
|
|
113
|
+
- `verify_test_fixtures`: Audits test suites and fixtures against the Anti-Hallucination Real DOM Standard, detecting synthetic placeholders and unexercised boundary invariants.
|
|
114
|
+
- `profile_future_size`: Profiles async enum variants and future frames, detecting oversized variants (>128B) and generating `Box<T>` stack-squashing recommendations with compile-time assertions.
|
|
115
|
+
- `check_cancellation_safety`: Scans async code and `tokio::select!` branches for drop-hazard operations (`read_exact`, partial writes, lock starvation across cancellation).
|
|
116
|
+
- `optimize_serde_zero_copy`: Transforms owned serde payloads (`String`, `Vec<u8>`) into zero-copy borrowed structs (`&'a str`, `Cow<'a, str>`, `#[serde(borrow)]`) to eliminate deserialization heap churn.
|
|
117
|
+
- `generate_hardened_docker`: Generates hardened multi-stage Dockerfiles (<65MB) with Debian Bookworm C-ABI parity, symbol stripping, and `MALLOC_ARENA_MAX=2` memory guarding.
|
|
118
|
+
|
|
119
|
+
### 1. Real-World Testing & Anti-Hallucination Standards
|
|
120
|
+
|
|
121
|
+
- **The Law of Real DOM Fixtures**: Strict prohibition against synthetic, invented DOM placeholders (`.item`, `.main-content`, `Card 1`). All scrapers, decoders, and parsers must be verified against authentic captured production fixtures.
|
|
122
|
+
- **Dual-Assertion Invariant Verification**: Every unit test must assert both positive extraction (primary domain data extractable by static `LazyLock<Selector>` instances) and negative severance (trackers, bloat carousels, and footers severed outside the slice).
|
|
123
|
+
- **Zero-Downgrade Adaptive Self-Healing Fallback**: Never retreating or reverting optimizations due to layout variations; implementing fast-path text slicing paired with automatic full-document re-parsing if sliced output is incomplete.
|
|
124
|
+
- **Modern Hydration Extraction**: Testing and verifying against modern frontend state delivery formats including React Server Component (RSC) streaming (`self.__next_f.push(...)`) and Laravel Inertia.js root view-models (`div#app[data-page]`).
|
|
106
125
|
|
|
107
|
-
###
|
|
126
|
+
### 2. Modern Rust Language Features (1.80+ / 2024 Edition)
|
|
108
127
|
|
|
109
128
|
- Native `async fn in trait` (AFIT) and return-position `impl Trait in trait` (RPITIT) eliminating `#[async_trait]` heap allocation (`Box<dyn Future>`).
|
|
110
129
|
- Const generics, inline `const` blocks (`const { ... }`), and advanced type inference.
|
|
@@ -114,7 +133,7 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
|
|
|
114
133
|
- Procedural and declarative macro systems for clean compile-time abstractions.
|
|
115
134
|
- Module visibility controls, re-exports, and clean workspace architecture.
|
|
116
135
|
|
|
117
|
-
###
|
|
136
|
+
### 3. Ownership, Layout & Zero-Cost Memory Management
|
|
118
137
|
|
|
119
138
|
- Ownership, move semantics, and borrow checker mastery.
|
|
120
139
|
- Reference counting with `Rc`, `Arc`, and `Weak` reference cycles avoidance.
|
|
@@ -124,7 +143,7 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
|
|
|
124
143
|
- Zero-copy data handling using `std::borrow::Cow<'a, str>` and `bytes::Bytes` for cheap reference-counted slicing.
|
|
125
144
|
- Compile-time type-state pattern using Zero-Sized Types (ZSTs) and `PhantomData` to enforce lifecycle state machines.
|
|
126
145
|
|
|
127
|
-
###
|
|
146
|
+
### 4. Linux Memory Allocator Tuning & Docker Slimming
|
|
128
147
|
|
|
129
148
|
- **The Musl Target Trap**: Understanding why `x86_64-unknown-linux-musl` is rejected for high-concurrency REST APIs (due to `mallocng` lock contention, 30%–50% throughput penalty, and lack of `malloc_trim`), establishing **Debian Bookworm (`x86_64-unknown-linux-gnu`)** as the primary target.
|
|
130
149
|
- **Glibc Arena Containment**: Configuring `ENV MALLOC_ARENA_MAX=2` in Dockerfiles to prevent multi-threaded Tokio worker arena fragmentation.
|
|
@@ -139,15 +158,17 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
|
|
|
139
158
|
- Exclude `.env` and `.env.*` to prevent developer secrets from baking into image layers.
|
|
140
159
|
- Keeps build context transfer under 2MB (instead of 3GB+ local compiler artifacts) and prevents non-code file changes from invalidating expensive Docker build layers.
|
|
141
160
|
|
|
142
|
-
###
|
|
161
|
+
### 5. High-Efficiency Scraping & DOM Pruning
|
|
143
162
|
|
|
163
|
+
- **The Law of Real DOM Fixtures (No Synthetic Mocks)**: Strictly prohibiting hallucinatory, synthetic DOM placeholders (`<div class="item">Card 1</div>`). Scrapers must be verified against representative production DOM snippets containing authentic tag hierarchies, class signatures, and attributes.
|
|
144
164
|
- **Pre-Parse HTML Slicing**: Truncating raw HTML text strings (`&html[..end_pos]`) _before_ passing them to `Html::parse_document` to slash 70%–90% of DOM AST node allocations.
|
|
165
|
+
- **Zero-Downgrade Adaptive Self-Healing Fallback**: Always pairing pre-parse text slicing with automatic full-document re-parsing if extracted data is empty or essential fields are missing while `pruned.len() < full_html.len()`. This guarantees zero data loss on unexpected upstream layout shifts.
|
|
145
166
|
- **Static Selectors (`LazyLock`)**: Compiling CSS selectors once at startup using `static SEL: LazyLock<Selector>` instead of recompiling selector ASTs inside request loops.
|
|
146
167
|
- **Direct Byte Slice Deserialization**: Parsing undocumented internal JSON APIs directly from byte buffers using `serde_json::from_slice(bytes)` without creating intermediate `String` instances.
|
|
147
168
|
- **Scope-Confined DOM Lifecycle**: Extracting values immediately into small typed structs and instantly dropping the `Html` document out of scope.
|
|
148
|
-
- **
|
|
169
|
+
- **Dual-Assertion Real-World Testing**: Unit tests must verify both positive extraction invariants (essential fields extractable by static selectors) and negative severance invariants (trackers, recommendation carousels, and footers severed outside the slice).
|
|
149
170
|
|
|
150
|
-
###
|
|
171
|
+
### 6. Async Concurrency & Tokio Reactor Safety
|
|
151
172
|
|
|
152
173
|
- **Reactor Protection**: Strict isolation of blocking operations; offloading synchronous filesystem I/O to `tokio::task::spawn_blocking` and heavy compute to `rayon`.
|
|
153
174
|
- **Lock Boundaries**: Strictly prohibiting `std::sync::MutexGuard` across `.await` points. Using `tokio::sync::Mutex` only when necessary, and preferring lock-free actor channels (`mpsc`/`oneshot`).
|
|
@@ -155,63 +176,65 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
|
|
|
155
176
|
- **Task Orchestration**: Managing concurrent worker groups with `tokio::task::JoinSet` instead of raw `Vec<JoinHandle>`.
|
|
156
177
|
- **Graceful Shutdown**: Trapping `SIGINT` (Ctrl+C) and `SIGTERM` signals and draining tasks cooperatively via `tokio_util::sync::CancellationToken`.
|
|
157
178
|
|
|
158
|
-
###
|
|
179
|
+
### 7. Network Pooling & Tiered Timeouts
|
|
159
180
|
|
|
160
181
|
- **Singleton Client Architecture**: Reusing a single `reqwest::Client` inside `Arc<AppState>` with keep-alive (60s), pool idle timeouts (90s), and max idle connections per host (10).
|
|
161
182
|
- **Tiered Timeouts**: Enforcing standard 15s timeouts for scrapers while applying aggressive **fast-fail 3s timeouts** on ancillary metadata/GeoIP calls to prevent worker thread pinning.
|
|
162
183
|
- **Native Compression**: Configuring `gzip(true)` and `deflate(true)` to reduce network payload memory buffers.
|
|
163
184
|
- **Selective Non-Caching**: Explicitly skipping cache insertion for volatile or `/random` endpoints to avoid cache pollution.
|
|
164
185
|
|
|
165
|
-
###
|
|
186
|
+
### 8. Headless-Free Anti-Bot & Session Resilience
|
|
166
187
|
|
|
167
188
|
- **Eliminating Headless Browsers**: Replacing 500MB+ Chromium (Puppeteer/Playwright) instances with algorithmic challenge solvers in pure Rust.
|
|
168
189
|
- **Single-Flight Cookie Bootstrapping**: Using double-checked `Arc<RwLock<Option<(String, Instant)>>>` locks so concurrent requests share one authentication handshake without thundering herds.
|
|
169
190
|
- **Chunked Early-Break Streaming**: Reading responses in 8KB chunks and terminating immediately when target challenge scripts appear or at a 64KB cap.
|
|
170
191
|
- **Target Page Challenge Invalidation**: Detecting unexpected session expiry on target pages and triggering transparent re-authentication and retry.
|
|
171
192
|
|
|
172
|
-
###
|
|
193
|
+
### 9. Bounded State Management & Caching Resilience
|
|
173
194
|
|
|
174
195
|
- **Solving the Redis Lazy Pool Trap**: Bypassing lazy connection traps in `deadpool-redis` by executing an asynchronous background `PING` check (`test_connection().await`) on server boot.
|
|
175
196
|
- **Hybrid Zero-Downtime Fallback**: Automatically falling back to a bounded in-memory `moka::future::Cache` (`max_capacity(1000)`) if Redis disconnects, ensuring the web service never crashes.
|
|
176
197
|
- **Credential Masking**: Sanitizing sensitive passwords in connection strings before logging (`mask_redis_url`).
|
|
177
198
|
- **Bounded Rate Limiting**: Implementing `DashMap` rate limiters with hard capacity caps (`BUCKET_MAX_SIZE = 50,000`), 30s background sweeping tasks, trusted reverse-proxy header parsing (`cf-connecting-ip`), and progressive slow-down delays.
|
|
178
199
|
|
|
179
|
-
###
|
|
200
|
+
### 10. Production Web Development (Axum 0.8 & GraphQL)
|
|
180
201
|
|
|
181
202
|
- Modern web service architecture using Axum 0.8 and Tower HTTP middleware (CORS, Trace, Timeout).
|
|
182
203
|
- REST and GraphQL parity using `async-graphql` and `async-graphql-axum` with depth and complexity boundaries.
|
|
183
204
|
- Zero-cost query validation using `validator::Validate` derive macros.
|
|
184
205
|
- Serving static OpenAPI / Swagger documentation without dynamic runtime schema compilation.
|
|
185
206
|
|
|
186
|
-
###
|
|
207
|
+
### 11. Zero-Dependency Telemetry & Metric Cardinality
|
|
187
208
|
|
|
188
209
|
- Hand-rolled Prometheus 0.0.4 text format exporter via string buffers, avoiding bloated third-party telemetry crates.
|
|
189
210
|
- **PID-Only Sysinfo**: Refreshing only the running process (`ProcessesToUpdate::Some(&[pid])`) instead of scanning all system PIDs in `/proc`.
|
|
190
211
|
- **Event Loop Lag Detection**: Measuring Tokio scheduler delay using scheduled sub-tasks and `Instant::now()`.
|
|
191
212
|
- **Cardinality Explosion Prevention**: Strictly normalizing metric path labels using `req.extensions().get::<MatchedPath>()` to prevent unbounded hashmap memory growth.
|
|
192
213
|
|
|
193
|
-
###
|
|
214
|
+
### 12. Hot-Path String & Arithmetic Helpers
|
|
194
215
|
|
|
195
216
|
- Single-pass character iterators with boolean state (`last_was_space`) to collapse whitespace without regex engines.
|
|
196
217
|
- Native integer division and modulo (`seconds / 60`, `seconds % 60`) for time formatting instead of heavy date/time crates.
|
|
197
218
|
- Standard-compliant URL query encoding via `form_urlencoded::byte_serialize`.
|
|
198
219
|
- Static regex compilation using `static RE: LazyLock<Regex>` for strictly necessary patterns.
|
|
199
220
|
|
|
200
|
-
###
|
|
221
|
+
### 13. Error Handling & Safety Boundaries
|
|
201
222
|
|
|
202
223
|
- **Zero-Panic Policy**: Enforce `#![deny(clippy::unwrap_used, clippy::expect_used)]` at crate root. Never use `.unwrap()` or `.expect()` in request paths to prevent Tokio worker thread panics, allocator corruption, and orphan locks.
|
|
203
224
|
- Domain errors structured as strongly typed enums using `thiserror` with actionable error descriptions.
|
|
204
225
|
- Application entrypoints and binaries using `anyhow::Result<T>` with rich `.with_context(...)` chains.
|
|
205
226
|
- Clean HTTP status code and JSON error envelope mapping via Axum's `IntoResponse` trait.
|
|
206
227
|
|
|
207
|
-
###
|
|
228
|
+
### 14. Testing & Verification
|
|
208
229
|
|
|
209
|
-
-
|
|
230
|
+
- Real DOM fixture testing using captured production snippets, enforcing dual-assertion invariants (positive extraction + negative bloat severance).
|
|
231
|
+
- Verification of zero-downgrade adaptive self-healing fallbacks when pruning slices are artificially constricted.
|
|
232
|
+
- Unit testing with Rust's built-in test harness and fixtures strictly conforming to production domain hierarchies.
|
|
210
233
|
- Property-based testing with `proptest` for edge cases.
|
|
211
234
|
- Async service testing with `tokio-test` and temporary environment isolation (`temp-env`).
|
|
212
235
|
- Benchmark testing with `criterion.rs` and flamegraph profiling (`cargo-flamegraph`).
|
|
213
236
|
|
|
214
|
-
###
|
|
237
|
+
### 15. Modern Tooling & Cargo Configuration
|
|
215
238
|
|
|
216
239
|
- Router recursion limit for deeply nested routers: `#![recursion_limit = "512"]`.
|
|
217
240
|
- Release profile optimization:
|
|
@@ -232,6 +255,8 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
|
|
|
232
255
|
- Prioritizes physical memory efficiency (RSS) and long-term runtime stability alongside raw throughput.
|
|
233
256
|
- Makes invalid states unrepresentable using Rust's compile-time type system and type-state pattern.
|
|
234
257
|
- Rejects dynamic-language bad habits: avoids unneeded cloning, unbounded maps, dynamic string regexes, and inline client creation.
|
|
258
|
+
- Rejects synthetic test placeholders: Never writes unit tests using hallucinated, invented DOM structures (`<div class="item">Card 1</div>`); validates against authentic production topographies, tests exact selector compilation, and enforces dual-assertion invariants.
|
|
259
|
+
- Champions engineering resilience over retreat: Never proposes reverting optimizations when boundary edge-cases appear; designs self-healing fast-paths and fallback layers (Zero Downgrade).
|
|
235
260
|
- Employs deterministic resource management (RAII), explicitly bounding every collection, pool, and cache.
|
|
236
261
|
- Confines unsafe code strictly to necessary FFI boundaries (e.g. `libc::malloc_trim(0)`) and documents all safety invariants.
|
|
237
262
|
- Writes comprehensive tests, verifying both correctness and pruning boundary safety.
|
|
@@ -277,6 +302,7 @@ When registered as an MCP server (`rust-shapeshift mcp` or `npx @sinkaroid/rust-
|
|
|
277
302
|
|
|
278
303
|
Consult the attached reference guides for complete, production-tested code templates:
|
|
279
304
|
|
|
305
|
+
- `resources/real_world_testing_and_dom_fixtures.md` — The Law of Real DOM Fixtures, eliminating synthetic mock anti-patterns, dual-assertion invariants, and zero-downgrade adaptive self-healing fallbacks.
|
|
280
306
|
- `resources/dom_and_scraper_pruning.md` — Pre-parse HTML slicing (`&html[..end_pos]`), static `LazyLock<Selector>`, zero-copy JSON parsing, and mock HTML tests.
|
|
281
307
|
- `resources/ownership_borrowing_and_memory_decisions.md` — Borrow checker permissions (R/W/O), eliminating `.clone()`, Stack vs Heap decision matrix, Future size containment, and scoped visibility (`pub(crate)`).
|
|
282
308
|
- `resources/stack_inlining_and_allocation_reduction.md` — Zero-allocation type discipline, stack-inlining (`compact_str`), `Box<str>`, and `SmallVec` heap churn elimination.
|
|
@@ -108,9 +108,17 @@ pub fn parse_direct_slice(bytes: &[u8]) -> Result<ApiResponse, serde_json::Error
|
|
|
108
108
|
|
|
109
109
|
---
|
|
110
110
|
|
|
111
|
-
## 4. Pattern D:
|
|
111
|
+
## 4. Pattern D: Real-World Testing & Dual-Assertion Invariants
|
|
112
112
|
|
|
113
|
-
|
|
113
|
+
> [!CAUTION]
|
|
114
|
+
> **Never use disconnected synthetic HTML mocks** (e.g., `<div class="item">Card 1</div>` or generic placeholders). Unit tests on hallucinated DOMs pass green while completely failing in production against live website changes or unexpected layouts. Always test with production fixtures and enforce **The Law of Real DOM Fixtures**.
|
|
115
|
+
|
|
116
|
+
For the comprehensive guide on eliminating synthetic test hallucinations, see [`real_world_testing_and_dom_fixtures.md`](real_world_testing_and_dom_fixtures.md).
|
|
117
|
+
|
|
118
|
+
### Dual-Assertion Invariants & Self-Healing Architecture
|
|
119
|
+
1. **Positive Assertions**: Verify that all essential extracted items reside within the slice and parse cleanly via compiled `LazyLock<Selector>` instances.
|
|
120
|
+
2. **Negative Assertions**: Verify that bloat (trackers, recommendation carousels, heavy footers) is strictly excluded before AST instantiation.
|
|
121
|
+
3. **Adaptive Fallback**: If a slice cuts off data due to an upstream layout shift, automatically fall back to full document parsing (Zero Downgrade).
|
|
114
122
|
|
|
115
123
|
```rust
|
|
116
124
|
#[cfg(test)]
|
|
@@ -118,37 +126,53 @@ mod tests {
|
|
|
118
126
|
use super::*;
|
|
119
127
|
|
|
120
128
|
#[test]
|
|
121
|
-
fn
|
|
122
|
-
|
|
123
|
-
|
|
129
|
+
fn test_search_pruning_real_dom_dual_invariants() {
|
|
130
|
+
// Realistic DOM fixture reflecting production tag hierarchy and sibling bloat
|
|
131
|
+
let production_search_html = r##"
|
|
132
|
+
<!DOCTYPE html><html><head><title>Search Results - Target Service</title></head>
|
|
124
133
|
<body>
|
|
125
|
-
<div
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
134
|
+
<div id="results_wrapper">
|
|
135
|
+
<div class="wrap"><a title="Video 1" href="/v/101">Video 1</a></div>
|
|
136
|
+
<div class="wrap"><a title="Video 2" href="/v/102">Video 2</a></div>
|
|
137
|
+
</div>
|
|
138
|
+
<!-- Bloat starts here: pagination, comment trees, related carousels, and footers -->
|
|
139
|
+
<div class="pagination"><a href="?p=2">2</a><a href="?p=3">3</a></div>
|
|
140
|
+
<div id="comments"><div class="comment">Heavy user comments...</div></div>
|
|
141
|
+
<footer class="footer-wrap">
|
|
142
|
+
<div class="trackers"><script src="https://telemetry.cdn.com/t.js"></script></div>
|
|
143
|
+
</footer>
|
|
144
|
+
</body></html>
|
|
131
145
|
"##;
|
|
132
146
|
|
|
133
|
-
let results = parse_search_optimized(
|
|
134
|
-
.expect("Parsing should succeed");
|
|
135
|
-
|
|
147
|
+
let results = parse_search_optimized(production_search_html.as_bytes(), "https://example.com/search")
|
|
148
|
+
.expect("Parsing should succeed on real DOM slice");
|
|
149
|
+
|
|
150
|
+
// Positive assertions: essential data extracted
|
|
151
|
+
assert_eq!(results.len(), 2);
|
|
136
152
|
assert_eq!(results[0], "Video 1");
|
|
153
|
+
assert_eq!(results[1], "Video 2");
|
|
154
|
+
|
|
155
|
+
// Negative assertions: bloat excluded from sliced processing
|
|
156
|
+
let html_str = String::from_utf8_lossy(production_search_html.as_bytes());
|
|
157
|
+
let end_pos = html_str.find("class=\"pagination\"").unwrap_or(html_str.len());
|
|
158
|
+
let slice = &html_str[..end_pos];
|
|
159
|
+
assert!(!slice.contains("Heavy user comments"), "Comments must be excluded");
|
|
160
|
+
assert!(!slice.contains("footer-wrap"), "Footer must be excluded");
|
|
137
161
|
}
|
|
138
162
|
|
|
139
163
|
#[test]
|
|
140
164
|
fn test_related_pruning_with_comment_pagination() {
|
|
141
|
-
let
|
|
142
|
-
|
|
165
|
+
let production_detail_html = r##"
|
|
166
|
+
<!DOCTYPE html><html><head><title>Detail Page</title></head>
|
|
143
167
|
<body>
|
|
168
|
+
<div id="player-container"><h1>Main Video</h1></div>
|
|
144
169
|
<div id="comments"><div class="pagination">Comment page 1</div></div>
|
|
145
|
-
<div class="wrap"><a title="Related Video 1"
|
|
146
|
-
<footer>Footer</footer>
|
|
147
|
-
</body>
|
|
148
|
-
</html>
|
|
170
|
+
<div class="wrap"><a title="Related Video 1" href="/v/201">Related Video 1</a></div>
|
|
171
|
+
<footer class="footer-wrap">Footer</footer>
|
|
172
|
+
</body></html>
|
|
149
173
|
"##;
|
|
150
174
|
|
|
151
|
-
let results = parse_search_optimized(
|
|
175
|
+
let results = parse_search_optimized(production_detail_html.as_bytes(), "https://example.com/view_video.php")
|
|
152
176
|
.expect("Parsing should succeed without truncation from comment pagination");
|
|
153
177
|
assert_eq!(results.len(), 1);
|
|
154
178
|
assert_eq!(results[0], "Related Video 1");
|
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
# Real-World Testing & DOM Fixtures: Eliminating Synthetic Mock Anti-Patterns
|
|
2
|
+
|
|
3
|
+
> *"A unit test that passes green against an invented, synthetic DOM fixture proves nothing, validates nothing, and protects no one. It breeds false confidence while leaving production ingestion pipelines vulnerable to silent failures and layout drifts."*
|
|
4
|
+
|
|
5
|
+
When optimizing data ingestion pipelines, HTML scrapers, and DOM tree parsers for extreme memory efficiency, the primary optimization is pre-parse string slicing (`&html[..end_pos]`), which eliminates 80%–90% of heap AST allocations.
|
|
6
|
+
|
|
7
|
+
However, unit testing these boundaries frequently falls victim to the **Disconnected Placeholder Anti-Pattern**: engineers and autonomous AI agents construct trivial, synthetic HTML snippets that bear zero structural resemblance to real production targets.
|
|
8
|
+
|
|
9
|
+
This reference guide establishes the mandatory engineering standards for **Real-World Testing**, the curation of production DOM fixtures, dual-assertion invariants, and zero-downgrade adaptive fallbacks in Rust.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 1. The Disconnected Placeholder Anti-Pattern
|
|
14
|
+
|
|
15
|
+
The root flaw in naive parser testing is the generation of synthetic, idealized HTML snippets:
|
|
16
|
+
|
|
17
|
+
```rust
|
|
18
|
+
// ❌ ANTI-PATTERN: DISCONNECTED SYNTHETIC MOCK (DO NOT REPLICATE)
|
|
19
|
+
#[test]
|
|
20
|
+
fn test_naive_pruning_boundary() {
|
|
21
|
+
let mock_html = r#"
|
|
22
|
+
<html><body>
|
|
23
|
+
<div class="main-content"><div class="item">Card 1</div><div class="item">Card 2</div></div>
|
|
24
|
+
<div class="pagination"><a>1</a><a>2</a></div>
|
|
25
|
+
<footer>Heavy footer with tracker scripts and links</footer>
|
|
26
|
+
</body></html>
|
|
27
|
+
"#;
|
|
28
|
+
|
|
29
|
+
let pruned = prune_search_html(mock_html);
|
|
30
|
+
assert!(pruned.contains("Card 1"));
|
|
31
|
+
assert!(!pruned.contains("Heavy footer"));
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### Technical Autopsy: Why Synthetic Fixtures Fail in Production
|
|
36
|
+
|
|
37
|
+
1. **Zero Real-World Selector Coverage**:
|
|
38
|
+
Production websites never use generic structures like `.main-content` or `.item`. Target platforms employ deep nesting, framework-generated class signatures, or vendor-specific naming conventions. Testing against generic placeholders leaves 100% of the compiled CSS selector AST (`static SEL: LazyLock<Selector>`) unexercised against realistic token streams.
|
|
39
|
+
|
|
40
|
+
2. **False-Positive Green Tests**:
|
|
41
|
+
The test passes with `100% Ok` in CI. However, because the test verifies the agent's own hallucinated markup rather than target layout topography, breaking structural changes or invalid selectors in production code pass silently into production.
|
|
42
|
+
|
|
43
|
+
3. **Masking Preceding Sibling Layout Boundaries**:
|
|
44
|
+
*Production Case Study:* Web targets frequently place massive dynamic blocks (recommendation carousels, related media grids, nested comment feeds) **prior** to the semantic `<footer>`. In production parsers, slicing strictly at `<footer>` fails to prune thousands of DOM nodes because the heaviest bloat sits inside preceding sibling containers (e.g. `<div id="related">`). Synthetic mocks omit these preceding sibling blocks, completely masking severe memory leaks and buffer over-allocations.
|
|
45
|
+
|
|
46
|
+
4. **Blindness to Modern Frontend Hydration Architectures**:
|
|
47
|
+
- Modern web architectures migrate away from static JSON blocks (such as `<script id="__NEXT_DATA__">`) to **React Server Components (RSC)** streaming payloads (`self.__next_f.push(...)`) or **Laravel Inertia.js** root attributes (`<div id="app" data-page="...">`).
|
|
48
|
+
- Synthetic mocks validate stale legacy assumptions, creating pipelines that fail on live production deployments.
|
|
49
|
+
|
|
50
|
+
5. **Defeatist Engineering (The Revert Trap)**:
|
|
51
|
+
When questioned about edge-case safety in pre-parse string slicing, developers frequently propose abandoning the optimization entirely and reverting to full DOM parsing. Reversion is an engineering failure. The correct architectural response is **Zero-Downgrade Adaptive Fallback**.
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## 2. The Real-World Fixture Protocol
|
|
56
|
+
|
|
57
|
+
All unit and integration tests for HTML scrapers, DOM pruners, and streaming text decoders **MUST** execute against realistic production DOM fixtures.
|
|
58
|
+
|
|
59
|
+
### Fixture Curation Guidelines
|
|
60
|
+
|
|
61
|
+
1. **Capture Live Topography**:
|
|
62
|
+
Capture representative production markup directly from the target domain using standard HTTP tooling:
|
|
63
|
+
```bash
|
|
64
|
+
curl -sL -A "Mozilla/5.0 (X11; Linux x86_64)" "https://target-domain.com/item/1024" -o tests/fixtures/item_target.html
|
|
65
|
+
```
|
|
66
|
+
2. **Preserve Authentic Structural Hierarchies**:
|
|
67
|
+
- Retain exact tag hierarchies, class names, and attribute namespaces (`data-*`, `rel`, `canonical`).
|
|
68
|
+
- Preserve adjacent bloat structures (recommendation carousels, related items, script tags, trackers) to exercise boundary pruning edge cases.
|
|
69
|
+
- For repository size efficiency, truncate repetitive repeating item rows (e.g., retain 2–3 cards rather than 50), while strictly preserving container boundaries and footer siblings.
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## 3. Dual-Assertion Invariant Verification
|
|
74
|
+
|
|
75
|
+
Scraper and pruning unit tests must enforce symmetrical positive and negative verification invariants:
|
|
76
|
+
|
|
77
|
+
| Verification Stage | Target Invariant | Assertion Rule |
|
|
78
|
+
|---|---|---|
|
|
79
|
+
| **Positive Invariant** | Essential Domain Data | Assert that primary fields (Title, ID, Cover URL, Canonical Link, Metadata) **remain within the slice** AND are **successfully extracted** via production `LazyLock<Selector>` instances. |
|
|
80
|
+
| **Negative Invariant** | Unwanted Memory Bloat | Assert that heavy non-essential DOM nodes (Related carousels, tracker scripts, ads, footers) are **strictly severed outside the slice** (`!pruned.contains(...)`). |
|
|
81
|
+
|
|
82
|
+
### Canonical Real-World Test Blueprint
|
|
83
|
+
|
|
84
|
+
```rust
|
|
85
|
+
use scraper::{Html, Selector};
|
|
86
|
+
use std::sync::LazyLock;
|
|
87
|
+
|
|
88
|
+
// Canonical production selectors compiled once via LazyLock
|
|
89
|
+
static SEL_CONTAINER: LazyLock<Selector> =
|
|
90
|
+
LazyLock::new(|| Selector::parse("div.gallery_right").unwrap());
|
|
91
|
+
static SEL_TITLE: LazyLock<Selector> =
|
|
92
|
+
LazyLock::new(|| Selector::parse("div.info h1, h2.g_title").unwrap());
|
|
93
|
+
static SEL_THUMB: LazyLock<Selector> =
|
|
94
|
+
LazyLock::new(|| Selector::parse("div.gallery_thumb img").unwrap());
|
|
95
|
+
static SEL_PAGES: LazyLock<Selector> =
|
|
96
|
+
LazyLock::new(|| Selector::parse("span.i_text.pages").unwrap());
|
|
97
|
+
static SEL_TAGS: LazyLock<Selector> =
|
|
98
|
+
LazyLock::new(|| Selector::parse("a.tag_btn").unwrap());
|
|
99
|
+
|
|
100
|
+
/// Pre-parse slice boundary eliminating 80%+ DOM AST allocations
|
|
101
|
+
pub fn prune_gallery_html(html: &str) -> &str {
|
|
102
|
+
let end_pos = html
|
|
103
|
+
.find("<div id=\"related\"")
|
|
104
|
+
.or_else(|| html.find("id=\"related\""))
|
|
105
|
+
.or_else(|| html.find("<footer"))
|
|
106
|
+
.or_else(|| html.find("id=\"footer\""))
|
|
107
|
+
.unwrap_or(html.len());
|
|
108
|
+
&html[..end_pos]
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
#[cfg(test)]
|
|
112
|
+
mod tests {
|
|
113
|
+
use super::*;
|
|
114
|
+
|
|
115
|
+
#[test]
|
|
116
|
+
fn test_real_world_dom_dual_invariants() {
|
|
117
|
+
// Realistic production DOM fixture preserving live structural hierarchies
|
|
118
|
+
let production_fixture = r#"
|
|
119
|
+
<!DOCTYPE html>
|
|
120
|
+
<html lang="en">
|
|
121
|
+
<head>
|
|
122
|
+
<title>Sample Item Release - Target Platform</title>
|
|
123
|
+
<link rel="canonical" href="https://target-platform.com/item/59026/">
|
|
124
|
+
</head>
|
|
125
|
+
<body>
|
|
126
|
+
<div id="content_wrapper">
|
|
127
|
+
<div class="gallery_right">
|
|
128
|
+
<div class="info">
|
|
129
|
+
<h1>Sample Production Item 59026</h1>
|
|
130
|
+
</div>
|
|
131
|
+
<div class="gallery_thumb">
|
|
132
|
+
<img src="//cdn.target-platform.com/covers/59026/cover.jpg"
|
|
133
|
+
data-src="//cdn.target-platform.com/covers/59026/cover.jpg"
|
|
134
|
+
alt="Cover Thumbnail" />
|
|
135
|
+
</div>
|
|
136
|
+
<span class="i_text pages">Pages: 42</span>
|
|
137
|
+
<div class="tag_list">
|
|
138
|
+
<a class="tag_btn" href="/tag/system/">System <span>1,200</span></a>
|
|
139
|
+
<a class="tag_btn" href="/tag/runtime/">Runtime <span>850</span></a>
|
|
140
|
+
</div>
|
|
141
|
+
</div>
|
|
142
|
+
</div>
|
|
143
|
+
|
|
144
|
+
<!-- Heavy Bloat Boundary: Recommendation Carousel (thousands of AST nodes) -->
|
|
145
|
+
<div id="related">
|
|
146
|
+
<div class="related_card"><a href="/item/99001/">Related Item 1</a></div>
|
|
147
|
+
<div class="related_card"><a href="/item/99002/">Related Item 2</a></div>
|
|
148
|
+
</div>
|
|
149
|
+
|
|
150
|
+
<footer id="footer">
|
|
151
|
+
<div class="tracker_scripts">
|
|
152
|
+
<script src="https://telemetry.thirdparty.com/analytics.js"></script>
|
|
153
|
+
</div>
|
|
154
|
+
</footer>
|
|
155
|
+
</body>
|
|
156
|
+
</html>
|
|
157
|
+
"#;
|
|
158
|
+
|
|
159
|
+
// 1. Execute Memory-Bounded Text Slicing
|
|
160
|
+
let pruned = prune_gallery_html(production_fixture);
|
|
161
|
+
|
|
162
|
+
// 2. Negative Assertions: Verify bloat nodes are severed from memory
|
|
163
|
+
assert!(!pruned.contains("Related Item 1"), "Recommendation carousel must be severed");
|
|
164
|
+
assert!(!pruned.contains("telemetry.thirdparty.com"), "Trackers must be severed");
|
|
165
|
+
assert!(!pruned.contains("id=\"footer\""), "Footer must be severed");
|
|
166
|
+
|
|
167
|
+
// 3. Positive Assertions: Verify essential textual tokens persist
|
|
168
|
+
assert!(pruned.contains("Sample Production Item 59026"));
|
|
169
|
+
assert!(pruned.contains("//cdn.target-platform.com/covers/59026/cover.jpg"));
|
|
170
|
+
assert!(pruned.contains("Pages: 42"));
|
|
171
|
+
|
|
172
|
+
// 4. Selector Verification: Parse pruned slice into scoped AST
|
|
173
|
+
let doc = Html::parse_document(pruned);
|
|
174
|
+
|
|
175
|
+
let title = doc
|
|
176
|
+
.select(&SEL_TITLE)
|
|
177
|
+
.next()
|
|
178
|
+
.map(|el| el.text().collect::<String>())
|
|
179
|
+
.unwrap_or_default();
|
|
180
|
+
assert_eq!(title.trim(), "Sample Production Item 59026");
|
|
181
|
+
|
|
182
|
+
let cover_url = doc
|
|
183
|
+
.select(&SEL_THUMB)
|
|
184
|
+
.next()
|
|
185
|
+
.and_then(|el| el.value().attr("src"))
|
|
186
|
+
.unwrap_or_default();
|
|
187
|
+
assert_eq!(cover_url, "//cdn.target-platform.com/covers/59026/cover.jpg");
|
|
188
|
+
|
|
189
|
+
let tags: Vec<String> = doc
|
|
190
|
+
.select(&SEL_TAGS)
|
|
191
|
+
.map(|el| el.text().collect::<String>().trim().to_string())
|
|
192
|
+
.collect();
|
|
193
|
+
assert!(tags.iter().any(|t| t.contains("System")));
|
|
194
|
+
assert!(tags.iter().any(|t| t.contains("Runtime")));
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
---
|
|
200
|
+
|
|
201
|
+
## 4. Zero-Downgrade Adaptive Self-Healing Fallback
|
|
202
|
+
|
|
203
|
+
To eliminate the risk of upstream website layout drift cutting off valid content without abandoning memory optimization, production architectures employ a **two-tier self-healing parser**:
|
|
204
|
+
|
|
205
|
+
```
|
|
206
|
+
Inbound Raw HTML Payload
|
|
207
|
+
│
|
|
208
|
+
▼
|
|
209
|
+
┌─────────────────────────┐
|
|
210
|
+
│ Fast Path: Text Pruning │ <- Slashes 80%-90% RSS Allocations
|
|
211
|
+
│ (&html[..end_pos]) │
|
|
212
|
+
└────────────┬────────────┘
|
|
213
|
+
│
|
|
214
|
+
▼
|
|
215
|
+
┌─────────────────────────┐
|
|
216
|
+
│ Html::parse_document │
|
|
217
|
+
│ (Tuned Sub-AST Tree) │
|
|
218
|
+
└────────────┬────────────┘
|
|
219
|
+
│
|
|
220
|
+
▼
|
|
221
|
+
Domain Model Extracted?
|
|
222
|
+
╱ ╲
|
|
223
|
+
╱ ╲
|
|
224
|
+
YES╱ ╲NO (Empty & String Was Sliced)
|
|
225
|
+
│ │
|
|
226
|
+
▼ ▼
|
|
227
|
+
Return Data ┌─────────────────────────┐
|
|
228
|
+
│ Self-Healing Tier: │ <- Zero Data Loss
|
|
229
|
+
│ Re-Parse Full Document │
|
|
230
|
+
│ (Emit Metric Alert) │
|
|
231
|
+
└────────────┬────────────┘
|
|
232
|
+
│
|
|
233
|
+
▼
|
|
234
|
+
Return Extracted Data
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
### Self-Healing Pipeline Implementation
|
|
238
|
+
|
|
239
|
+
```rust
|
|
240
|
+
use scraper::{Html, Selector};
|
|
241
|
+
use std::sync::LazyLock;
|
|
242
|
+
use tracing::warn;
|
|
243
|
+
|
|
244
|
+
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
245
|
+
pub struct ScrapedPayload {
|
|
246
|
+
pub title: String,
|
|
247
|
+
pub cover_url: String,
|
|
248
|
+
pub page_count: u32,
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
static SEL_TITLE: LazyLock<Selector> =
|
|
252
|
+
LazyLock::new(|| Selector::parse("div.info h1, meta[property='og:title']").unwrap());
|
|
253
|
+
static SEL_COVER: LazyLock<Selector> =
|
|
254
|
+
LazyLock::new(|| Selector::parse("div.gallery_thumb img, .cover img").unwrap());
|
|
255
|
+
static SEL_PAGES: LazyLock<Selector> =
|
|
256
|
+
LazyLock::new(|| Selector::parse("span.i_text.pages").unwrap());
|
|
257
|
+
|
|
258
|
+
pub fn parse_gallery_adaptive(raw_html: &str) -> Option<ScrapedPayload> {
|
|
259
|
+
// 1. FAST PATH: Slice HTML string (cuts 80%+ AST memory overhead)
|
|
260
|
+
let end_pos = raw_html
|
|
261
|
+
.find("<div id=\"related\"")
|
|
262
|
+
.or_else(|| raw_html.find("<footer"))
|
|
263
|
+
.or_else(|| raw_html.find("id=\"footer\""))
|
|
264
|
+
.unwrap_or(raw_html.len());
|
|
265
|
+
|
|
266
|
+
let pruned = &raw_html[..end_pos];
|
|
267
|
+
let fast_doc = Html::parse_document(pruned);
|
|
268
|
+
let extracted = extract_domain_fields(&fast_doc);
|
|
269
|
+
|
|
270
|
+
// 2. SELF-HEALING FALLBACK: If extraction yielded empty data but the payload was sliced,
|
|
271
|
+
// automatically re-parse the full document to guarantee zero data loss.
|
|
272
|
+
if extracted.is_none() && pruned.len() < raw_html.len() {
|
|
273
|
+
warn!(
|
|
274
|
+
pruned_bytes = pruned.len(),
|
|
275
|
+
total_bytes = raw_html.len(),
|
|
276
|
+
"Pruning boundary dropped valid data; executing self-healing full document parse"
|
|
277
|
+
);
|
|
278
|
+
let full_doc = Html::parse_document(raw_html);
|
|
279
|
+
return extract_domain_fields(&full_doc);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
extracted
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
fn extract_domain_fields(doc: &Html) -> Option<ScrapedPayload> {
|
|
286
|
+
let title = doc
|
|
287
|
+
.select(&SEL_TITLE)
|
|
288
|
+
.next()?
|
|
289
|
+
.text()
|
|
290
|
+
.collect::<String>()
|
|
291
|
+
.trim()
|
|
292
|
+
.to_string();
|
|
293
|
+
|
|
294
|
+
let cover_url = doc
|
|
295
|
+
.select(&SEL_COVER)
|
|
296
|
+
.next()
|
|
297
|
+
.and_then(|el| el.value().attr("src").or_else(|| el.value().attr("data-src")))?
|
|
298
|
+
.to_string();
|
|
299
|
+
|
|
300
|
+
let page_count = doc
|
|
301
|
+
.select(&SEL_PAGES)
|
|
302
|
+
.next()
|
|
303
|
+
.and_then(|el| {
|
|
304
|
+
let txt = el.text().collect::<String>();
|
|
305
|
+
txt.chars().filter(|c| c.is_ascii_digit()).collect::<String>().parse().ok()
|
|
306
|
+
})
|
|
307
|
+
.unwrap_or(1);
|
|
308
|
+
|
|
309
|
+
Some(ScrapedPayload {
|
|
310
|
+
title,
|
|
311
|
+
cover_url,
|
|
312
|
+
page_count,
|
|
313
|
+
})
|
|
314
|
+
}
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
---
|
|
318
|
+
|
|
319
|
+
## 5. Modern Hydration Payload Extraction
|
|
320
|
+
|
|
321
|
+
Target platforms that migrate to modern frontend frameworks must be tested against realistic streaming or serialized state payloads.
|
|
322
|
+
|
|
323
|
+
### 5.1 Next.js App Router (React Server Component Streaming)
|
|
324
|
+
|
|
325
|
+
Modern Next.js platforms stream serialized component state via `self.__next_f.push`:
|
|
326
|
+
|
|
327
|
+
```rust
|
|
328
|
+
/// Extracts serialized JSON payloads from React Server Component streaming chunks
|
|
329
|
+
pub fn extract_next_rsc_payload(html: &str, target_key: &str) -> Option<String> {
|
|
330
|
+
let mut search_idx = 0;
|
|
331
|
+
while let Some(pos) = html[search_idx..].find("self.__next_f.push(") {
|
|
332
|
+
let absolute_pos = search_idx + pos;
|
|
333
|
+
let window = &html[absolute_pos..];
|
|
334
|
+
if window.contains(target_key) {
|
|
335
|
+
if let Some(start_quote) = window.find('"') {
|
|
336
|
+
if let Some(end_quote) = window[start_quote + 1..].find("\"]") {
|
|
337
|
+
let escaped = &window[start_quote + 1..start_quote + 1 + end_quote];
|
|
338
|
+
return Some(escaped.replace("\\\"", "\"").replace("\\\\", "\\"));
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
search_idx = absolute_pos + 20;
|
|
343
|
+
}
|
|
344
|
+
None
|
|
345
|
+
}
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
### 5.2 Laravel Inertia.js Hydration Payloads
|
|
349
|
+
|
|
350
|
+
Applications built on Inertia.js pass full view-model state through HTML root attributes:
|
|
351
|
+
|
|
352
|
+
```rust
|
|
353
|
+
use scraper::{Html, Selector};
|
|
354
|
+
use std::sync::LazyLock;
|
|
355
|
+
|
|
356
|
+
static SEL_INERTIA: LazyLock<Selector> =
|
|
357
|
+
LazyLock::new(|| Selector::parse("div#app[data-page]").unwrap());
|
|
358
|
+
|
|
359
|
+
pub fn extract_inertia_view_model(doc: &Html) -> Option<String> {
|
|
360
|
+
doc.select(&SEL_INERTIA)
|
|
361
|
+
.next()
|
|
362
|
+
.and_then(|el| el.value().attr("data-page"))
|
|
363
|
+
.map(|raw| html_escape::decode_html_entities(raw).to_string())
|
|
364
|
+
}
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
---
|
|
368
|
+
|
|
369
|
+
## 6. Engineering Verification Checklist
|
|
370
|
+
|
|
371
|
+
Before completing any task touching HTML parsing, scraping, or string pruning, verify:
|
|
372
|
+
|
|
373
|
+
- [ ] **Zero Synthetic Mocks**: No test uses invented generic placeholders (`.main-content`, `.item`, `Card 1`).
|
|
374
|
+
- [ ] **Real-World Fixture Topography**: Test fixtures mirror the exact class names, tag hierarchies, and data attributes of production targets.
|
|
375
|
+
- [ ] **Dual-Assertion Invariants**: Every pruning test verifies that target data is within the slice AND bloat is cleanly excluded.
|
|
376
|
+
- [ ] **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 guard against upstream layout shifts.
|
|
378
|
+
- [ ] **Architectural Integrity**: Never propose reverting memory optimizations when edge cases appear; implement resilient self-healing tiers.
|