rusty-ssr 0.1.0

High-performance SSR engine for Rust with V8 isolate pool and multi-tier caching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# Rusty SSR

**The fastest SSR engine for Rust. Period.**

Render 95,000+ pages per second with sub-millisecond latency. Drop-in replacement for Node.js SSR that's 50x faster.

[![Crates.io](https://img.shields.io/crates/v/rusty-ssr.svg)](https://crates.io/crates/rusty-ssr)
[![Documentation](https://docs.rs/rusty-ssr/badge.svg)](https://docs.rs/rusty-ssr)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

## Benchmarks (Apple M4, 10 cores)

```
┌─────────────────────────────────────────────────────────────┐
│                    STRESS TEST (30 seconds)                 │
├─────────────────────────────────────────────────────────────┤
│  Requests/sec:      95,363 RPS                              │
│  Total requests:    2,869,878                               │
│  Data transferred:  171 GB                                  │
├─────────────────────────────────────────────────────────────┤
│  Latency p50:       0.46ms                                  │
│  Latency p99:       4.60ms                                  │
│  Max latency:       45.7ms                                  │
└─────────────────────────────────────────────────────────────┘
```

### vs Competition

| Engine | RPS | p99 Latency | Memory |
|--------|-----|-------------|--------|
| **Rusty SSR** | **95,363** | **4.6ms** | ~200MB |
| Next.js (Node) | 500-2,000 | 50-200ms | ~500MB+ |
| Nuxt (Node) | 500-1,500 | 40-150ms | ~500MB+ |

**50x faster throughput. 40x lower latency. 60% less memory.**

## Why Rusty SSR?

### The Problem with Node.js SSR

```
Node.js Cluster Mode          Rusty SSR
┌─────────────────────┐       ┌─────────────────────┐
│ Process 1           │       │ 1 Process           │
│  └─ V8 + 512MB heap │       │  ├─ V8 isolate 1    │
├─────────────────────┤       │  ├─ V8 isolate 2    │
│ Process 2           │       │  ├─ V8 isolate 3    │
│  └─ V8 + 512MB heap │       │  ├─ ...             │
├─────────────────────┤       │  └─ V8 isolate 10   │
│ ... × 10            │       │                     │
├─────────────────────┤       │  Shared L1/L2 Cache │
│ ~5GB RAM total      │       │  ~200MB RAM total   │
│ No shared cache     │       │  Zero-copy Arc<str> │
└─────────────────────┘       └─────────────────────┘
```

- **Node.js**: 10 processes × 512MB = 5GB RAM, no shared cache
- **Rusty SSR**: 1 process, 10 V8 isolates, shared cache, 200MB RAM

### The Solution

Rusty SSR runs V8 isolates in a thread pool managed by Rust. Each CPU core gets its own V8 instance, but they share a common cache. Zero-copy `Arc<str>` means no memory duplication.

## Quick Start

```toml
[dependencies]
rusty-ssr = "0.1"
tokio = { version = "1", features = ["full"] }
axum = "0.7"
```

### 1. Create SSR Bundle

```javascript
// ssr-bundle.js
globalThis.renderPage = async function(url, data) {
    // Your framework's SSR here (React, Preact, Vue, Solid...)
    const html = renderToString(<App url={url} {...data} />);

    return `<!DOCTYPE html>
<html>
<head><title>My App</title></head>
<body><div id="app">${html}</div></body>
</html>`;
};
```

### 2. Use with Axum

```rust
use axum::{extract::State, response::Html, routing::get, Router};
use rusty_ssr::prelude::*;
use std::sync::Arc;

#[tokio::main]
async fn main() {
    // Initialize SSR engine (auto-detects CPU cores)
    let engine = Arc::new(
        SsrEngine::builder()
            .bundle_path("ssr-bundle.js")
            .cache_size(500)        // ~500 cached pages (entries, not MB)
            .cache_ttl_secs(300)    // 5 min TTL
            .build_engine()
            .expect("Failed to create SSR engine")
    );

    let app = Router::new()
        .route("/", get(ssr_handler))
        .route("/*path", get(ssr_handler))
        .with_state(engine);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    println!("SSR server running on http://localhost:3000");
    axum::serve(listener, app).await.unwrap();
}

async fn ssr_handler(
    State(engine): State<Arc<SsrEngine>>,
    axum::extract::Path(path): axum::extract::Path<String>,
) -> Html<String> {
    match engine.render(&format!("/{}", path)).await {
        Ok(html) => Html(html.to_string()),
        Err(e) => Html(format!("<h1>Error</h1><pre>{}</pre>", e)),
    }
}
```

That's it. Your SSR is now 50x faster.

## Features

### Built-in Browser Polyfills

No more "window is not defined" errors. Rusty SSR automatically injects polyfills for:

- `window`, `document`, `navigator`, `location`
- `localStorage`, `sessionStorage`
- `requestAnimationFrame`, `cancelAnimationFrame`
- `MutationObserver`, `ResizeObserver`, `IntersectionObserver`
- `matchMedia`, `Image`, `performance`

Just load your bundle — it works.

### Multi-tier Cache

```
Request → L1/L2 Hot Cache (1-3ns) → Cold Cache (100ns) → V8 Render
               ↑                          ↑                  ↓
               └──────────────────────────┴──── cache result ┘
```

- **Hot cache**: Thread-local, L1/L2 CPU cache speed
- **Cold cache**: DashMap with LRU eviction
- **Automatic**: No configuration needed

### Framework Agnostic

Works with any JavaScript framework that supports SSR:

- **React** / **Preact**
- **Vue 3** / **Nuxt**
- **Solid**
- **Svelte** / **SvelteKit**
- **Vanilla JS**

See `examples/bundles/` for complete examples.

## API Reference

### Basic Render

```rust
// Simple render
let html = engine.render("/products").await?;

// With JSON data
use serde_json::json;
let html = engine.render_json("/products", json!({
    "products": [...],
    "user": { "id": 1 }
})).await?;

// With string data
let html = engine.render_with_data("/products", r#"{"page": 1}"#).await?;

// Skip cache (always render fresh)
let html = engine.render_uncached("/admin", "{}").await?;
```

### Configuration

```rust
    let engine = SsrEngine::builder()
        .bundle_path("ssr-bundle.js")     // Path to JS bundle
        .pool_size(num_cpus::get())       // V8 workers (default: CPU count)
        .queue_capacity(512)               // Task queue size
        .pin_threads(true)                 // Pin workers to CPU cores
        .cache_size(500)                   // Number of cached entries
        .cache_ttl_secs(300)               // Cache TTL (0 = forever)
        .render_function("renderPage")     // JS function name
        .build_engine()?;
```

### Cache Metrics

```rust
let metrics = engine.cache_metrics();
println!("Hit rate: {:.1}%", metrics.hit_rate);
println!("Hot hits: {}", metrics.hot_hits);
println!("Cold hits: {}", metrics.cold_hits);
println!("Misses: {}", metrics.misses);
```

## Building SSR Bundles

### Option 1: Vite (Recommended)

```typescript
// vite.config.ts
export default defineConfig({
  build: {
    ssr: true,
    rollupOptions: {
      input: 'src/entry-server.tsx',
      output: {
        format: 'iife',
        name: 'SSRBundle',
        inlineDynamicImports: true
      },
    },
  },
});
```

```bash
# Build SSR bundle
vite build --ssr

# Wrap for Rusty SSR
node scripts/build-bundle.js dist/server/entry.js ssr-bundle.js --iife SSRBundle
```

### Option 2: Direct

Write your bundle with `globalThis.renderPage` directly:

```javascript
import { render } from 'preact-render-to-string';
import App from './App';

globalThis.renderPage = async function(url, data) {
    const html = render(<App url={url} {...data} />);
    return `<!DOCTYPE html><html><body>${html}</body></html>`;
};
```

## Feature Flags

| Feature | Default | Description |
|---------|---------|-------------|
| `v8-pool` || V8 thread pool |
| `cache` || Multi-tier caching |
| `axum-integration` || Axum middleware |
| `brotli-compression` || Brotli middleware |
| `full` || All features |

```toml
# Minimal (just V8 pool)
rusty-ssr = { version = "0.1", default-features = false, features = ["v8-pool"] }

# Full (everything)
rusty-ssr = { version = "0.1", features = ["full"] }
```

## Testing & Benchmarks

### Running Tests

```bash
# Run all tests
cargo test

# Run integration tests only
cargo test --test integration_tests

# Run with verbose output
cargo test -- --nocapture
```

Integration tests cover:
- V8 pool configuration
- DashMap concurrent cache operations
- LRU cache eviction behavior
- Async patterns (tokio channels, timeouts)
- Thread safety (Arc, Mutex, mpsc)
- URL parsing and JSON serialization

### Running Benchmarks

```bash
# Run all benchmarks
cargo bench

# Run SSR benchmarks only
cargo bench --bench ssr_benchmark

# Run cache benchmarks only
cargo bench --bench cache_benchmark
```

**SSR Benchmarks** (`ssr_benchmark`):
- Pool config creation overhead
- String operations (small/medium/large HTML)
- JSON serialization performance
- Channel throughput (request queue simulation)

**Cache Benchmarks** (`cache_benchmark`):
- DashMap concurrent read/write (1, 2, 4, 8 threads)
- DashMap sharding (sequential vs random keys)
- L1/L2 cache hit performance
- LRU eviction overhead (128, 512, 2048 entries)
- Arc<str> vs String cloning

Results are saved to `target/criterion/` with HTML reports.

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                        SsrEngine                            │
│                                                             │
│  ┌─────────────────┐           ┌──────────────────────────┐ │
│  │   SSR Cache     │           │       V8 Pool            │ │
│  │                 │  miss     │                          │ │
│  │  ┌───────────┐  │ ───────►  │  ┌────┐ ┌────┐ ┌────┐   │ │
│  │  │ Hot (L1)  │  │           │  │ V8 │ │ V8 │ │ V8 │   │ │
│  │  └───────────┘  │           │  └────┘ └────┘ └────┘   │ │
│  │  ┌───────────┐  │  result   │         ...              │ │
│  │  │ Cold (RAM)│  │ ◄───────  │  ┌────┐ ┌────┐ ┌────┐   │ │
│  │  └───────────┘  │           │  │ V8 │ │ V8 │ │ V8 │   │ │
│  │  LRU eviction   │           │  └────┘ └────┘ └────┘   │ │
│  └─────────────────┘           └──────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```

## Deployment

### Docker

```dockerfile
FROM rust:1.75-slim-bookworm AS builder
WORKDIR /app
COPY . .
RUN cargo build --release

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/your-app /app/server
COPY ssr-bundle.js /app/
WORKDIR /app
CMD ["./server"]
```

### Railway / Fly.io

Just push your code — Rusty SSR works with any platform that supports Rust.

## Troubleshooting

### "window is not defined"

This shouldn't happen with v0.1+ — browser polyfills are automatic. If it does:

1. Check your bundle doesn't run browser code at module load time
2. Use `typeof window !== 'undefined'` guards if needed

### "renderPage is not a function"

Your bundle must expose `globalThis.renderPage`:

```javascript
// Correct
globalThis.renderPage = async (url, data) => { ... };

// Wrong
export function renderPage() { ... }  // ESM export won't work
```

### Memory usage grows

Set a cache TTL to prevent unbounded growth:

```rust
.cache_ttl_secs(300)  // Expire after 5 minutes
```

## License

MIT — use it however you want.

## Contributing

Issues and PRs welcome! See [CONTRIBUTING.md](CONTRIBUTING.md).