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
95
tests/hs.rs
95
tests/hs.rs
|
|
@ -69,6 +69,101 @@ fn broken_or_shutdown_never_ready() {
|
|||
assert!(!hs::hs_is_ready(State::Shutdown, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tor_state_maps_every_arti_status() {
|
||||
// The four states the Android UI branches on, derived from the same status
|
||||
// union `hs_is_ready` reads.
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::Running, false, false),
|
||||
hs::TorState::Published
|
||||
);
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::DegradedReachable, false, false),
|
||||
hs::TorState::DegradedReachable
|
||||
);
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::Bootstrapping, false, false),
|
||||
hs::TorState::Bootstrapping
|
||||
);
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::DegradedUnreachable, false, false),
|
||||
hs::TorState::Bootstrapping
|
||||
);
|
||||
// A freshly launched service reports Shutdown before its publish reactor
|
||||
// starts. Mapping that to Stopped would make a live node look dead for the
|
||||
// first seconds after unlock — caught on a real Tor network.
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::Shutdown, false, false),
|
||||
hs::TorState::Bootstrapping
|
||||
);
|
||||
// Arti reads `Broken` while the HsDir retry loop is still going; a dead
|
||||
// service surfaces as an error from `wait_until_published`, not as a state
|
||||
// the UI has to poll for.
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::Broken, false, false),
|
||||
hs::TorState::Bootstrapping
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reachable_statuses_report_published_while_arti_says_bootstrapping() {
|
||||
// `wait_until_published` returns on a successful probe while Arti's
|
||||
// combined status is still Bootstrapping (see `hs_is_ready`). Reporting
|
||||
// Bootstrapping there would keep the UI saying "starting" for minutes after
|
||||
// friends can actually reach us.
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::Bootstrapping, false, true),
|
||||
hs::TorState::Published
|
||||
);
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::DegradedUnreachable, false, true),
|
||||
hs::TorState::Published
|
||||
);
|
||||
// Broken stays Broken, reachable or not: `hs_is_ready` refuses it too.
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::Broken, false, true),
|
||||
hs::TorState::Bootstrapping
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopped_outranks_whatever_arti_reports() {
|
||||
// A node that has been told to stop is Stopped even if Arti's status cache
|
||||
// still says Running, and even if it was reachable a moment ago: the flag
|
||||
// is set before the service is dropped.
|
||||
for state in [
|
||||
State::Running,
|
||||
State::DegradedReachable,
|
||||
State::DegradedUnreachable,
|
||||
State::Bootstrapping,
|
||||
State::Broken,
|
||||
State::Shutdown,
|
||||
] {
|
||||
for reachable in [false, true] {
|
||||
assert_eq!(
|
||||
hs::tor_state_of(state, true, reachable),
|
||||
hs::TorState::Stopped,
|
||||
"wrong state for {state:?} (reachable={reachable}) on a stopped node"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ready_states_are_the_published_ones() {
|
||||
// Published/degraded must not drift from the readiness bar: anything
|
||||
// `hs_is_ready` accepts without a probe is a state the UI calls up.
|
||||
let ready = [State::Running, State::DegradedReachable];
|
||||
for state in ready {
|
||||
assert!(hs::hs_is_ready(state, false), "{state:?} must be ready");
|
||||
assert_ne!(
|
||||
hs::tor_state_of(state, false, false),
|
||||
hs::TorState::Bootstrapping,
|
||||
"{state:?} is ready but reported as still coming up"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hs_log_label_is_not_the_full_v3_onion() {
|
||||
// Public v3 address; checksum is valid so HsId::from_str works.
|
||||
|
|
|
|||
96
tests/tor_lifecycle.rs
Normal file
96
tests/tor_lifecycle.rs
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
//! Lifecycle: a node stops when told to, says so, and refuses further work
|
||||
//! with an error instead of panicking.
|
||||
//!
|
||||
//! Needs a live Tor network to publish the onion service, so `cargo test` skips
|
||||
//! it. Run it on a networked machine with:
|
||||
//!
|
||||
//! ```text
|
||||
//! cargo test --test tor_lifecycle -- --ignored --nocapture
|
||||
//! ```
|
||||
//!
|
||||
//! The offline half of this contract — the Arti-status projection, the WAL
|
||||
//! checkpoint, and the SDK's typed error after shutdown — runs in the normal
|
||||
//! suite (`tests/hs.rs`, `src/node.rs`, `crates/onionwire-sdk/src/lib.rs`).
|
||||
|
||||
use onionwire::node::{FlushOutcome, Node};
|
||||
use onionwire::hs::TorState;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "needs live Tor network"]
|
||||
async fn shutdown_stops_the_node_and_later_calls_are_typed_errors() {
|
||||
let _ = tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()),
|
||||
)
|
||||
.with_test_writer()
|
||||
.try_init();
|
||||
|
||||
let root = tempfile::tempdir().expect("tempdir");
|
||||
let home = root.path().join("alice");
|
||||
unsafe {
|
||||
std::env::set_var("ONIONWIRE_STORE_PASSPHRASE", "onionwire-test");
|
||||
}
|
||||
|
||||
let node = Node::start(home.clone()).await.expect("start");
|
||||
|
||||
// `start` returns only after `wait_until_published`, so the node is
|
||||
// reachable by the time a caller can call this — which must not read as
|
||||
// `Stopped` or `Bootstrapping`. `DegradedReachable` is the honest answer
|
||||
// when Arti says the service is degraded.
|
||||
//
|
||||
// This caught a real bug: `tor_state()` originally projected Arti's raw
|
||||
// combined status, which is still `Bootstrapping` after a *successful*
|
||||
// probe (that mismatch is what the 360s publish wait exists for), and which
|
||||
// reads `Shutdown` on a service that has not started its reactor yet — so a
|
||||
// live node reported `Stopped`. See `onion_reachable` in `src/node.rs`.
|
||||
let started_state = node.tor_state();
|
||||
assert!(
|
||||
matches!(
|
||||
started_state,
|
||||
TorState::Published | TorState::DegradedReachable
|
||||
),
|
||||
"start returned Ok but tor_state() is {started_state:?}"
|
||||
);
|
||||
|
||||
// A flush with nothing queued is a no-op that reports it, not an error.
|
||||
let drained: FlushOutcome = node.flush().await.expect("flush on a live node");
|
||||
assert_eq!(drained.remaining, 0, "empty outbox: {drained:?}");
|
||||
|
||||
node.shutdown().await.expect("shutdown");
|
||||
|
||||
assert_eq!(
|
||||
node.tor_state(),
|
||||
TorState::Stopped,
|
||||
"tor_state must report Stopped after shutdown"
|
||||
);
|
||||
|
||||
// Second shutdown: idempotent at the node level — no panic, no repeat work.
|
||||
node.shutdown().await.expect("shutdown is idempotent");
|
||||
|
||||
let err = node
|
||||
.flush()
|
||||
.await
|
||||
.expect_err("flush after shutdown must be an error");
|
||||
assert!(err.contains("stopped"), "flush error was {err:?}");
|
||||
|
||||
let err = node
|
||||
.send(&[0u8; 32], b"after shutdown")
|
||||
.await
|
||||
.expect_err("send after shutdown must be an error");
|
||||
assert!(err.contains("stopped"), "send error was {err:?}");
|
||||
|
||||
// `RotateResult` is not `Debug`, so match on the error instead of
|
||||
// `expect_err`.
|
||||
let err = node
|
||||
.rotate()
|
||||
.await
|
||||
.err()
|
||||
.expect("rotate after shutdown must be an error");
|
||||
assert!(err.contains("stopped"), "rotate error was {err:?}");
|
||||
|
||||
// The store file survives the checkpoint: stopping is not wiping.
|
||||
assert!(
|
||||
home.join("onionwire.db").exists(),
|
||||
"shutdown must not delete the store"
|
||||
);
|
||||
}
|
||||
Loading…
Reference in a new issue