eggress-runtime 1.0.3

Service supervisor and composition layer for eggress
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
use std::io::Write;
use std::sync::atomic::Ordering;
use std::time::Duration;

use tempfile::NamedTempFile;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;

fn write_config(content: &str) -> NamedTempFile {
    let mut f = NamedTempFile::new().unwrap();
    f.write_all(content.as_bytes()).unwrap();
    f.flush().unwrap();
    f
}

/// Start a TCP server that accepts connections and holds them open indefinitely.
async fn start_slow_backend() -> (std::net::SocketAddr, tokio::task::JoinHandle<()>) {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let jh = tokio::spawn(async move {
        loop {
            let (stream, _) = match listener.accept().await {
                Ok(s) => s,
                Err(_) => break,
            };
            // Hold the connection open by sleeping forever
            tokio::spawn(async move {
                let (mut rd, mut wr) = stream.into_split();
                let _ = tokio::io::copy(&mut rd, &mut wr).await;
            });
        }
    });
    (addr, jh)
}

/// Perform a minimal SOCKS5 handshake (no auth) targeting an IPv4 address.
async fn socks5_handshake(
    stream: &mut tokio::net::TcpStream,
    target: std::net::SocketAddr,
) -> std::io::Result<()> {
    // Method negotiation: version=5, 1 method, NO AUTH
    stream.write_all(&[0x05, 0x01, 0x00]).await?;
    // Read response: version=5, selected method
    let mut resp = [0u8; 2];
    stream.read_exact(&mut resp).await?;
    if resp[0] != 0x05 || resp[1] != 0x00 {
        return Err(std::io::Error::other("SOCKS5 method negotiation failed"));
    }
    // CONNECT request: version=5, cmd=CONNECT, rsv=0, atyp=IPv4, addr, port
    let octets = match target.ip() {
        std::net::IpAddr::V4(v4) => v4.octets(),
        _ => {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "only IPv4 supported",
            ))
        }
    };
    let port = target.port().to_be_bytes();
    stream
        .write_all(&[
            0x05, 0x01, 0x00, 0x01, octets[0], octets[1], octets[2], octets[3],
        ])
        .await?;
    stream.write_all(&port).await?;
    // Read reply header
    let mut reply = [0u8; 10];
    stream.read_exact(&mut reply).await?;
    if reply[1] != 0x00 {
        return Err(std::io::Error::other(format!(
            "SOCKS5 connect failed: {:#04x}",
            reply[1]
        )));
    }
    Ok(())
}

#[tokio::test]
async fn readiness_transitions_to_false_on_shutdown() {
    let config = r#"
version = 1

[[listeners]]
name = "http-in"
bind = "127.0.0.1:0"
protocols = ["http"]
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    // Wait for readiness
    for _ in 0..50 {
        if state.readiness.load(Ordering::Relaxed) {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert!(state.readiness.load(Ordering::Relaxed), "should be ready");

    // Trigger shutdown
    token.cancel();
    jh.await.ok();

    // Readiness should be false after shutdown
    assert!(
        !state.readiness.load(Ordering::Relaxed),
        "readiness should be false after shutdown"
    );
}

#[tokio::test]
async fn shutdown_drains_active_connections() {
    let config = r#"
version = 1

[[listeners]]
name = "http-in"
bind = "127.0.0.1:0"
protocols = ["http"]
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    // Wait for readiness
    for _ in 0..50 {
        if state.readiness.load(Ordering::Relaxed) {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert!(state.readiness.load(Ordering::Relaxed));

    // Trigger shutdown (should drain within shutdown_grace of 30s)
    let start = std::time::Instant::now();
    token.cancel();
    jh.await.ok();
    let elapsed = start.elapsed();

    // Shutdown should complete well within the 30s grace period
    assert!(
        elapsed < Duration::from_secs(10),
        "shutdown took too long: {:?}",
        elapsed
    );
}

#[tokio::test]
async fn shutdown_generation_remains_consistent() {
    let config = r#"
version = 1

[[listeners]]
name = "http-in"
bind = "127.0.0.1:0"
protocols = ["http"]
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let gen_before = state.generation();
    assert_eq!(gen_before, 0);

    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    // Wait for readiness
    for _ in 0..50 {
        if state.readiness.load(Ordering::Relaxed) {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }

    // Trigger shutdown
    token.cancel();
    jh.await.ok();

    // Generation should not change during shutdown
    let gen_after = state.generation();
    assert_eq!(
        gen_before, gen_after,
        "generation should not change during shutdown"
    );
}

#[tokio::test]
async fn shutdown_active_connections_returns_to_zero() {
    let config = r#"
version = 1

[[listeners]]
name = "http-in"
bind = "127.0.0.1:0"
protocols = ["http"]
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    assert_eq!(state.active_connections.load(Ordering::Relaxed), 0);

    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    // Wait for readiness
    for _ in 0..50 {
        if state.readiness.load(Ordering::Relaxed) {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }

    // Trigger shutdown
    token.cancel();
    jh.await.ok();

    assert_eq!(
        state.active_connections.load(Ordering::Relaxed),
        0,
        "active connections should be zero after shutdown"
    );
}

#[tokio::test]
async fn shutdown_stops_accepting_new_connections() {
    let config = r#"
version = 1

[[listeners]]
name = "http-in"
bind = "127.0.0.1:0"
protocols = ["http"]
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    // Wait for readiness
    for _ in 0..50 {
        if state.readiness.load(Ordering::Relaxed) {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert!(state.readiness.load(Ordering::Relaxed));

    // Trigger shutdown
    token.cancel();
    jh.await.ok();

    // Active connections should be zero
    assert_eq!(
        state.active_connections.load(Ordering::Relaxed),
        0,
        "active connections should be zero after shutdown"
    );
}

#[tokio::test]
async fn shutdown_completes_within_grace_period() {
    let config = r#"
version = 1

[[listeners]]
name = "http-in"
bind = "127.0.0.1:0"
protocols = ["http"]
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    for _ in 0..50 {
        if state.readiness.load(Ordering::Relaxed) {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert!(state.readiness.load(Ordering::Relaxed));

    // Trigger shutdown — with zero active connections it should finish instantly
    let start = std::time::Instant::now();
    token.cancel();
    jh.await.ok();
    let elapsed = start.elapsed();

    // With no connections to drain, shutdown should complete in under 2s
    assert!(
        elapsed < Duration::from_secs(2),
        "empty shutdown took too long: {:?}",
        elapsed
    );
    assert!(!state.readiness.load(Ordering::Relaxed));
}

#[tokio::test]
async fn shutdown_force_cancels_after_deadline() {
    let (backend_addr, _backend_jh) = start_slow_backend().await;

    let config = r#"
version = 1

[process]
shutdown_grace = "2s"

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[rules]]
id = "route-all"
any = true
direct = true
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    // Wait for readiness
    for _ in 0..100 {
        if state.readiness.load(Ordering::Relaxed) {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert!(state.readiness.load(Ordering::Relaxed), "should be ready");

    // Get the listener address
    let listener_addr = {
        let addrs = state.listener_addrs.lock().unwrap();
        assert!(!addrs.is_empty(), "should have at least one listener");
        addrs[0].unwrap()
    };

    // Connect through SOCKS5 to the slow backend
    let mut stream = tokio::net::TcpStream::connect(listener_addr)
        .await
        .expect("failed to connect to listener");
    socks5_handshake(&mut stream, backend_addr)
        .await
        .expect("SOCS5 handshake failed");

    // Verify active connection is tracked
    tokio::time::sleep(Duration::from_millis(100)).await;
    let active = state.active_connections.load(Ordering::Relaxed);
    assert!(
        active >= 1,
        "should have at least 1 active connection, got {active}"
    );

    // Trigger shutdown — the 2s grace period should forcibly cancel the connection
    let start = std::time::Instant::now();
    token.cancel();
    jh.await.ok();
    let elapsed = start.elapsed();

    // Shutdown should complete within grace period + margin, not hang forever
    assert!(
        elapsed < Duration::from_secs(6),
        "shutdown took too long with active connection: {:?}",
        elapsed
    );

    // Active connections should be zero
    assert_eq!(
        state.active_connections.load(Ordering::Relaxed),
        0,
        "active connections should be zero after forced shutdown"
    );

    // The client stream should be dead
    let mut buf = [0u8; 1];
    let result = tokio::time::timeout(Duration::from_millis(500), stream.read(&mut buf)).await;
    assert!(
        result.is_err() || matches!(result, Ok(Ok(0))),
        "client stream should be dead after forced shutdown"
    );
}

#[tokio::test]
async fn admin_responds_during_shutdown_drain() {
    let (backend_addr, _backend_jh) = start_slow_backend().await;

    let config = r#"
version = 1

[process]
shutdown_grace = "5s"

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[rules]]
id = "route-all"
any = true
direct = true

[admin]
bind = "127.0.0.1:0"
enabled = true
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    for _ in 0..100 {
        if state.readiness.load(Ordering::Relaxed) {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert!(state.readiness.load(Ordering::Relaxed));

    let listener_addr = state.listener_addrs.lock().unwrap()[0].unwrap();
    let admin_addr = state
        .admin_local_addr
        .lock()
        .unwrap()
        .expect("admin should have bound")
        .to_string();

    let mut client = tokio::net::TcpStream::connect(listener_addr)
        .await
        .expect("connect listener");
    socks5_handshake(&mut client, backend_addr)
        .await
        .expect("socks5 handshake");

    tokio::time::sleep(Duration::from_millis(100)).await;
    let active = state.active_connections.load(Ordering::Relaxed);
    assert!(
        active >= 1,
        "should have one active connection, got {active}"
    );

    token.cancel();

    tokio::time::sleep(Duration::from_millis(100)).await;

    let mut stream = tokio::net::TcpStream::connect(&admin_addr)
        .await
        .expect("admin should still be listening during drain");
    let req = b"GET /-/ready HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
    tokio::io::AsyncWriteExt::write_all(&mut stream, req)
        .await
        .unwrap();
    tokio::io::AsyncWriteExt::flush(&mut stream).await.unwrap();

    let mut buf = Vec::new();
    let _ = tokio::time::timeout(
        Duration::from_secs(2),
        tokio::io::AsyncReadExt::read_to_end(&mut stream, &mut buf),
    )
    .await;
    let response = String::from_utf8_lossy(&buf);
    assert!(
        response.starts_with("HTTP/1.1 503"),
        "admin /-/ready should respond 503 during drain, got: {response}"
    );

    drop(client);
    jh.await.ok();
}

#[tokio::test]
async fn admin_metrics_visible_during_drain() {
    let (backend_addr, _backend_jh) = start_slow_backend().await;

    let config = r#"
version = 1

[process]
shutdown_grace = "5s"

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[rules]]
id = "route-all"
any = true
direct = true

[admin]
bind = "127.0.0.1:0"
enabled = true
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    for _ in 0..100 {
        if state.readiness.load(Ordering::Relaxed) {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert!(state.readiness.load(Ordering::Relaxed));

    let listener_addr = state.listener_addrs.lock().unwrap()[0].unwrap();
    let admin_addr = state
        .admin_local_addr
        .lock()
        .unwrap()
        .expect("admin should have bound")
        .to_string();

    let mut client = tokio::net::TcpStream::connect(listener_addr)
        .await
        .expect("connect listener");
    socks5_handshake(&mut client, backend_addr)
        .await
        .expect("socks5 handshake");

    tokio::time::sleep(Duration::from_millis(100)).await;
    let active = state.active_connections.load(Ordering::Relaxed);
    assert!(
        active >= 1,
        "should have one active connection, got {active}"
    );

    token.cancel();

    tokio::time::sleep(Duration::from_millis(100)).await;

    let mut stream = tokio::net::TcpStream::connect(&admin_addr)
        .await
        .expect("admin should still be listening during drain");
    let req = b"GET /metrics HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
    tokio::io::AsyncWriteExt::write_all(&mut stream, req)
        .await
        .unwrap();
    tokio::io::AsyncWriteExt::flush(&mut stream).await.unwrap();

    let mut buf = Vec::new();
    let _ = tokio::time::timeout(
        Duration::from_secs(2),
        tokio::io::AsyncReadExt::read_to_end(&mut stream, &mut buf),
    )
    .await;
    let response = String::from_utf8_lossy(&buf);
    assert!(
        response.contains("eggress_connections_active"),
        "/metrics should be available during drain, got: {response}"
    );

    drop(client);
    jh.await.ok();
}

#[tokio::test]
async fn new_connections_refused_after_shutdown_begins() {
    let config = r#"
version = 1

[[listeners]]
name = "http-in"
bind = "127.0.0.1:0"
protocols = ["http"]
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    // Wait for readiness
    for _ in 0..50 {
        if state.readiness.load(Ordering::Relaxed) {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert!(state.readiness.load(Ordering::Relaxed));

    let listener_addr = state.listener_addrs.lock().unwrap()[0].unwrap();

    // Trigger shutdown
    token.cancel();

    // Wait briefly for shutdown to propagate
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Attempting to connect after shutdown should fail or be refused
    let result = tokio::time::timeout(Duration::from_secs(2), async {
        tokio::net::TcpStream::connect(listener_addr).await
    })
    .await;

    match result {
        Ok(Ok(_)) => {
            // If the connection succeeds, readiness must be false (server is shutting down)
            assert!(
                !state.readiness.load(Ordering::Relaxed),
                "if connect succeeds during shutdown, readiness must be false"
            );
        }
        Ok(Err(_)) => {
            // Connection refused — expected during shutdown
        }
        Err(_) => {
            // Timeout — listener is no longer accepting
        }
    }

    jh.await.ok();
}

#[tokio::test]
async fn malformed_handshake_does_not_corrupt_listener() {
    let config = r#"
version = 1

[[listeners]]
name = "socks-in"
bind = "127.0.0.1:0"
protocols = ["socks5"]

[[rules]]
id = "route-all"
any = true
direct = true
"#;
    let f = write_config(config);
    let path = f.path().to_str().unwrap();
    let mut sup = eggress_runtime::ServiceSupervisor::start(path).unwrap();

    let state = sup.state().clone();
    let token = sup.shutdown_token();
    let jh = tokio::task::spawn_blocking(move || sup.run());

    // Wait for readiness
    for _ in 0..50 {
        if state.readiness.load(Ordering::Relaxed) {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert!(state.readiness.load(Ordering::Relaxed));

    let listener_addr = state.listener_addrs.lock().unwrap()[0].unwrap();

    // Send garbage bytes to trigger a handshake error
    {
        let mut bad_stream = tokio::net::TcpStream::connect(listener_addr)
            .await
            .expect("connect for malformed handshake");
        let _ = bad_stream.write_all(b"NOT_A_SOCKS5_PROTOCOL").await;
        // The server should close this connection after detecting the error
        drop(bad_stream);
    }

    // Wait briefly for the bad connection to be cleaned up
    tokio::time::sleep(Duration::from_millis(200)).await;

    // Now send a valid SOCKS5 handshake — listener must still accept it
    {
        let mut good_stream = tokio::net::TcpStream::connect(listener_addr)
            .await
            .expect("connect for valid handshake after malformed");
        good_stream.write_all(&[0x05, 0x01, 0x00]).await.unwrap();
        let mut resp = [0u8; 2];
        let result =
            tokio::time::timeout(Duration::from_secs(2), good_stream.read_exact(&mut resp)).await;
        assert!(result.is_ok(), "valid handshake must get a response");
        assert_eq!(resp, [0x05, 0x00], "server must accept valid SOCKS5");
    }

    // Verify the service is still operational
    assert!(state.readiness.load(Ordering::Relaxed));

    token.cancel();
    jh.await.ok();
}