Merge pull request 'feat(sdk): explicit Tor lifecycle — Wire.shutdown / flush / torState + observable state' (#49) from feat/tor-lifecycle into main
All checks were successful
ci / test (push) Successful in 4m17s
release / version (push) Successful in 2s
release / x86_64 (push) Successful in 1m55s
release / aarch64 (push) Successful in 2m25s
release / publish (push) Successful in 11s

Reviewed-on: #49
This commit is contained in:
sirius 2026-09-12 20:58:31 +00:00
commit 02b531625f
6 changed files with 834 additions and 27 deletions

View file

@ -96,6 +96,64 @@ pub fn hs_is_ready(state: State, probe_ok: bool) -> bool {
}
}
/// Observable lifecycle state of the node's onion service.
///
/// This is the four-state projection callers actually act on: is the onion
/// service serving, is it serving but unhealthy, is it still coming up, or did
/// we stop it. A process that gets killed by the Android background-process
/// killer never observes `Stopped` — that is why `Wire.flush()` exists — but a
/// clean teardown always does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TorState {
/// Bootstrap or HsDir descriptor upload is still in flight: the service is
/// not reliably reachable yet.
Bootstrapping,
/// The onion service is running and its descriptor is published.
Published,
/// Reachable through the service, but Arti reports the service degraded.
/// Usable, worth surfacing, not identical to `Published`.
DegradedReachable,
/// The node was shut down: no onion service, no client dials, and the
/// store is checkpointed.
Stopped,
}
/// Project an Arti onion-service status onto [`TorState`].
///
/// Deliberately mirrors `hs_is_ready`: `Running` and `DegradedReachable` are
/// the states a probe could already reach, everything transient is
/// `Bootstrapping`, and a shut-down service is `Stopped`.
///
/// `reachable` is the same evidence `wait_until_published` accepts from a
/// probe: a successful connect to our own onion means some HsDir already has
/// the descriptor even though Arti's combined status is still `Bootstrapping`
/// (that mismatch is exactly what the 360s publish wait exists for). Without
/// it, a node that is live and reachable would report `Bootstrapping` for
/// another few minutes.
///
/// Two statuses look terminal but are not:
/// * `Shutdown` on a *live* node is transient — a freshly launched service
/// reports it before its publish reactor starts, which is why a live node
/// reads `Bootstrapping` there and only the explicit stop flag produces
/// `Stopped`. (Caught on device-real conditions by the live test: the
/// first `tor_state()` after `start()` returned `Shutdown`.)
/// * `Broken` maps to `Bootstrapping` rather than a state of its own: Arti
/// reads `Broken` while the HsDir retry loop is still going, and
/// `wait_until_published` is where a genuinely dead service surfaces as an
/// error instead of a flag the UI would have to poll for.
pub fn tor_state_of(state: State, stopped: bool, reachable: bool) -> TorState {
if stopped {
return TorState::Stopped;
}
match state {
State::Running => TorState::Published,
State::DegradedReachable => TorState::DegradedReachable,
State::Broken | State::Shutdown => TorState::Bootstrapping,
_ if reachable => TorState::Published,
_ => TorState::Bootstrapping,
}
}
pub async fn wait_until_published(
client: &Client,
svc: &RunningOnionService,

View file

@ -1,6 +1,7 @@
//! Two-node onion session: host HS, Noise IK, persist plaintext locally.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
@ -13,7 +14,7 @@ use zeroize::Zeroizing;
use crate::dispatch::{self, Kind};
use crate::file;
use crate::frame;
use crate::hs::{self, Client, HS_PORT};
use crate::hs::{self, Client, HS_PORT, TorState};
use crate::loc;
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
use crate::pay;
@ -30,8 +31,27 @@ pub struct RotateResult {
pub friends: usize,
}
/// What a `flush` actually managed to do, for UI surfacing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FlushOutcome {
/// Outbox rows we tried to deliver in this pass.
pub attempted: usize,
/// Rows delivered now — their outbox rows are gone.
pub delivered: usize,
/// Rows still queued or terminally failed after the pass.
pub remaining: usize,
}
/// A foreground/unlock flush is bounded: the caller is a UI thread and a dead
/// peer's onion can hold a dial open for 20s. Whatever is left stays queued and
/// the retry worker picks it up on its normal schedule.
pub const FLUSH_TIMEOUT: Duration = Duration::from_secs(30);
/// The drain inside `shutdown` gets a shorter budget: teardown must not hang
/// the caller behind a Tor dial. Undelivered rows survive in sqlite.
pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(10);
struct HsHandle {
_svc: Arc<RunningOnionService>,
svc: Arc<RunningOnionService>,
rend: tokio::task::JoinHandle<()>,
}
@ -61,7 +81,17 @@ pub struct Node {
incoming_limit: Mutex<TokenBucket>,
inbox: Mutex<file::Inbox>,
outbox: Arc<Outbox>,
_outbox_worker: WorkerHandle,
worker: Mutex<Option<WorkerHandle>>,
/// Set by `shutdown`. Checked before any operation that would touch Tor or
/// the store, so a stopped node fails cleanly instead of dialing.
stopped: AtomicBool,
/// Has this node's onion service ever crossed the reachability bar (status
/// `Running`/`DegradedReachable`, or a successful probe of our own onion)?
/// Arti's combined status can stay `Bootstrapping` for minutes *after* the
/// descriptor is downloadable, so without this the UI would keep saying
/// "starting" long past the point where friends can reach us. Cleared when
/// `rotate` hard-cuts the service.
onion_reachable: AtomicBool,
}
impl Node {
@ -113,7 +143,9 @@ impl Node {
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(inbox),
outbox: Arc::clone(&outbox),
_outbox_worker: WorkerHandle(outbox.spawn_worker()),
worker: Mutex::new(Some(WorkerHandle(outbox.spawn_worker()))),
stopped: AtomicBool::new(false),
onion_reachable: AtomicBool::new(false),
});
// Unlock trigger: flush anything queued by a previous run now, in the
// background, rather than waiting out its backoff.
@ -122,10 +154,14 @@ impl Node {
// while combined status is still Bootstrapping.
let rend = spawn_rend(Arc::clone(&node), rend);
*node.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
_svc: Arc::clone(&svc),
svc: Arc::clone(&svc),
rend,
});
hs::wait_until_published(&node.client, &svc, &onion).await?;
// Published by the same bar `wait_until_published` uses — a probe
// success counts, which is the whole reason `tor_state` tracks it
// separately from Arti's (slower, flappier) combined status.
node.onion_reachable.store(true, Ordering::SeqCst);
node.store
.lock()
.map_err(|e| e.to_string())?
@ -134,6 +170,141 @@ impl Node {
Ok(node)
}
/// Observable onion/Tor lifecycle state: `Bootstrapping` / `Published` /
/// `DegradedReachable` / `Stopped`.
///
/// Read-only and cheap (one mutex + one status read, no I/O), so a UI or a
/// foreground-service notification can poll it instead of guessing from a
/// timer. A poisoned handle is reported as `Stopped` rather than panicking:
/// the node is unusable either way, and the caller is often a UI thread.
pub fn tor_state(&self) -> TorState {
let stopped = self.stopped.load(Ordering::SeqCst);
let reachable = self.onion_reachable.load(Ordering::SeqCst);
match self.hs.lock() {
Ok(guard) => match guard.as_ref() {
Some(h) => hs::tor_state_of(h.svc.status().state(), stopped, reachable),
// Between `rotate`'s hard cut and the new service being
// installed there is no handle; before the first publish there
// is none either. Both are "not serving *yet*" unless we stopped.
None if stopped => TorState::Stopped,
None => TorState::Bootstrapping,
},
Err(_) => TorState::Stopped,
}
}
/// Drain the outbox: one delivery attempt for every outstanding row, now,
/// ignoring its retry schedule. Then checkpoint the WAL.
///
/// This is the "deliver what is deliverable before we lose the process"
/// call. Bounded by [`FLUSH_TIMEOUT`] because a dead peer's onion holds a
/// dial for ~20s and the caller is usually a UI thread. Rows that could not
/// be delivered stay queued and are picked up by the retry worker on its
/// normal backoff.
pub async fn flush(&self) -> Result<FlushOutcome, String> {
self.ensure_running()?;
let outcome = self.drain(FLUSH_TIMEOUT).await?;
self.checkpoint();
Ok(outcome)
}
/// Stop the node.
///
/// Order matters: drain the outbox while the Tor client is still alive,
/// then drop the onion service (its rendezvous task is aborted and the v3
/// service goes down), then abort the retry worker so nothing dials after
/// this, then checkpoint the WAL.
///
/// Idempotent: the flag is swapped first, so a second call — or a call
/// racing another teardown — returns `Ok(())` without touching anything
/// twice. Every other method on a stopped node returns a clean `Err`, never
/// a panic. A process killed outright never gets here at all, which is why
/// [`flush`](Self::flush) exists.
pub async fn shutdown(&self) -> Result<(), String> {
if self.stopped.swap(true, Ordering::SeqCst) {
return Ok(());
}
// Bounded: teardown must not hang behind a Tor dial. Undelivered rows
// survive in sqlite and are retried on the next unlock.
match self.drain(SHUTDOWN_FLUSH_TIMEOUT).await {
Ok(o) if o.remaining > 0 => {
eprintln!("shutdown: {} outbox row(s) still pending", o.remaining)
}
Ok(_) => {}
Err(e) => eprintln!("shutdown: drain failed: {e}"),
}
match self.hs.lock() {
Ok(mut g) => *g = None,
Err(_) => eprintln!("shutdown: onion-service lock poisoned"),
}
match self.worker.lock() {
Ok(mut g) => drop(g.take()),
Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"),
}
self.checkpoint();
Ok(())
}
/// One bounded pass over every outstanding outbox row.
///
/// A timeout cancels the pass mid-flight, which can leave a row in
/// `sending`; `Outbox::reset_stale` requeues those on the next unlock, the
/// same recovery the parent uses for a process that died mid-attempt.
async fn drain(&self, budget: Duration) -> Result<FlushOutcome, String> {
let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).await {
Ok(Ok(rows)) => Some(rows),
Ok(Err(e)) => return Err(e),
Err(_) => {
eprintln!("outbox: drain hit its {budget:?} budget, undelivered rows stay queued");
None
}
};
let delivered = attempted
.as_ref()
.map(|rows| {
rows.iter()
.filter(|(_, s)| matches!(s, OutboxStatus::Sent))
.count()
})
.unwrap_or(0);
Ok(FlushOutcome {
// `None` means the pass was cancelled: we know how many rows are
// still queued, not how many were started.
attempted: attempted.as_ref().map(Vec::len).unwrap_or(0),
delivered,
remaining: self.pending_rows()?,
})
}
/// Rows the outbox still holds for every friend, queued or terminally
/// failed. A message absent here was delivered.
fn pending_rows(&self) -> Result<usize, String> {
let friends = self.list_friends()?;
let mut n = 0usize;
for f in &friends {
n += self.outbox.pending(&f.pubkey)?.len();
}
Ok(n)
}
/// Checkpoint the sqlite WAL into the main db file and truncate it.
///
/// Best effort on purpose: WAL replay on open recovers everything committed,
/// so this is about leaving less to replay (and less on disk) if the
/// process is killed right after teardown — not about correctness.
fn checkpoint(&self) {
if let Err(e) = checkpoint_wal(&self.home) {
eprintln!("wal checkpoint: {e}");
}
}
fn ensure_running(&self) -> Result<(), String> {
if self.stopped.load(Ordering::SeqCst) {
return Err("node is stopped — open the identity again".to_string());
}
Ok(())
}
pub fn onion(&self) -> String {
self.onion.lock().map(|g| g.clone()).unwrap_or_default()
}
@ -434,6 +605,7 @@ impl Node {
}
async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
self.ensure_running()?;
let (onion, prekey) = {
let f = self.friend(friend_pk)?;
if f.prekey.len() != 32 {
@ -447,6 +619,7 @@ impl Node {
/// Dial a peer's onion. Success is evidence the peer is up, which is one of
/// the outbox retry triggers.
pub async fn connect_onion(&self, onion: &str) -> Result<(), String> {
self.ensure_running()?;
tokio::time::timeout(
Duration::from_secs(20),
self.client.connect((onion, HS_PORT)),
@ -466,6 +639,7 @@ impl Node {
}
pub async fn rotate(self: &Arc<Self>) -> Result<RotateResult, String> {
self.ensure_running()?;
let old_nick = self
.store
.lock()
@ -482,12 +656,16 @@ impl Node {
let onion = hs::onion_string(&svc)?;
// ponytail: hard-cut old HS before waiting; keeping both stalled ow1 at Bootstrapping.
*self.hs.lock().map_err(|e| e.to_string())? = None;
// The new service is not reachable until it publishes: the locator in
// flight is dead until then, so do not carry the old verdict over.
self.onion_reachable.store(false, Ordering::SeqCst);
let rend = spawn_rend(Arc::clone(self), rend);
*self.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
_svc: Arc::clone(&svc),
svc: Arc::clone(&svc),
rend,
});
hs::wait_until_published(&self.client, &svc, &onion).await?;
self.onion_reachable.store(true, Ordering::SeqCst);
{
let store = self.store.lock().map_err(|e| e.to_string())?;
store.set_onion(&onion).map_err(|e| e.to_string())?;
@ -549,6 +727,7 @@ impl Node {
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
/// frame) still fails immediately and is never retried.
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
self.ensure_running()?;
self.outbox.send(friend_pk, plaintext).await
}
@ -857,6 +1036,49 @@ fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
});
}
/// Checkpoint the sqlite WAL into the main db file and truncate it.
///
/// `Store` owns the write connection and deliberately does not lend it out, and
/// a checkpoint is a property of the *database*, not of one connection — so a
/// short-lived second connection to the same file is the least invasive way to
/// reach it from the node without widening `Store`'s API.
///
/// That works because the connection needs no passphrase: it moves
/// already-committed pages, it does not decrypt them. It stops working the
/// moment the store is SQLCipher-encrypted (PR #43), because the key lives only
/// inside `Store` and a second connection cannot read the file at all. That case
/// is detected and reported as a skip rather than a failure: nothing is lost
/// (sqlite folds the WAL into the db when the last connection closes) — the
/// explicit truncation just has to move inside `Store` to happen here.
fn checkpoint_wal(home: &Path) -> Result<(), String> {
let db = home.join("onionwire.db");
if !db.exists() {
return Ok(());
}
let conn = rusqlite::Connection::open(&db).map_err(|e| format!("open {}: {e}", db.display()))?;
let (busy, log, checkpointed): (i64, i64, i64) = conn
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
})
.map_err(|e| {
let msg = e.to_string();
if msg.contains("not a database") {
// SQLCipher store: no key here, so this connection sees noise.
format!("store is SQLCipher-encrypted — skipped ({msg})")
} else {
format!("wal_checkpoint: {msg}")
}
})?;
if busy != 0 {
// Another connection is reading/writing: pages are still safe in the
// WAL, they just were not moved this time.
return Err(format!(
"busy ({checkpointed}/{log} pages moved, another connection active)"
));
}
Ok(())
}
fn next_hs_nickname(cur: &str) -> String {
let n = cur
.strip_prefix("ow")
@ -899,3 +1121,57 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
}
false
}
#[cfg(test)]
mod lifecycle_tests {
//! Offline half of the shutdown contract. The live-Tor half lives in
//! `tests/tor_lifecycle.rs` (ignored) — everything here runs in CI.
use super::*;
/// `checkpoint_wal` reaches the database through a *second* connection,
/// because `Store` owns the write one. That assumption is the whole reason
/// the helper can live in `node.rs`, so prove it against a real WAL.
#[test]
fn checkpoint_wal_truncates_a_live_wal() {
let root = tempfile::tempdir().expect("tempdir");
let home = root.path();
let db = home.join("onionwire.db");
let conn = rusqlite::Connection::open(&db).expect("open db");
let mode: String = conn
.query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0))
.expect("wal mode");
assert_eq!(mode.to_lowercase(), "wal");
conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v BLOB);")
.expect("create table");
for _ in 0..64 {
conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params![vec![7u8; 512]])
.expect("insert");
}
let wal = home.join("onionwire.db-wal");
let before = std::fs::metadata(&wal).expect("wal file").len();
assert!(before > 0, "expected pending WAL frames, got {before}");
checkpoint_wal(home).expect("checkpoint");
let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0);
assert_eq!(after, 0, "WAL not truncated ({before} bytes before)");
// The rows are still there — a checkpoint moves pages, it never drops
// committed data.
let n: i64 = conn
.query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0))
.expect("count");
assert_eq!(n, 64);
}
/// A home directory with no store yet is not an error: `shutdown` and
/// `flush` are safe to call on a node whose db was never created (tests,
/// wiped installs).
#[test]
fn checkpoint_wal_is_a_no_op_without_a_database() {
let root = tempfile::tempdir().expect("tempdir");
checkpoint_wal(root.path()).expect("no db, no error");
}
}