feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state
A node had no way to stop. `Wire` was a bare handle over a `Node`: dropping the
Kotlin reference left Arti's client, the hosted v3 onion service, the outbox
retry worker and the sqlite connection alive, and there was no way to ask where
the onion service was. On Android the process is killed without warning by Doze
and the background-process killer, so "drop everything when the process dies" is
not a lifecycle.
Core (`src/node.rs`, `src/hs.rs`):
* `Node::shutdown()` — bounded outbox drain (10s), stop the onion service (the
rendezvous task is aborted and the RunningOnionService dropped), abort the
retry worker, checkpoint the sqlite WAL. Idempotent at this level: the flag is
swapped first, so a racing second call is a no-op.
* `Node::flush() -> FlushOutcome { attempted, delivered, remaining }` — one
delivery attempt for every queued outbox row, ignoring backoff, then a WAL
checkpoint. Bounded by 30s because a dead peer's onion holds a dial for ~20s
and the caller is a UI thread. A timeout leaves rows in `sending`;
`Outbox::reset_stale` requeues them on the next unlock, same as a process that
died mid-attempt.
* `Node::tor_state() -> TorState` (`Bootstrapping` / `Published` /
`DegradedReachable` / `Stopped`) and `hs::tor_state_of(state, stopped,
reachable)`, which mirrors `hs_is_ready` exactly instead of re-deriving
readiness.
* Every network entry point (`send`, `send_once`, `connect_onion`, `rotate`,
`flush`) fails with a typed error after the node stops, rather than dialing a
dead client.
* `checkpoint_wal` reaches the database through a short-lived second connection:
`Store` owns the write connection and does not lend it out, and a checkpoint is
a property of the database, not of one connection. Best effort — WAL replay on
open recovers anything committed.
The `WorkerHandle` moved into a `Mutex<Option<...>>` so the teardown can *abort*
the retry worker instead of only dropping it when the whole `Node` dies.
SDK (`crates/onionwire-sdk/src/lib.rs`):
* `Wire.shutdown()`, `Wire.flush(): FlushOutcome`, `Wire.torState(): TorState`.
`Wire` now holds `Mutex<Option<Arc<Node>>>`, so teardown drops the last
reference to the Tor client and the store instead of keeping them alive behind
a JNI handle.
* `WireError::Stopped` — a second flat variant, so "you must unlock again" is a
typed `WireException.Stopped` in Kotlin, not a string match on `Failed`.
* No `unwrap()` on a poisoned mutex anywhere: a poisoned handle reports
`Stopped`, which is the correct recovery (unlock again).
* Fixes the crate not compiling on this base at all: `Node::send` has returned
`Result<OutboxStatus, String>` since the outbox landed, and the SDK still
mapped it to `Result<(), String>` (E0308). CI's path allowlist excludes
`crates/**` from the Rust job, which is why it stayed green.
The live Tor test found a real bug in the first version of `tor_state`: Arti's
combined status is still `Bootstrapping` after a *successful* probe of our own
onion (that mismatch is what the 360s publish wait exists for), and a freshly
launched service reports `Shutdown` before its publish reactor starts — so a
node that was live and reachable reported `Bootstrapping`, and briefly
`Stopped`, right after unlock. `Node` now tracks an `onion_reachable` flag set
when the publish bar is crossed and cleared when `rotate` hard-cuts the service,
and `Shutdown`/`Broken` on a live node read `Bootstrapping` (transient) rather
than terminal.
This commit is contained in:
parent
c39259b919
commit
38fde75d40
5 changed files with 772 additions and 25 deletions
288
src/node.rs
288
src/node.rs
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue