mothership 0.0.13

Process supervisor with HTTP exposure - wrap, monitor, and expose your fleet
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# WarpDrive Routing Architecture

## Overview

WarpDrive supports **multi-upstream routing** with path-based, host-based, and load-balanced routing to multiple backend services, matching modern nginx reverse-proxy setups.

## Design Philosophy

- **Simple by default**: Single upstream via env vars (backward compatible)
- **Powerful when needed**: TOML config unlocks advanced routing
- **Zero-copy performance**: Route selection in O(1) or O(log n)
- **Process-aware**: Supervise multiple upstream processes

---

## Configuration Modes

### Mode 1: Simple (Current - Env Vars Only)

**Use case**: Single Rails/Node app

```bash
export WARPDRIVE_TARGET_HOST=127.0.0.1
export WARPDRIVE_TARGET_PORT=3000
warpdrive
```

**Behavior**: All requests → `127.0.0.1:3000`

---

### Mode 2: Advanced (TOML Config)

**Use case**: Rails + ActionCable + Sidekiq Web

```toml
# warpdrive.toml

[server]
http_port = 8080
https_port = 443

# Define upstream services
[upstreams.rails]
host = "127.0.0.1"
port = 3000

[upstreams.cable]
host = "127.0.0.1"
port = 3001

[upstreams.sidekiq]
host = "127.0.0.1"
port = 7080

# Define routing rules (evaluated in order)
[[routes]]
path_prefix = "/cable"
upstream = "cable"

[[routes]]
path_prefix = "/sidekiq"
upstream = "sidekiq"
strip_prefix = true  # /sidekiq/jobs → /jobs

[[routes]]
path_prefix = "/"
upstream = "rails"
```

**Behavior**:
- `GET /cable``127.0.0.1:3001`
- `GET /sidekiq/jobs``127.0.0.1:7080/jobs`
- `GET /``127.0.0.1:3000`

---

## Upstream Types

### 1. TCP Socket (host:port)

```toml
[upstreams.api]
host = "127.0.0.1"
port = 3000
```

### 2. Unix Domain Socket (faster than TCP)

```toml
[upstreams.rails]
socket = "/tmp/puma.sock"
```

**Performance**: ~30% faster than TCP loopback

### 3. Load Balanced Pool

```toml
[upstreams.rails]
strategy = "round_robin"  # or "least_conn", "random", "ip_hash"

[[upstreams.rails.instances]]
socket = "/tmp/puma.0.sock"

[[upstreams.rails.instances]]
socket = "/tmp/puma.1.sock"

[[upstreams.rails.instances]]
socket = "/tmp/puma.2.sock"
```

**Strategies**:
- `round_robin`: Distribute evenly
- `least_conn`: Send to least busy (requires connection tracking)
- `random`: Random selection (useful for stateless)
- `ip_hash`: Sticky sessions based on client IP

### 4. With Health Checks

```toml
[upstreams.api]
host = "127.0.0.1"
port = 3000

[upstreams.api.health]
path = "/health"
interval_secs = 10
timeout_secs = 2
unhealthy_threshold = 3  # Mark down after 3 failures
healthy_threshold = 2    # Mark up after 2 successes
```

---

## Routing Rules

Routes are evaluated **in order** (first match wins).

### 1. Path Prefix Matching

```toml
[[routes]]
path_prefix = "/api/v1"
upstream = "api_v1"

[[routes]]
path_prefix = "/api/v2"
upstream = "api_v2"
```

### 2. Exact Path Matching

```toml
[[routes]]
path_exact = "/health"
upstream = "health_check"
```

### 3. Regex Matching

```toml
[[routes]]
path_regex = "^/users/[0-9]+/posts"
upstream = "posts_service"
```

### 4. Host-Based Routing (Multi-Tenant)

```toml
[[routes]]
host = "api.example.com"
upstream = "api"

[[routes]]
host = "www.example.com"
path_prefix = "/cable"
upstream = "cable"

[[routes]]
host = "www.example.com"
upstream = "rails"
```

### 5. Method-Based Routing

```toml
[[routes]]
path_prefix = "/admin"
methods = ["GET", "POST"]
upstream = "admin_readonly"

[[routes]]
path_prefix = "/admin"
methods = ["PUT", "DELETE"]
upstream = "admin_writable"
```

### 6. Header-Based Routing

```toml
[[routes]]
header = { name = "X-API-Version", value = "v2" }
upstream = "api_v2"

[[routes]]
header = { name = "X-API-Version", value = "v1" }
upstream = "api_v1"
```

---

## Advanced Features

### Path Rewriting

```toml
[[routes]]
path_prefix = "/old-api"
upstream = "api"
rewrite = "/new-api"  # /old-api/users → /new-api/users
```

### Strip Prefix

```toml
[[routes]]
path_prefix = "/sidekiq"
upstream = "sidekiq"
strip_prefix = true  # /sidekiq/jobs → /jobs
```

### Add Headers

```toml
[[routes]]
path_prefix = "/api"
upstream = "api"
add_headers = [
  { name = "X-Backend", value = "api-service" },
  { name = "X-Forwarded-Prefix", value = "/api" }
]
```

### Timeouts

```toml
[[routes]]
path_prefix = "/slow-reports"
upstream = "reports"
read_timeout_secs = 120
connect_timeout_secs = 5
```

---

## Process Supervision Integration

Supervise multiple upstream processes:

```toml
[upstreams.rails]
socket = "/tmp/puma.sock"
process.command = "bundle"
process.args = ["exec", "puma", "-b", "unix:///tmp/puma.sock"]
process.env = { RAILS_ENV = "production" }

[upstreams.cable]
socket = "/tmp/anycable.sock"
process.command = "anycable-go"
process.args = ["--port", "3001"]

[upstreams.sidekiq_web]
host = "127.0.0.1"
port = 7080
process.command = "bundle"
process.args = ["exec", "sidekiq-web", "-p", "7080"]
```

WarpDrive will:
1. Start all configured processes
2. Monitor health
3. Restart on crash
4. Graceful shutdown in reverse dependency order

---

## Complete Real-World Example

```toml
# warpdrive.toml - Production Rails + ActionCable + Sidekiq

[server]
http_port = 80
https_port = 443
worker_threads = 4

[tls]
enabled = true
domains = ["example.com", "www.example.com"]
acme_directory = "/var/lib/warpdrive/acme"

# Main Rails app (3 Puma workers via sockets)
[upstreams.rails]
strategy = "round_robin"
process.command = "bundle"
process.args = ["exec", "puma", "-w", "3", "-b", "unix:///tmp/puma.sock"]
process.env = { RAILS_ENV = "production", PORT = "3000" }

[[upstreams.rails.instances]]
socket = "/tmp/puma.0.sock"

[[upstreams.rails.instances]]
socket = "/tmp/puma.1.sock"

[[upstreams.rails.instances]]
socket = "/tmp/puma.2.sock"

# ActionCable server (separate process for WebSocket connections)
[upstreams.cable]
host = "127.0.0.1"
port = 3001
process.command = "bundle"
process.args = ["exec", "puma", "-p", "3001", "cable/config.ru"]
process.env = { RAILS_ENV = "production" }

[upstreams.cable.health]
path = "/health"
interval_secs = 5

# Sidekiq Web UI (admin access only)
[upstreams.sidekiq]
host = "127.0.0.1"
port = 7080
process.command = "bundle"
process.args = ["exec", "sidekiq-web", "-p", "7080"]

# Routing rules
[[routes]]
host = "example.com"
path_prefix = "/cable"
upstream = "cable"
description = "WebSocket connections to ActionCable"

[[routes]]
host = "example.com"
path_prefix = "/sidekiq"
upstream = "sidekiq"
strip_prefix = true
require_auth = true  # Check X-Admin-Token header
description = "Sidekiq monitoring (admins only)"

[[routes]]
host = "example.com"
path_prefix = "/"
upstream = "rails"
description = "Main Rails application"

[[routes]]
host = "www.example.com"
upstream = "rails"
add_headers = [{ name = "X-Forwarded-Host", value = "www.example.com" }]

[cache]
size_bytes = 134217728  # 128 MB
redis_url = "redis://localhost:6379/0"

[postgres]
url = "postgres://localhost/warpdrive_production"
channel = "warpdrive_cache_invalidation"

[middleware]
forward_headers = true
x_sendfile_enabled = true
gzip_compression_enabled = true
log_requests = true
```

---

## Implementation Strategy

### Phase 1: Core Router (src/router.rs)

```rust
pub struct Router {
    upstreams: HashMap<String, Upstream>,
    routes: Vec<Route>,
}

impl Router {
    pub fn select_upstream(&self, session: &Session) -> Result<&Upstream> {
        for route in &self.routes {
            if route.matches(session) {
                return self.upstreams.get(&route.upstream)
                    .ok_or_else(|| Error::new(ErrorType::HTTPStatus(502)));
            }
        }
        Err(Error::new(ErrorType::HTTPStatus(502)))
    }
}
```

### Phase 2: TOML Config Loading

```rust
#[derive(Deserialize)]
struct RouterConfig {
    upstreams: HashMap<String, UpstreamConfig>,
    routes: Vec<RouteConfig>,
}

impl Config {
    pub fn from_toml(path: &Path) -> Result<Self> {
        let contents = std::fs::read_to_string(path)?;
        let config: TomlConfig = toml::from_str(&contents)?;
        // Merge with env vars (env wins)
        Ok(config.merge_with_env())
    }
}
```

### Phase 3: Load Balancer

```rust
pub trait LoadBalancer: Send + Sync {
    fn select(&self, instances: &[Instance]) -> Result<&Instance>;
}

pub struct RoundRobin {
    counter: AtomicUsize,
}

pub struct LeastConnections {
    active_conns: DashMap<usize, usize>,
}
```

### Phase 4: Process Supervisor Integration

```rust
pub struct ProcessManager {
    supervisors: HashMap<String, ProcessSupervisor>,
}

impl ProcessManager {
    pub async fn start_all(&mut self) -> Result<()> {
        for (name, supervisor) in &self.supervisors {
            supervisor.start().await?;
        }
        Ok(())
    }
}
```

---

## Performance Considerations

### Route Matching Complexity

- Path prefix: O(1) with HashMap
- Regex: O(n) patterns × O(m) regex complexity
- Host exact: O(1) with HashMap
- Header: O(h) headers to check

**Optimization**: Compile routing table into decision tree for O(log n) lookups.

### Memory Overhead

- Single upstream: ~0 bytes
- 100 routes: ~10 KB (route table)
- 1000 routes: ~100 KB

**Design choice**: Routes stored in Vec (sequential scan), not tree, for simplicity and cache locality.

### Unix Socket Performance

Measured on Linux 5.x:
- TCP loopback: ~15µs latency
- Unix socket: ~10µs latency
- **Benefit**: 33% faster connection time

---

## Migration Path

### Step 1: Add Router (Backward Compatible)

Detect TOML config presence:
```rust
let router = if let Some(config_path) = std::env::var("WARPDRIVE_CONFIG").ok() {
    Router::from_toml(config_path)?  // Advanced mode
} else {
    Router::single_upstream(config)  // Simple mode (current)
};
```

### Step 2: Optional TOML

Users can opt-in:
```bash
WARPDRIVE_CONFIG=warpdrive.toml warpdrive
```

### Step 3: Full TOML Support

After testing, recommend TOML as primary config method.

---

## Comparison with Alternatives

| Feature | WarpDrive | nginx |
|---------|-----------|-------|
| **Single upstream** |||
| **Multi upstream** |||
| **Unix sockets** |||
| **Load balancing** | ✅ (always on) ||
| **Path routing** |||
| **Host routing** |||
| **Process supervision** |||
| **Health checks** |||
| **Config format** | TOML | nginx.conf |
| **Written in** | Rust | C |

---

## Testing Strategy

### Unit Tests

```rust
#[test]
fn test_path_prefix_routing() {
    let router = Router::from_toml("test.toml").unwrap();
    let session = mock_session("/api/users");
    let upstream = router.select_upstream(&session).unwrap();
    assert_eq!(upstream.name, "api");
}
```

### Integration Tests

```bash
# Start test services
docker-compose up -d redis postgres rails cable

# Test routing
curl http://localhost:8080/ | grep "Rails"
curl http://localhost:8080/cable | grep "ActionCable"
```

### Benchmarks

```rust
#[bench]
fn bench_route_selection(b: &mut Bencher) {
    let router = Router::with_100_routes();
    b.iter(|| {
        router.select_upstream(&random_session())
    });
}
// Target: < 1µs per route selection
```

---

## Next Steps

1. ✅ Document routing architecture (this file)
2. ⬜ Implement `Router` struct with path prefix matching
3. ⬜ Add TOML config loading with `serde` + `toml`
4. ⬜ Support Unix domain sockets in `HttpPeer`
5. ⬜ Implement round-robin load balancer
6. ⬜ Add health check system
7. ⬜ Integrate with process supervisor for multi-process
8. ⬜ Performance benchmark vs nginx

---

## Questions & Decisions

**Q: Should routes be case-sensitive?**
**A**: Yes (HTTP paths are case-sensitive per RFC 3986).

**Q: Should we support regex by default or require opt-in?**
**A**: Opt-in via `path_regex` field (avoid regex overhead for simple routing).

**Q: How to handle conflicting routes?**
**A**: First match wins (document ordering importance).

**Q: Should we cache route selection?**
**A**: No for v1 (sequential scan is fast enough for <1000 routes). Add later if profiling shows bottleneck.

**Q: Unix socket vs TCP - which is default?**
**A**: TCP for backward compat, Unix socket recommended in docs for performance.