litebucket 0.1.3

Durable SQLite on S3, Cloudflare R2, and Laravel Cloud Object Storage — CLI & proxy for zero-sidecar cloud-native SQLite with PITR, encryption, and per-tenant isolation.
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
//! Language-agnostic Tier 1 ephemeral SQLite supervisor & Tokio write-holding reverse proxy.
//!
//! Wraps ANY web server (Rails/Puma, Laravel Rust, Laravel PHP/FrankenPHP, Django, Node):
//! - Owns the R2/S3 `FencedLease` (`If-None-Match: *` / `If-Match: <etag>`) and Litestream 0.5.18.
//! - Passes `/up` immediately in `Standby` (hot-tailing via `litestream restore -f`).
//! - Proxies `GET`/`HEAD` immediately to the wrapped upstream app.
//! - Parks `POST`/`PUT`/`PATCH`/`DELETE` in Tokio during rolling deploy cutovers, signals
//!   `yield_requested_by` to the old primary, promotes atomically, runs migrations, restarts
//!   the wrapped app in read-write mode, and replays the parked HTTP requests with zero 5xx errors!

use std::net::SocketAddr;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::time::{Duration, Instant};

use axum::body::{Body, to_bytes};
use axum::extract::{Request, State};
use axum::http::{HeaderName, HeaderValue, Method, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::any;
use axum::{Json, Router};
use litebucket_cas::{FencedLease, LeaseSnapshot, LeaseState, S3Client, S3Config, S3Error};
use serde::Serialize;
use litebucket_handoff::litestream::{LitestreamPaths, terminate_gracefully};
use tokio::net::TcpStream;
use tokio::process::{Child, Command};
use tokio::sync::{Mutex, Notify, watch};
use tracing::{error, info, warn};

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "role", rename_all = "snake_case")]
pub enum ProxyRole {
    Booting,
    Standby { primary_holder: String, epoch: u64 },
    Promoting,
    Primary { epoch: u64 },
    Draining,
    Stopped,
}

#[derive(Debug, Clone)]
pub struct ProxyConfig {
    pub node_id: String,
    pub listen_addr: SocketAddr,
    pub upstream_addr: SocketAddr,
    pub work_dir: PathBuf,
    pub litestream_bin: PathBuf,
    pub s3: S3Config,
    pub replica_prefix: String,
    pub lease_key: String,
    pub lease_ttl_ms: i64,
    pub sync_interval: String,
    pub app_cmd: String,
    pub migrate_cmd: Option<String>,
    pub worker_cmd: Option<String>,
    pub write_hold_timeout_ms: u64,
}

pub struct ProxySupervisor {
    cfg: ProxyConfig,
    ls: LitestreamPaths,
    lease: FencedLease,
    http: reqwest::Client,
    role_tx: watch::Sender<ProxyRole>,
    role_rx: watch::Receiver<ProxyRole>,
    lifecycle_lock: Mutex<()>,
    active_lease: Mutex<Option<LeaseSnapshot>>,
    replicate_child: Mutex<Option<Child>>,
    follow_child: Mutex<Option<Child>>,
    app_child: Mutex<Option<Child>>,
    worker_child: Mutex<Option<Child>>,
    in_flight_writes: AtomicUsize,
    writes_drained: Notify,
    held_writes_total: AtomicU64,
    max_hold_ms: AtomicU64,
}

impl ProxySupervisor {
    pub async fn start(cfg: ProxyConfig) -> Result<Arc<Self>, Box<dyn std::error::Error + Send + Sync>> {
        let s3 = S3Client::new(cfg.s3.clone())?;
        s3.ensure_bucket().await?;
        let ls = LitestreamPaths::new(
            cfg.litestream_bin.clone(),
            cfg.work_dir.clone(),
            cfg.replica_prefix.clone(),
            cfg.sync_interval.clone(),
        );
        ls.write_config(&cfg.s3)?;
        let lease = FencedLease::new(s3, cfg.lease_key.clone(), cfg.lease_ttl_ms);
        let (role_tx, role_rx) = watch::channel(ProxyRole::Booting);
        let http = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()?;

        let sup = Arc::new(Self {
            cfg,
            ls,
            lease,
            http,
            role_tx,
            role_rx,
            lifecycle_lock: Mutex::new(()),
            active_lease: Mutex::new(None),
            replicate_child: Mutex::new(None),
            follow_child: Mutex::new(None),
            app_child: Mutex::new(None),
            worker_child: Mutex::new(None),
            in_flight_writes: AtomicUsize::new(0),
            writes_drained: Notify::new(),
            held_writes_total: AtomicU64::new(0),
            max_hold_ms: AtomicU64::new(0),
        });

        sup.boot().await?;
        sup.spawn_lease_loop();
        Ok(sup)
    }

    pub fn role(&self) -> ProxyRole {
        self.role_rx.borrow().clone()
    }

    pub fn stats(&self) -> serde_json::Value {
        serde_json::json!({
            "node_id": self.cfg.node_id,
            "role": self.role(),
            "upstream": self.cfg.upstream_addr.to_string(),
            "in_flight_writes": self.in_flight_writes.load(Ordering::Relaxed),
            "held_writes_total": self.held_writes_total.load(Ordering::Relaxed),
            "max_hold_ms": self.max_hold_ms.load(Ordering::Relaxed),
        })
    }

    async fn spawn_shell_child(&self, cmd_str: &str, role_env: &str) -> Result<Child, std::io::Error> {
        let db_str = self.ls.db_path.display().to_string();
        let mode = if role_env == "standby" { "ro" } else { "rwc" };
        let db_url = format!("sqlite://{db_str}?mode={mode}");
        let child = Command::new("sh")
            .arg("-c")
            .arg(cmd_str)
            .env("PORT", self.cfg.upstream_addr.port().to_string())
            .env("APP_HOST", self.cfg.upstream_addr.ip().to_string())
            .env("DB_PATH", &db_str)
            .env("DATABASE_URL", &db_url)
            .env("SQLITE_ROLE", role_env)
            .env("NODE_ID", &self.cfg.node_id)
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .kill_on_drop(true)
            .spawn()?;
        Ok(child)
    }

    async fn stop_child_slot(&self, slot: &Mutex<Option<Child>>, grace: Duration) {
        if let Some(mut child) = slot.lock().await.take() {
            terminate_gracefully(&mut child, grace).await;
        }
    }

    async fn wait_upstream_tcp(&self, timeout: Duration) -> Result<(), String> {
        let deadline = Instant::now() + timeout;
        while Instant::now() < deadline {
            if TcpStream::connect(self.cfg.upstream_addr).await.is_ok() {
                return Ok(());
            }
            tokio::time::sleep(Duration::from_millis(30)).await;
        }
        Err(format!("upstream {} did not open TCP port", self.cfg.upstream_addr))
    }

    async fn boot(self: &Arc<Self>) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let now = FencedLease::now_ms();
        match self.lease.read().await? {
            None => match self.lease.try_acquire_fresh(&self.cfg.node_id).await {
                Ok(snap) => self.activate_primary(snap, false).await?,
                Err(S3Error::PreconditionFailed(_)) => self.enter_standby().await?,
                Err(e) => return Err(Box::new(e)),
            },
            Some(snap) if snap.record.can_be_claimed(now) => {
                match self.lease.try_promote(&snap, &self.cfg.node_id).await {
                    Ok(claimed) => self.activate_primary(claimed, true).await?,
                    Err(S3Error::PreconditionFailed(_)) => self.enter_standby().await?,
                    Err(e) => return Err(Box::new(e)),
                }
            }
            Some(_) => self.enter_standby().await?,
        }
        Ok(())
    }

    async fn enter_standby(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let _guard = self.lifecycle_lock.lock().await;
        let restored = self.ls.restore(true).await?;
        if restored {
            let child = self.ls.spawn_follow("100ms")?;
            *self.follow_child.lock().await = Some(child);
            // Launch wrapped upstream app in read-only standby mode so GETs serve immediately!
            let app = self.spawn_shell_child(&self.cfg.app_cmd, "standby").await?;
            *self.app_child.lock().await = Some(app);
            let _ = self.wait_upstream_tcp(Duration::from_secs(10)).await;
        }
        let (holder, epoch) = match self.lease.read().await? {
            Some(s) => (s.record.holder_id, s.record.epoch),
            None => ("unknown".into(), 0),
        };
        let _ = self.role_tx.send(ProxyRole::Standby {
            primary_holder: holder,
            epoch,
        });
        info!(node = %self.cfg.node_id, "proxy STANDBY ready (serving GETs + holding writes)");
        Ok(())
    }

    async fn activate_primary(
        &self,
        lease_snap: LeaseSnapshot,
        force_restore: bool,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let _guard = self.lifecycle_lock.lock().await;
        if matches!(self.role(), ProxyRole::Draining | ProxyRole::Stopped) {
            let _ = self.lease.release(&lease_snap, None).await;
            return Ok(());
        }
        *self.active_lease.lock().await = Some(lease_snap.clone());

        // Stop standby upstream + follow process before restoring final snapshot
        self.stop_child_slot(&self.app_child, Duration::from_secs(3)).await;
        self.stop_child_slot(&self.follow_child, Duration::from_secs(2)).await;

        let _restored = self.ls.restore(force_restore).await?;

        // Run migrations (or create fresh DB file before starting litestream replicate!)
        if let Some(ref mig) = self.cfg.migrate_cmd {
            let db_str = self.ls.db_path.display().to_string();
            let status = Command::new("sh")
                .arg("-c")
                .arg(mig)
                .env("DB_PATH", &db_str)
                .env("DATABASE_URL", format!("sqlite://{db_str}"))
                .env("SQLITE_ROLE", "primary")
                .status()
                .await?;
            if !status.success() {
                return Err(format!("migrate command failed with {status}").into());
            }
        }

        // Start wrapped upstream app in Primary RW mode
        let app = self.spawn_shell_child(&self.cfg.app_cmd, "primary").await?;
        *self.app_child.lock().await = Some(app);
        self.wait_upstream_tcp(Duration::from_secs(15)).await?;

        // Ensure DB file exists (even if app creates it lazily on boot/first request)
        if !self.ls.db_path.exists() {
            let _ = std::fs::File::create(&self.ls.db_path);
        }

        // Start Litestream replicate + force immediate initial sync so monitor is live at t=0
        let rep = self.ls.spawn_replicate().await?;
        *self.replicate_child.lock().await = Some(rep);
        if let Err(e) = self.ls.sync_wait(10).await {
            warn!(error = %e, "initial litestream sync -wait warning");
        }

        // Start optional background worker ONLY while Primary
        if let Some(ref wcmd) = self.cfg.worker_cmd {
            let w = self.spawn_shell_child(wcmd, "primary").await?;
            *self.worker_child.lock().await = Some(w);
        }

        let _ = self.role_tx.send(ProxyRole::Primary {
            epoch: lease_snap.record.epoch,
        });
        info!(
            node = %self.cfg.node_id,
            epoch = lease_snap.record.epoch,
            "proxy PRIMARY ACTIVE"
        );
        Ok(())
    }

    fn spawn_lease_loop(self: &Arc<Self>) {
        let sup = Arc::clone(self);
        tokio::spawn(async move {
            let renew_ms = (sup.cfg.lease_ttl_ms as u64 / 4).max(150);
            loop {
                match sup.role() {
                    ProxyRole::Primary { .. } => {
                        tokio::time::sleep(Duration::from_millis(renew_ms)).await;
                        if !matches!(sup.role(), ProxyRole::Primary { .. }) {
                            continue;
                        }
                        let snap_opt = sup.active_lease.lock().await.clone();
                        let Some(snap) = snap_opt else { continue };
                        match sup.lease.renew(&snap).await {
                            Ok(next) => {
                                let y = next.record.yield_requested_by.clone();
                                *sup.active_lease.lock().await = Some(next);
                                if y.is_some() {
                                    sup.graceful_drain().await;
                                }
                            }
                            Err(S3Error::PreconditionFailed(_)) => match sup.lease.read().await {
                                Ok(Some(latest))
                                    if latest.record.holder_id == sup.cfg.node_id
                                        && latest.record.epoch == snap.record.epoch =>
                                {
                                    *sup.active_lease.lock().await = Some(latest.clone());
                                    if latest.record.yield_requested_by.is_some() {
                                        sup.graceful_drain().await;
                                    }
                                }
                                _ => {
                                    error!(node = %sup.cfg.node_id, "FENCED OUT! Killing wrapped app + litestream immediately");
                                    sup.emergency_fence_stop().await;
                                }
                            },
                            Err(e) => warn!(error = %e, "lease renew error"),
                        }
                    }
                    ProxyRole::Standby { .. } => {
                        tokio::time::sleep(Duration::from_millis(100)).await;
                        if !matches!(sup.role(), ProxyRole::Standby { .. }) {
                            continue;
                        }
                        if let Ok(Some(snap)) = sup.lease.read().await
                            && snap.record.can_be_claimed(FencedLease::now_ms()) {
                                let _ = sup.role_tx.send(ProxyRole::Promoting);
                                match sup.lease.try_promote(&snap, &sup.cfg.node_id).await {
                                    Ok(claimed) => {
                                        if let Err(e) = sup.activate_primary(claimed, true).await {
                                            error!(error = %e, "promotion failed");
                                            let _ = sup.role_tx.send(ProxyRole::Stopped);
                                            break;
                                        }
                                    }
                                    Err(S3Error::PreconditionFailed(_)) => {
                                        let _ = sup.enter_standby().await;
                                    }
                                    Err(_) => {
                                        let _ = sup.enter_standby().await;
                                    }
                                }
                            }
                    }
                    ProxyRole::Stopped => break,
                    _ => tokio::time::sleep(Duration::from_millis(50)).await,
                }
            }
        });
    }

    pub async fn signal_yield(&self) {
        if let Ok(Some(snap)) = self.lease.read().await
            && snap.record.state == LeaseState::Active && snap.record.holder_id != self.cfg.node_id {
                let _ = self.lease.request_yield(&snap, &self.cfg.node_id).await;
            }
    }

    pub async fn wait_for_primary(&self) -> Result<u64, &'static str> {
        let timeout = Duration::from_millis(self.cfg.write_hold_timeout_ms);
        let started = Instant::now();
        let mut rx = self.role_rx.clone();
        loop {
            match rx.borrow().clone() {
                ProxyRole::Primary { .. } => {
                    let ms = started.elapsed().as_millis() as u64;
                    if ms > 0 {
                        self.held_writes_total.fetch_add(1, Ordering::Relaxed);
                        self.max_hold_ms.fetch_max(ms, Ordering::Relaxed);
                    }
                    return Ok(ms);
                }
                ProxyRole::Draining | ProxyRole::Stopped => return Err("draining"),
                _ => {}
            }
            let rem = timeout.saturating_sub(started.elapsed());
            if rem.is_zero() {
                return Err("handoff_timeout");
            }
            match tokio::time::timeout(rem, rx.changed()).await {
                Ok(Ok(())) => continue,
                _ => return Err("handoff_timeout"),
            }
        }
    }

    pub async fn graceful_drain(&self) {
        let _guard = self.lifecycle_lock.lock().await;
        if matches!(self.role(), ProxyRole::Draining | ProxyRole::Stopped) {
            return;
        }
        let was_primary = matches!(self.role(), ProxyRole::Primary { .. })
            || self.active_lease.lock().await.is_some();
        let _ = self.role_tx.send(ProxyRole::Draining);

        if !was_primary {
            self.stop_child_slot(&self.app_child, Duration::from_secs(2)).await;
            self.stop_child_slot(&self.follow_child, Duration::from_secs(2)).await;
            let _ = self.role_tx.send(ProxyRole::Stopped);
            return;
        }

        // 1. Drain in-flight proxied writes
        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
        while self.in_flight_writes.load(Ordering::SeqCst) > 0 {
            let rem = deadline.saturating_duration_since(tokio::time::Instant::now());
            if rem.is_zero() {
                break;
            }
            let _ = tokio::time::timeout(rem, self.writes_drained.notified()).await;
        }

        // 2. Stop wrapped upstream app & worker cleanly so SQLite WAL flushes
        self.stop_child_slot(&self.worker_child, Duration::from_secs(3)).await;
        self.stop_child_slot(&self.app_child, Duration::from_secs(4)).await;

        // 3. Force remote sync via `litestream sync -wait` then gracefully stop replicate
        let final_txid = self.ls.sync_wait(15).await.ok().flatten();
        self.stop_child_slot(&self.replicate_child, Duration::from_secs(5)).await;

        // 4. Release R2 lease with exact `final_txid`
        if let Some(snap) = self.active_lease.lock().await.take() {
            let cur = self.lease.read().await.ok().flatten().unwrap_or(snap);
            if cur.record.holder_id == self.cfg.node_id {
                let _ = self.lease.release(&cur, final_txid).await;
            }
        }
        let _ = self.role_tx.send(ProxyRole::Stopped);
    }

    async fn emergency_fence_stop(&self) {
        let _ = self.role_tx.send(ProxyRole::Draining);
        for slot in [&self.worker_child, &self.app_child, &self.replicate_child] {
            if let Some(mut c) = slot.lock().await.take() {
                let _ = c.kill().await;
                let _ = c.wait().await;
            }
        }
        *self.active_lease.lock().await = None;
        let _ = self.role_tx.send(ProxyRole::Stopped);
    }
}

fn is_write_method(m: &Method) -> bool {
    matches!(m, &Method::POST | &Method::PUT | &Method::PATCH | &Method::DELETE)
}

async fn proxy_handler(State(sup): State<Arc<ProxySupervisor>>, req: Request) -> Response {
    let path_and_query = req
        .uri()
        .path_and_query()
        .map(|pq| pq.as_str().to_string())
        .unwrap_or_else(|| "/".to_string());

    if req.uri().path() == "/up" {
        return match sup.role() {
            ProxyRole::Primary { .. } | ProxyRole::Standby { .. } | ProxyRole::Promoting => {
                (StatusCode::OK, Json(sup.stats())).into_response()
            }
            _ => (StatusCode::SERVICE_UNAVAILABLE, Json(sup.stats())).into_response(),
        };
    }
    if req.uri().path() == "/_ephemeral/status" {
        return Json(sup.stats()).into_response();
    }

    let method = req.method().clone();
    let headers = req.headers().clone();
    let is_write = is_write_method(&method);
    let mut waited_ms: Option<u64> = None;

    if is_write {
        match sup.role() {
            ProxyRole::Primary { .. } => {}
            ProxyRole::Standby { .. } | ProxyRole::Promoting | ProxyRole::Booting => {
                let s = Arc::clone(&sup);
                tokio::spawn(async move {
                    s.signal_yield().await;
                });
                match sup.wait_for_primary().await {
                    Ok(ms) => waited_ms = Some(ms),
                    Err(reason) => {
                        let mut r = (StatusCode::SERVICE_UNAVAILABLE, format!("handoff: {reason}")).into_response();
                        r.headers_mut().insert("retry-after", HeaderValue::from_static("1"));
                        return r;
                    }
                }
            }
            ProxyRole::Draining | ProxyRole::Stopped => {
                let mut r = (StatusCode::SERVICE_UNAVAILABLE, "draining").into_response();
                r.headers_mut().insert("retry-after", HeaderValue::from_static("1"));
                return r;
            }
        }
    } else if matches!(sup.role(), ProxyRole::Promoting | ProxyRole::Booting) {
        // Hold GET/HEAD briefly (~50ms) while upstream restarts from Standby RO -> Primary RW
        // so live reads experience ZERO 502 errors during rolling deploy promotion!
        let _ = sup.wait_for_primary().await;
    }

    // Track in-flight writes so drain waits for completion
    struct Guard(Arc<ProxySupervisor>);
    impl Drop for Guard {
        fn drop(&mut self) {
            if self.0.in_flight_writes.fetch_sub(1, Ordering::SeqCst) == 1 {
                self.0.writes_drained.notify_waiters();
            }
        }
    }
    let _write_guard = if is_write {
        sup.in_flight_writes.fetch_add(1, Ordering::SeqCst);
        if !matches!(sup.role(), ProxyRole::Primary { .. }) {
            if sup.in_flight_writes.fetch_sub(1, Ordering::SeqCst) == 1 {
                sup.writes_drained.notify_waiters();
            }
            let mut r = (StatusCode::SERVICE_UNAVAILABLE, "draining").into_response();
            r.headers_mut().insert("retry-after", HeaderValue::from_static("1"));
            return r;
        }
        Some(Guard(Arc::clone(&sup)))
    } else {
        None
    };

    let body_bytes = match to_bytes(req.into_body(), 16 * 1024 * 1024).await {
        Ok(b) => b,
        Err(e) => return (StatusCode::BAD_REQUEST, e.to_string()).into_response(),
    };

    let is_hop_by_hop = |h: &str| {
        matches!(
            h.to_ascii_lowercase().as_str(),
            "connection"
                | "keep-alive"
                | "proxy-authenticate"
                | "proxy-authorization"
                | "te"
                | "trailer"
                | "trailers"
                | "transfer-encoding"
                | "upgrade"
        )
    };
    let target_url = format!("http://{}{}", sup.cfg.upstream_addr, path_and_query);
    let mut upstream_resp = None;
    let mut last_err = None;
    for attempt in 0..2 {
        let mut out_req = sup.http.request(method.clone(), &target_url).body(body_bytes.clone());
        for (name, val) in headers.iter() {
            if name.as_str().eq_ignore_ascii_case("host")
                || name.as_str().eq_ignore_ascii_case("content-length")
                || is_hop_by_hop(name.as_str())
            {
                continue;
            }
            out_req = out_req.header(name, val);
        }
        match out_req.send().await {
            Ok(r) => {
                upstream_resp = Some(r);
                break;
            }
            Err(e) => {
                last_err = Some(e);
                if attempt == 0 && !is_write && matches!(sup.role(), ProxyRole::Promoting | ProxyRole::Standby { .. }) {
                    let _ = sup.wait_for_primary().await;
                    continue;
                }
                break;
            }
        }
    }
    let upstream_resp = match upstream_resp {
        Some(r) => r,
        None => {
            tracing::warn!(error = ?last_err, "litebucket-proxy upstream error");
            return (StatusCode::BAD_GATEWAY, "upstream bad gateway").into_response();
        }
    };

    let status = upstream_resp.status();
    let resp_headers = upstream_resp.headers().clone();
    let resp_bytes = upstream_resp.bytes().await.unwrap_or_default();

    let mut resp = Response::builder().status(status).body(Body::from(resp_bytes)).unwrap();
    for (k, v) in resp_headers.iter() {
        if is_hop_by_hop(k.as_str()) || k.as_str().eq_ignore_ascii_case("content-length") {
            continue;
        }
        if let Ok(name) = HeaderName::from_bytes(k.as_str().as_bytes()) {
            resp.headers_mut().append(name, v.clone());
        }
    }
    if let Some(ms) = waited_ms
        && let Ok(v) = HeaderValue::from_str(&ms.to_string()) {
            resp.headers_mut().insert("x-ephemeral-handoff-wait-ms", v);
        }
    resp
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "info".into()),
        )
        .init();

    let port: u16 = std::env::var("PORT").ok().and_then(|s| s.parse().ok()).unwrap_or(8080);
    let upstream_port: u16 = std::env::var("UPSTREAM_PORT")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(port + 10000);
    let node_id = std::env::var("NODE_ID")
        .unwrap_or_else(|_| format!("proxy-{}", &uuid::Uuid::new_v4().to_string()[..8]));
    let work_dir = PathBuf::from(
        std::env::var("WORK_DIR").unwrap_or_else(|_| format!("/tmp/ephemeral-proxy-{node_id}")),
    );
    let litestream_bin = PathBuf::from(
        std::env::var("LITESTREAM_BIN").unwrap_or_else(|_| "litestream".into()),
    );
    let app_cmd = std::env::var("APP_CMD").expect("APP_CMD env var required");
    let migrate_cmd = std::env::var("MIGRATE_CMD").ok().filter(|s| !s.is_empty());
    let worker_cmd = std::env::var("WORKER_CMD").ok().filter(|s| !s.is_empty());

    let bind_host = std::env::var("BIND_ADDR")
        .or_else(|_| std::env::var("HOST"))
        .unwrap_or_else(|_| "::".to_string());
    let listen_addr: SocketAddr = match bind_host.parse::<std::net::IpAddr>() {
        Ok(ip) => SocketAddr::new(ip, port),
        Err(_) => SocketAddr::from(([0, 0, 0, 0], port)),
    };

    let cfg = ProxyConfig {
        node_id: node_id.clone(),
        listen_addr,
        upstream_addr: SocketAddr::from(([127, 0, 0, 1], upstream_port)),
        work_dir,
        litestream_bin,
        s3: S3Config::from_env()?,
        replica_prefix: std::env::var("REPLICA_PREFIX").unwrap_or_else(|_| "proxy/db".into()),
        lease_key: std::env::var("LEASE_KEY").unwrap_or_else(|_| "proxy/lease.json".into()),
        lease_ttl_ms: std::env::var("LEASE_TTL_MS")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(2500),
        sync_interval: std::env::var("SYNC_INTERVAL").unwrap_or_else(|_| "150ms".into()),
        app_cmd,
        migrate_cmd,
        worker_cmd,
        write_hold_timeout_ms: 15_000,
    };

    let listen_addr = cfg.listen_addr;
    let sup = ProxySupervisor::start(cfg).await?;

    let app = Router::new().fallback(any(proxy_handler)).with_state(Arc::clone(&sup));
    let listener = match tokio::net::TcpListener::bind(listen_addr).await {
        Ok(l) => l,
        Err(_) if listen_addr.is_ipv6() => {
            let fallback = SocketAddr::from(([0, 0, 0, 0], port));
            tokio::net::TcpListener::bind(fallback).await?
        }
        Err(e) => return Err(e.into()),
    };
    let bound_addr = listener.local_addr()?;
    info!(listen_addr = %bound_addr, %node_id, "litebucket-proxy listening");

    let sup_shutdown = Arc::clone(&sup);
    axum::serve(listener, app)
        .with_graceful_shutdown(async move {
            shutdown_signal().await;
            sup_shutdown.graceful_drain().await;
        })
        .await?;

    Ok(())
}

async fn shutdown_signal() {
    let ctrl_c = async {
        let _ = tokio::signal::ctrl_c().await;
    };
    #[cfg(unix)]
    let terminate = async {
        let mut sig = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
            .expect("install SIGTERM handler");
        sig.recv().await;
    };
    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();
    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }
}