@sinkaroid/rust-shapeshift 1.0.2 → 1.0.4
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 +52 -52
- package/package.json +7 -7
- package/skills/rust-shapeshift/SKILL.md +41 -6
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# Rust Shapeshift
|
|
2
2
|
|
|
3
|
-
`@sinkaroid/rust-shapeshift`
|
|
3
|
+
`@sinkaroid/rust-shapeshift` is an AI agent skill specialized in **extreme memory and runtime efficiency** for Rust backend architectures. It enforces deterministic resource containment, zero-allocation data paths, and allocator-level memory reclamation across long-running production workloads.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Universally compatible with all AI agent runtimes.
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -17,10 +17,10 @@ Before selecting libraries, AI agents must determine both the operating mode and
|
|
|
17
17
|
2. **The Native Architect (Greenfield Mode)**:
|
|
18
18
|
Architects native Rust services from scratch targeting modern Rust 1.80+ / 2024 Edition with baseline memory consumption (<50MB RSS), stack inlining (`compact_str`), bounded buffers, zero-copy parsing, and deterministic resource lifecycles.
|
|
19
19
|
|
|
20
|
-
### 2. Workload Archetypes
|
|
20
|
+
### 2. Workload Archetypes & Framework Adaptability
|
|
21
21
|
|
|
22
|
-
- **Archetype A (High-Throughput / High-Density Gateway)**: High QPS, WebSocket clusters (50k–500k), gRPC, Tokio multi-thread runtime,
|
|
23
|
-
- **Archetype B (Sub-Megabyte Minimalist Daemon / Sidecar - The Koburi Pattern)**: Low QPS, polling intervals, container monitors, CLI sidecars. **DO NOT use Tokio 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)**.
|
|
22
|
+
- **Archetype A (High-Throughput / High-Density Gateway)**: High QPS, WebSocket clusters (50k–500k), gRPC, Tokio multi-thread runtime, bounded Moka caches, connection pooling. **Axum 0.8 is adopted as the canonical reference architecture**, while remaining fully adaptable to **Actix Web**, **Salvo**, or **Loco** via the [Framework & Stack Selection Matrix](skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md). Target: <50MB–100MB bounded ceiling.
|
|
23
|
+
- **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)**.
|
|
24
24
|
|
|
25
25
|
---
|
|
26
26
|
|
|
@@ -34,71 +34,71 @@ All 47 deep-dive playbooks are located in [`skills/rust-shapeshift/resources`](s
|
|
|
34
34
|
|
|
35
35
|
### Memory, Stack & Allocator Optimization
|
|
36
36
|
|
|
37
|
-
- [
|
|
38
|
-
- [
|
|
39
|
-
- [
|
|
40
|
-
- [
|
|
41
|
-
- [
|
|
42
|
-
- [
|
|
43
|
-
- [
|
|
44
|
-
- [
|
|
45
|
-
- [
|
|
46
|
-
- [
|
|
37
|
+
- [`Memory Allocator Tuning`](skills/rust-shapeshift/resources/memory_allocator_tuning.md): Glibc arena containment (`MALLOC_ARENA_MAX=2`) and `libc::malloc_trim(0)`.
|
|
38
|
+
- [`Jemalloc Tuning & Profiling`](skills/rust-shapeshift/resources/jemalloc_profiling_and_allocator_switch.md): `tikv-jemallocator` vs `mimalloc`, dirty/muzzy decay tuning, live heap dumps via `jemalloc-ctl`, and DHAT.
|
|
39
|
+
- [`Arena Allocation & Bump Memory`](skills/rust-shapeshift/resources/arena_allocation_and_bump_memory.md): Bumpalo arena allocation, O(1) bulk dealloc, request-scoped ASTs/trees, and heap fragmentation elimination.
|
|
40
|
+
- [`Ownership, Borrowing & Decision Matrix`](skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md): Borrow checker permissions (R/W/O), eliminating `.clone()`, Stack vs Heap matrix, and Future size.
|
|
41
|
+
- [`Typestates, Domain Proofs & Buffer Recycling`](skills/rust-shapeshift/resources/typestate_domain_proofs_and_buffer_recycling.md): Eliminating runtime defensive branching via affine typestates, parse-don't-validate domain proofs, and buffer capacity recycling (`clone_from`, slab pools).
|
|
42
|
+
- [`Compiler Niche Optimizations & Size Assertions`](skills/rust-shapeshift/resources/compiler_niche_optimizations_and_size_assertions.md): NonZero niche packing (`Option<NonZeroU64>` 8B vs 16B), compile-time size asserts, `.clone_from()` reuse, and `Box<[T]>`.
|
|
43
|
+
- [`Stack Inlining & Allocation Reduction`](skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md): Inlining short strings via `compact_str`, `Box<str>`, and `SmallVec` (0 heap allocations).
|
|
44
|
+
- [`Cache-Line Alignment & Struct Layout`](skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md): Struct padding elimination, field ordering, and `#[repr(align(64))]` anti-false sharing.
|
|
45
|
+
- [`Zero-Allocation Error Architecture`](skills/rust-shapeshift/resources/zero_allocation_error_architecture.md): Boxing rare error payloads to minimize `Result<T, E>` stack size, eliminating `format!` on error paths.
|
|
46
|
+
- [`Hot-Path String & Zero-Cost Helpers`](skills/rust-shapeshift/resources/hot_path_string_and_zero_cost_helpers.md): Zero-regex single-pass whitespace collapsing and native integer time formatting.
|
|
47
47
|
|
|
48
48
|
### Tokio, Concurrency & Reactor Safety
|
|
49
49
|
|
|
50
|
-
- [
|
|
51
|
-
- [
|
|
52
|
-
- [
|
|
53
|
-
- [
|
|
54
|
-
- [
|
|
55
|
-
- [
|
|
50
|
+
- [`Predictable Tail Latency & WCET Contracts`](skills/rust-shapeshift/resources/hidden_drop_offload_and_wcet_contracts.md): Eliminating p99.99 spikes via offloaded destructors, bounded CAS loops, cooperative poll bounds, and lock-free ring-buffer logging.
|
|
51
|
+
- [`Hardware Resource Budgets & Loom Concurrency Verification`](skills/rust-shapeshift/resources/concurrency_model_checking_and_resource_budgets.md): Worst-case RSS ceiling calculations, deterministic schedule permutation testing with Loom, and Tokio runtime starvation diagnostics.
|
|
52
|
+
- [`Tokio Thread Starvation & CPU Offload`](skills/rust-shapeshift/resources/tokio_thread_starvation_and_cpu_offload.md): Cooperative scheduling safety, offloading CPU >100µs via `spawn_blocking`/`rayon`.
|
|
53
|
+
- [`Concurrency Primitives & Lock Contention`](skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md): `parking_lot` 1-byte locks, wait-free `ArcSwap`, and lock-free `Atomic*` memory orderings.
|
|
54
|
+
- [`Async Cancellation Safety & Task Drainage`](skills/rust-shapeshift/resources/async_cancellation_safety_and_task_drainage.md): Safety matrix for `tokio::select!`, drop hazard prevention, and `JoinSet` graceful drainage.
|
|
55
|
+
- [`Adaptive Concurrency & Load Shedding`](skills/rust-shapeshift/resources/adaptive_concurrency_and_load_shedding.md): Dynamic in-flight limits, Little's Law gradient feedback, and fast-fail `503 Service Unavailable` shedding.
|
|
56
56
|
|
|
57
57
|
### Network, Real-Time & Microservices
|
|
58
58
|
|
|
59
|
-
- [
|
|
60
|
-
- [
|
|
61
|
-
- [
|
|
62
|
-
- [
|
|
63
|
-
- [
|
|
59
|
+
- [`Real-Time WebSocket & Connection Scaling`](skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md): Scaling 50k–500k connections, tuned 4KB buffers, single-task event loops, and zero-copy broadcasting.
|
|
60
|
+
- [`gRPC, Tonic & HTTP/2 Memory Tuning`](skills/rust-shapeshift/resources/grpc_tonic_and_http2_memory_tuning.md): HTTP/2 stream/conn window bounding (64KB/512KB), streaming RPC backpressure, and zero-copy `Bytes`.
|
|
61
|
+
- [`Reqwest Client & Socket Pooling`](skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.md): Singleton pool in `Arc<AppState>`, tiered timeouts, and selective `/random` non-caching.
|
|
62
|
+
- [`Bounded Streaming & Payload Guards`](skills/rust-shapeshift/resources/bounded_streaming_and_payload_guards.md): Bounded HTTP streaming, `take(MAX_BYTES)` limits, memory bomb defense, and zero-copy proxying.
|
|
63
|
+
- [`Zero-Copy IPC & Shared Memory`](skills/rust-shapeshift/resources/zero_copy_ipc_and_shared_memory.md): Unix Domain Sockets (UDS) vs TCP loopback, and `memmap2` shared memory ring buffers.
|
|
64
64
|
|
|
65
65
|
### Data Ingestion, Storage & Queues
|
|
66
66
|
|
|
67
|
-
- [
|
|
68
|
-
- [
|
|
69
|
-
- [
|
|
70
|
-
- [
|
|
71
|
-
- [
|
|
72
|
-
- [
|
|
67
|
+
- [`SQLx & Database Pool Memory`](skills/rust-shapeshift/resources/sqlx_and_database_pool_memory.md): Streaming query rows (`.fetch`), connection pool sizing formula, and statement cache containment.
|
|
68
|
+
- [`Message Queue & Stream Backpressure`](skills/rust-shapeshift/resources/message_queue_and_stream_backpressure.md): Broker prefetch bounding (Kafka, RabbitMQ, SQS), decoupled Tokio MPSC pipeline, and offset safety.
|
|
69
|
+
- [`Streaming File I/O & Compression`](skills/rust-shapeshift/resources/streaming_file_io_and_compression.md): Chunked disk I/O, streaming Zstd/Gzip compression without in-memory `Vec<u8>` buffers, and Axum export streams.
|
|
70
|
+
- [`Redis Connection & Pooling Pitfalls`](skills/rust-shapeshift/resources/redis_connection_and_caching_pitfalls.md): Solving lazy connection traps, `tokio-comp` requirements, startup async `PING`, and credential masking.
|
|
71
|
+
- [`Bounded Caching & Pooling`](skills/rust-shapeshift/resources/bounded_caching_and_pooling.md): Hybrid `moka` in-memory cache (bounded 1,000) with `deadpool-redis` fallback.
|
|
72
|
+
- [`Rate Limiting & State Management`](skills/rust-shapeshift/resources/rate_limiting_and_state.md): Hard capacity ceiling `DashMap`, 30s background cleaner tasks, and proxy IP extraction.
|
|
73
73
|
|
|
74
74
|
### Serialization, SIMD, BCE & Compiler Tuning
|
|
75
75
|
|
|
76
|
-
- [
|
|
77
|
-
- [
|
|
78
|
-
- [
|
|
79
|
-
- [
|
|
80
|
-
- [
|
|
81
|
-
- [
|
|
82
|
-
- [
|
|
76
|
+
- [`Bounds Check Elimination & Zero-Cost Memory`](skills/rust-shapeshift/resources/bounds_check_elimination_and_zero_cost_memory.md): BCE loop proofing, eliminating zeroing tax via `MaybeUninit`/`BytesMut`, `std::mem::take`, and `ArrayVec`.
|
|
77
|
+
- [`SIMD Vectorization & Acceleration`](skills/rust-shapeshift/resources/simd_vectorization_and_hardware_acceleration.md): AVX2/NEON vector parsing, `memchr` delimiter scanning, `simdutf8` validation, and zero-copy unmasking.
|
|
78
|
+
- [`Profile-Guided Optimization & Fast Hashing`](skills/rust-shapeshift/resources/profile_guided_optimization_and_fast_hashing.md): PGO multi-stage pipeline, LLVM BOLT, `AHashMap`/`FxHashMap` selection matrix.
|
|
79
|
+
- [`Zero-Copy Serde & Streaming`](skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md): `#[serde(borrow)]` with `&'a str` (0 alloc), `BytesMut` streaming, and SIMD parsing.
|
|
80
|
+
- [`GraphQL Memory & Query Containment`](skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md): Hard query depth & complexity limits, `DataLoader` N+1 elimination, and Axum 0.8 integration.
|
|
81
|
+
- [`DOM & Scraper Pruning`](skills/rust-shapeshift/resources/dom_and_scraper_pruning.md): Pre-parse HTML slicing (`&html[..end_pos]`) slashing 80% of DOM AST node allocations.
|
|
82
|
+
- [`Headless-Free Anti-Bot Solvers`](skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md): Eliminating 500MB+ Chromium instances with reverse-engineered algorithmic solvers & single-flight `RwLock`.
|
|
83
83
|
|
|
84
84
|
### Minimalist Daemons, Container Ops & Wasm
|
|
85
85
|
|
|
86
|
-
- [
|
|
87
|
-
- [
|
|
88
|
-
- [
|
|
89
|
-
- [
|
|
90
|
-
- [
|
|
91
|
-
- [
|
|
92
|
-
- [
|
|
93
|
-
- [
|
|
94
|
-
- [
|
|
86
|
+
- [`Zero-Runtime Minimalist Daemons`](skills/rust-shapeshift/resources/zero_runtime_and_minimalist_daemons.md): The Koburi Pattern: sub-5MB idle RSS, zero-async blocking architecture, musl static linking, std-only streams, and ephemeral sockets.
|
|
87
|
+
- [`Axum 0.8 & Tower Middleware`](skills/rust-shapeshift/resources/axum_and_tower_architecture.md): Production Axum 0.8 template, Tower middleware ordering, and dual graceful shutdown signals.
|
|
88
|
+
- [`Zero-Panic & Router Architecture`](skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md): `#![deny(clippy::unwrap_used)]`, safe fallback idioms, and router recursion limits.
|
|
89
|
+
- [`Zero-Overhead Distributed Tracing`](skills/rust-shapeshift/resources/zero_overhead_distributed_tracing.md): Compile-time static level filtering, non-blocking `tracing-appender`, and zero-allocation span fields.
|
|
90
|
+
- [`Telemetry & Metric Cardinality`](skills/rust-shapeshift/resources/telemetry_and_metrics.md): Hand-rolled zero-dependency Prometheus exporter, PID-filtered sysinfo, and route cardinality protection.
|
|
91
|
+
- [`Docker Slimming & Build Hygiene`](skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md): Sub-80MB Debian multi-stage builds, `.dockerignore` discipline, and C-ABI version locking.
|
|
92
|
+
- [`Kubernetes Runtime & Resource Containment`](skills/rust-shapeshift/resources/kubernetes_runtime_and_resource_containment.md): CFS CPU quota threads, OOMKilled exit 137 defense, preStop 502 drain race, and safe probe architectures.
|
|
93
|
+
- [`WebAssembly Sandboxing & Memory Limits`](skills/rust-shapeshift/resources/wasm_runtime_and_memory_sandboxing.md): Wasmtime `ResourceLimiter` linear memory caps, epoch interruption, and zero-copy guest memory slices.
|
|
94
|
+
- [`Framework & Stack Selection Matrix`](skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md): Manual Zero-Deps vs Axum vs Actix Web vs Salvo vs Poem vs Rocket vs Loco decision trees.
|
|
95
95
|
|
|
96
96
|
### Silicon, Kernel Bedrock & Hardware Topography
|
|
97
97
|
|
|
98
|
-
- [
|
|
99
|
-
- [
|
|
100
|
-
- [
|
|
101
|
-
- [
|
|
98
|
+
- [`Zero-Syscall I/O & io_uring`](skills/rust-shapeshift/resources/io_uring_and_zero_syscall_networking.md): Zero-syscall I/O via io_uring, kernel SQPOLL threads, pre-registered fixed buffers, and memory-mapped completion rings.
|
|
99
|
+
- [`Thread-Per-Core & Shared-Nothing Architecture`](skills/rust-shapeshift/resources/thread_per_core_and_shared_nothing.md): Pinned CPU cores (`core_affinity`), `SO_REUSEPORT` listeners, and eliminating cross-core work-stealing cache thrashing.
|
|
100
|
+
- [`NUMA Architecture & HugePages`](skills/rust-shapeshift/resources/numa_architecture_and_hugepages.md): NUMA node memory binding (`mbind`), 2MB/1GB HugePages (`madvise` THP) eliminating TLB misses, and `mlockall` page pinning.
|
|
101
|
+
- [`Instruction Cache (I-Cache) & Cold Path Outlining`](skills/rust-shapeshift/resources/instruction_cache_and_cold_path_outlining.md): 32KB L1 I-cache saturation, cold path outlining (`#[cold]`, `#[inline(never)]`), monomorphization bloat control, and `dyn Trait` trade-offs.
|
|
102
102
|
|
|
103
103
|
---
|
|
104
104
|
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"bin": {
|
|
4
4
|
"rust-shapeshift": "bin/rust-shapeshift.js"
|
|
5
5
|
},
|
|
6
|
-
"description": "
|
|
6
|
+
"description": "Rust agent skill for extreme memory and runtime efficiency",
|
|
7
7
|
"files": [
|
|
8
8
|
"bin/rust-shapeshift.js",
|
|
9
9
|
"skills",
|
|
@@ -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.4",
|
|
30
|
+
"@sinkaroid/rust-shapeshift-darwin-x64": "1.0.4",
|
|
31
|
+
"@sinkaroid/rust-shapeshift-linux-arm64": "1.0.4",
|
|
32
|
+
"@sinkaroid/rust-shapeshift-linux-x64": "1.0.4",
|
|
33
|
+
"@sinkaroid/rust-shapeshift-win32-x64": "1.0.4"
|
|
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.4"
|
|
47
47
|
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: rust-shapeshift
|
|
3
3
|
author: "@sinkaroid"
|
|
4
|
-
version: "1.0.
|
|
4
|
+
version: "1.0.4"
|
|
5
5
|
repository: "https://github.com/sinkaroid"
|
|
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
|
|
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:
|
|
8
8
|
author: "@sinkaroid"
|
|
9
9
|
maintainer: "@sinkaroid"
|
|
@@ -19,7 +19,7 @@ You are an expert Rust systems architect and concurrency engineer specialized in
|
|
|
19
19
|
|
|
20
20
|
- Rewriting or migrating backend services from other runtimes (Go, Python, Java, Node.js/TypeScript) to high-performance, memory-efficient Rust.
|
|
21
21
|
- Architecting greenfield native Rust services (`cargo new --bin`) designed from day one with sub-50MB RSS baselines, bounded memory, and zero-panic guarantees.
|
|
22
|
-
- Building high-throughput async web services, REST/GraphQL gateways, microservices, or systems tooling
|
|
22
|
+
- Building high-throughput async web services, REST/GraphQL gateways, microservices, or systems tooling across modern frameworks (Axum 0.8 as reference standard, Actix Web, Salvo, or zero-runtime daemons).
|
|
23
23
|
- Engineering high-density real-time WebSocket gateways, chat brokers, or event-streaming hubs scaling to 50k–500k concurrent connections with sub-4KB per-socket RSS.
|
|
24
24
|
- Designing high-concurrency web scrapers, crawler pipelines, or reverse-proxy engines that suffer from DOM tree memory bloat.
|
|
25
25
|
- Debugging memory bloat, Linux glibc heap fragmentation, Tokio thread-pool starvation, async deadlocks, or `tokio::select!` cancellation safety.
|
|
@@ -36,14 +36,49 @@ You are an expert Rust systems architect and concurrency engineer specialized in
|
|
|
36
36
|
|
|
37
37
|
---
|
|
38
38
|
|
|
39
|
+
## Architectural Contract: Framework-Agnostic Core & Axum-First Reference Standard
|
|
40
|
+
|
|
41
|
+
> [!IMPORTANT]
|
|
42
|
+
> **Core Architectural Rule**:
|
|
43
|
+
> All core logic, memory optimization, and concurrency rules are **strictly framework-agnostic**. HTTP implementation examples use **Axum 0.8 as the canonical reference architecture**, but the Agent **MUST adapt** these primitives to Actix-Web, Salvo, Loco, or minimal `std::net` whenever the project or user selects an alternative stack based on the [`framework_and_stack_selection_matrix.md`](skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md).
|
|
44
|
+
|
|
45
|
+
To eliminate architectural confusion and ensure consistent agent behavior across different project stacks, this skill enforces a strict separation between **Universal Memory/Systems Foundations** and **HTTP Transport Layering**:
|
|
46
|
+
|
|
47
|
+
### 1. The Systems & Memory Core is 100% Framework-Agnostic
|
|
48
|
+
Over 70% of this skill focuses on hardware-, kernel-, allocator-, and compiler-level optimizations that apply to **every Rust codebase**, regardless of the web framework chosen:
|
|
49
|
+
- **Linux Allocator Hygiene**: `MALLOC_ARENA_MAX=2`, `libc::malloc_trim(0)`, musl vs glibc trade-offs, and Docker C-ABI pairing.
|
|
50
|
+
- **Data Layout & Zero Churn**: Stack inlining (`compact_str`), capacity trimming (`Box<str>`, `Box<[T]>`), enum boxing, struct alignment (`#[repr(align(64))]`), and arena allocation (`bumpalo`).
|
|
51
|
+
- **Low-Level Throughput**: Bounds Check Elimination (BCE), SIMD vector parsing, Profile-Guided Optimization (PGO), `io_uring`, and NUMA HugePages.
|
|
52
|
+
- **Concurrency & Reactor Safety**: Loom deterministic model checking, async cancellation safety, lock-free atomics, and bounded channel backpressure.
|
|
53
|
+
- **The Koburi Pattern (Archetype B)**: Zero-async, zero-dependency `std::net` / `UnixStream` minimal daemons under 1MB idle RSS.
|
|
54
|
+
|
|
55
|
+
### 2. Axum 0.8 as the Canonical Reference Implementation
|
|
56
|
+
Axum 0.8 is adopted as the primary reference standard across HTTP-specific playbooks because of its official Tokio ecosystem alignment, Tower middleware composition, and strict type-level extractor safety.
|
|
57
|
+
|
|
58
|
+
### 3. Mandatory AI Agent Contract for Alternative Frameworks
|
|
59
|
+
When project constraints or user requirements dictate an alternative framework based on [`framework_and_stack_selection_matrix.md`](skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md) (such as **Actix Web** for maximum raw throughput, **Salvo** for ultra-clean routing ergonomics, **Loco** for full-stack productivity, or **std::net** for minimalist daemons):
|
|
60
|
+
> **MANDATORY DIRECTIVE**: The AI agent **MUST NOT** force Axum onto the workspace. Instead, the agent **MUST adapt** the core zero-cost memory and safety principles into the target framework using the **Framework Adaptation Rosetta Stone** below:
|
|
61
|
+
|
|
62
|
+
| Architectural Primitive | Axum 0.8 (Canonical Reference) | Actix Web | Salvo | Minimal std::net (Koburi) |
|
|
63
|
+
|---|---|---|---|---|
|
|
64
|
+
| **Zero-Allocation Error Envelope** | `impl IntoResponse for AppError` | `impl ResponseError for AppError` | `#[salvo::async_trait] impl Writer for AppError` | Custom byte serializer over `TcpStream::write_all` |
|
|
65
|
+
| **Normalized Metric Routing (Cardinality Safe)** | `req.extensions().get::<MatchedPath>()` | `req.match_pattern()` | `req.params()` | Static route enum matching |
|
|
66
|
+
| **Shared Application State** | `axum::extract::State(Arc<AppState>)` | `actix_web::web::Data<AppState>` | `depot.obtain::<Arc<AppState>>()` | Passed by borrowed reference `&AppState` |
|
|
67
|
+
| **Zero-Downtime Rate Limiting Middleware** | `axum::middleware::from_fn_with_state` | `actix_web::dev::Transform` / `wrap_fn` | `#[handler] fn rate_limit(...)` | Inline bucket check before connection accept |
|
|
68
|
+
| **Low-Memory WebSocket Upgrades** | `axum::extract::ws::{WebSocket, Message}` (4KB tuned buffer) | `actix-ws` with session framing | `salvo::websocket::WebSocket` | Custom lightweight framing over raw TCP |
|
|
69
|
+
| **Chunked Streaming Response** | `axum::body::Body::from_stream` | `HttpResponse::Ok().streaming(stream)` | `Response::streaming(stream)` | Sequential `std::io::copy` to socket buffer |
|
|
70
|
+
| **Graceful Shutdown Signal** | `axum::serve().with_graceful_shutdown()` | `actix_web::HttpServer::stop()` | `salvo::Server::stop()` | Polling atomic flag / SIGINT listener |
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
39
74
|
## Instructions
|
|
40
75
|
|
|
41
76
|
1. **Classify Operating Mode**:
|
|
42
77
|
- **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).
|
|
43
78
|
- **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.
|
|
44
|
-
2. **Classify Project Archetype
|
|
45
|
-
- **Archetype A (High-Throughput / High-Density Gateway)**: High QPS, WebSocket clusters (50k–500k), gRPC, Tokio multi-thread runtime
|
|
46
|
-
- **Archetype B (Sub-Megabyte Minimalist Daemon / Sidecar - The Koburi Pattern)**: Low QPS, polling intervals, container monitors, CLI sidecars. **DO NOT use Tokio 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)**.
|
|
79
|
+
2. **Classify Project Archetype & Framework Decision**:
|
|
80
|
+
- **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
|
+
- **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)**.
|
|
47
82
|
3. **Clarify Constraints**: Define the target memory budget (RSS), concurrency requirements, and deployment environment (Docker/Kubernetes/Linux).
|
|
48
83
|
4. **Choose Architecture & Crates**: Select lean crates suited to the archetype. Never pull in Tokio or connection pools for simple polling daemons.
|
|
49
84
|
5. **Configure Release Profiles**: Ensure `Cargo.toml` specifies `lto = "fat"`, `panic = "abort"`, `codegen-units = 1`, and `strip = "symbols"`.
|