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
ad59a171b3
commit
201aa48344
5 changed files with 757 additions and 25 deletions
|
|
@ -13,13 +13,20 @@
|
|||
//! Orbot pipe. If the onion service cannot publish, this fails closed.
|
||||
//! * Chat bodies are encrypted at rest. Identity keys in sqlite are not.
|
||||
//!
|
||||
//! Lifecycle: a node is started by [`open_wire`] and stopped by
|
||||
//! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable
|
||||
//! state and [`Wire::flush`] is "deliver what is deliverable now". A process
|
||||
//! killed by Doze or the background-process killer never runs `shutdown`, which
|
||||
//! is exactly why queued sends live in sqlite and not in memory.
|
||||
//!
|
||||
//! The façade deliberately exposes only plain data (records + hex strings) so
|
||||
//! no TUI/ratatui type leaks into the AAR.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use onionwire::node::Node;
|
||||
use onionwire::hs::TorState as CoreTorState;
|
||||
use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node};
|
||||
use onionwire::qr;
|
||||
|
||||
uniffi::setup_scaffolding!();
|
||||
|
|
@ -54,6 +61,12 @@ pub fn install_crypto_provider() {
|
|||
pub enum WireError {
|
||||
#[error("{message}")]
|
||||
Failed { message: String },
|
||||
/// The node was shut down (or never opened). Distinct from `Failed` so
|
||||
/// Kotlin can branch on it instead of string-matching a message, and so
|
||||
/// "you must unlock again" is a different UI state from "the network is
|
||||
/// broken".
|
||||
#[error("node stopped: {message}")]
|
||||
Stopped { message: String },
|
||||
}
|
||||
|
||||
impl WireError {
|
||||
|
|
@ -62,6 +75,12 @@ impl WireError {
|
|||
message: e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn stopped(what: &str) -> Self {
|
||||
Self::Stopped {
|
||||
message: format!("{what} called on a shut-down node"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type WResult<T> = std::result::Result<T, WireError>;
|
||||
|
|
@ -98,10 +117,70 @@ pub struct InviteInfo {
|
|||
pub onion: String,
|
||||
}
|
||||
|
||||
/// Observable lifecycle state of the node's onion service.
|
||||
///
|
||||
/// Mirrors Arti's own service status, projected onto the four states a UI
|
||||
/// actually acts on. It is the same distinction `hs::hs_is_ready` makes when it
|
||||
/// decides whether the onion is reachable yet.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
|
||||
pub enum TorState {
|
||||
/// Bootstrap or descriptor upload still in flight. Not reliably reachable.
|
||||
Bootstrapping,
|
||||
/// Onion service running and its descriptor published.
|
||||
Published,
|
||||
/// Reachable, but Arti reports the service degraded. Usable — worth saying
|
||||
/// so, not identical to `Published`.
|
||||
DegradedReachable,
|
||||
/// Shut down: no onion service, no dials, store checkpointed. Every method
|
||||
/// on the node now returns `WireError.Stopped`.
|
||||
Stopped,
|
||||
}
|
||||
|
||||
impl From<CoreTorState> for TorState {
|
||||
fn from(s: CoreTorState) -> Self {
|
||||
match s {
|
||||
CoreTorState::Bootstrapping => Self::Bootstrapping,
|
||||
CoreTorState::Published => Self::Published,
|
||||
CoreTorState::DegradedReachable => Self::DegradedReachable,
|
||||
CoreTorState::Stopped => Self::Stopped,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a [`Wire::flush`] managed to do.
|
||||
#[derive(Debug, Clone, Copy, uniffi::Record)]
|
||||
pub struct FlushOutcome {
|
||||
/// Rows the pass started a delivery for. `0` when the pass hit its time
|
||||
/// budget before finishing — the rows are still queued, we just stopped
|
||||
/// counting.
|
||||
pub attempted: u32,
|
||||
/// Rows delivered now. A message absent from `remaining` was sent.
|
||||
pub delivered: u32,
|
||||
/// Rows still queued or terminally failed afterwards.
|
||||
pub remaining: u32,
|
||||
}
|
||||
|
||||
/// A running OnionWire node: identity + Arti client + hosted v3 onion service.
|
||||
///
|
||||
/// Holds the node handle. [`Wire::shutdown`] takes it out and drops it, which
|
||||
/// is what lets the last reference to the Tor client and the store go away —
|
||||
/// there is no hidden global keeping Arti (or the sqlite connection) alive
|
||||
/// after the UI is gone.
|
||||
#[derive(uniffi::Object)]
|
||||
pub struct Wire {
|
||||
inner: Arc<Node>,
|
||||
node: Mutex<Option<Arc<Node>>>,
|
||||
}
|
||||
|
||||
impl Wire {
|
||||
/// The live node, or `Stopped` if this handle was shut down. A poisoned
|
||||
/// mutex is reported the same way rather than panicking: a caller that sees
|
||||
/// `Stopped` unlocks again, which is the correct recovery either way.
|
||||
fn node(&self) -> WResult<Arc<Node>> {
|
||||
let guard = self.node.lock().map_err(|_| WireError::Stopped {
|
||||
message: "node handle lock poisoned by a panic; reopen the identity".to_string(),
|
||||
})?;
|
||||
guard.as_ref().cloned().ok_or_else(|| WireError::stopped("this call"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Open (or create) the identity in `home` and start hosting an onion service.
|
||||
|
|
@ -111,6 +190,11 @@ pub struct Wire {
|
|||
///
|
||||
/// This resolves only once the onion service is published — on a cold network
|
||||
/// that is minutes, not seconds. Call it off the main thread.
|
||||
///
|
||||
/// The returned handle owns the node: it lives until [`Wire::shutdown`], or
|
||||
/// until the handle itself is dropped (which the JVM does without running the
|
||||
/// drain, so call `shutdown()` from teardown — see the foreground-service
|
||||
/// caller).
|
||||
#[uniffi::export(async_runtime = "tokio")]
|
||||
pub async fn open_wire(home: String, passphrase: String) -> WResult<Arc<Wire>> {
|
||||
// Before anything that can build a TLS config: Arti's rustls backend dies
|
||||
|
|
@ -120,7 +204,9 @@ pub async fn open_wire(home: String, passphrase: String) -> WResult<Arc<Wire>> {
|
|||
let node = Node::start_with_passphrase(PathBuf::from(home), &passphrase)
|
||||
.await
|
||||
.map_err(WireError::new)?;
|
||||
Ok(Arc::new(Wire { inner: node }))
|
||||
Ok(Arc::new(Wire {
|
||||
node: Mutex::new(Some(node)),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Decode an invite without adding the friend. Verifies the signature.
|
||||
|
|
@ -135,24 +221,76 @@ pub fn decode_invite(invite: String) -> WResult<InviteInfo> {
|
|||
|
||||
#[uniffi::export(async_runtime = "tokio")]
|
||||
impl Wire {
|
||||
/// Stop the node: give every queued outbox row one last bounded delivery
|
||||
/// attempt, stop the onion service, abort the retry worker, checkpoint the
|
||||
/// sqlite WAL, and drop the Tor client.
|
||||
///
|
||||
/// Idempotent and safe to call twice, including from two threads: the
|
||||
/// second call is a no-op returning `Ok`. After it, every other method on
|
||||
/// this handle — including `send` — returns `WireError.Stopped` instead of
|
||||
/// touching a dead client or panicking.
|
||||
///
|
||||
/// Never called at all when the process is killed outright (Doze, the
|
||||
/// background-process killer, a force-stop): that is the case [`flush`]
|
||||
/// (Self::flush) and the sqlite outbox exist for. Once shut down, this
|
||||
/// handle is spent — unlock again to get a new one.
|
||||
pub async fn shutdown(&self) -> WResult<()> {
|
||||
let node = self.node()?;
|
||||
node.shutdown().await.map_err(WireError::new)?;
|
||||
// Drop our handle to the node. With the onion service and the outbox
|
||||
// worker aborted this is the last reference to the Tor client and the
|
||||
// store, so Arti's runtime and the sqlite connection are released here.
|
||||
let mut guard = self.node.lock().map_err(|_| WireError::Stopped {
|
||||
message: "node handle lock poisoned by a panic".to_string(),
|
||||
})?;
|
||||
*guard = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drain the outbox: one delivery attempt for every queued row, now,
|
||||
/// ignoring its retry backoff, then checkpoint the WAL.
|
||||
///
|
||||
/// Bounded by the SDK (30s): a dead peer's onion can hold a dial for ~20s
|
||||
/// and this is called from UI/lifecycle threads. Rows that did not go out
|
||||
/// stay queued; the retry worker keeps its normal schedule. Safe to call
|
||||
/// repeatedly — use it on unlock, on foreground, and before `shutdown`.
|
||||
pub async fn flush(&self) -> WResult<FlushOutcome> {
|
||||
let node = self.node()?;
|
||||
let out = node.flush().await.map_err(WireError::new)?;
|
||||
Ok(from_core_flush(out))
|
||||
}
|
||||
|
||||
/// Where the onion service is right now. Cheap and read-only, no I/O: a
|
||||
/// notification or a settings screen can call it directly.
|
||||
pub fn tor_state(&self) -> TorState {
|
||||
match self.node.lock() {
|
||||
Ok(guard) => match guard.as_ref() {
|
||||
Some(node) => node.tor_state().into(),
|
||||
None => TorState::Stopped,
|
||||
},
|
||||
// Poisoned: same answer as shut down — the node is unusable.
|
||||
Err(_) => TorState::Stopped,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fingerprint of our own identity key. Stable forever for this install.
|
||||
pub async fn fingerprint(&self) -> WResult<String> {
|
||||
self.inner.fingerprint().map_err(WireError::new)
|
||||
self.node()?.fingerprint().map_err(WireError::new)
|
||||
}
|
||||
|
||||
/// Current onion locator. Changes on rotate; identity does not.
|
||||
pub async fn onion(&self) -> String {
|
||||
self.inner.onion()
|
||||
pub async fn onion(&self) -> WResult<String> {
|
||||
Ok(self.node()?.onion())
|
||||
}
|
||||
|
||||
/// `onionwire:v1:…` invite string to hand to the other person out of band.
|
||||
pub async fn invite(&self) -> WResult<String> {
|
||||
self.inner.qr_payload().map_err(WireError::new)
|
||||
self.node()?.qr_payload().map_err(WireError::new)
|
||||
}
|
||||
|
||||
/// Roster, sorted by petname then fingerprint.
|
||||
pub async fn friends(&self) -> WResult<Vec<FriendInfo>> {
|
||||
let list = self.inner.list_friends().map_err(WireError::new)?;
|
||||
let list = self.node()?.list_friends().map_err(WireError::new)?;
|
||||
Ok(list
|
||||
.into_iter()
|
||||
.map(|f| FriendInfo {
|
||||
|
|
@ -168,9 +306,10 @@ impl Wire {
|
|||
/// Add a friend from an invite, or update the locator if the key is known.
|
||||
/// Same `k` never creates a second row.
|
||||
pub async fn add_friend(&self, invite: String) -> WResult<FriendInfo> {
|
||||
self.inner.add_friend_from_qr(&invite).map_err(WireError::new)?;
|
||||
let node = self.node()?;
|
||||
node.add_friend_from_qr(&invite).map_err(WireError::new)?;
|
||||
let p = qr::decode(&invite).map_err(WireError::new)?;
|
||||
let f = self.inner.friend(&p.pubkey).map_err(WireError::new)?;
|
||||
let f = node.friend(&p.pubkey).map_err(WireError::new)?;
|
||||
Ok(FriendInfo {
|
||||
pubkey_hex: hex(&f.pubkey),
|
||||
fingerprint: f.fingerprint,
|
||||
|
|
@ -183,26 +322,32 @@ impl Wire {
|
|||
/// Local label. Pass `None` to clear. Never goes on the wire.
|
||||
pub async fn set_petname(&self, pubkey_hex: String, petname: Option<String>) -> WResult<()> {
|
||||
let pk = unhex(&pubkey_hex)?;
|
||||
self.inner
|
||||
self.node()?
|
||||
.set_petname(&pk, petname.as_deref())
|
||||
.map_err(WireError::new)
|
||||
}
|
||||
|
||||
/// Send one message. Fail closed: if the peer's onion is down, this errors
|
||||
/// after retrying. There is no outbox in v1 — no silent spooling.
|
||||
/// Send one message. Returns once the outcome is known: delivered now, or
|
||||
/// queued for retry because the peer's onion is unreachable. A protocol
|
||||
/// error (bad signature, bad frame) still fails immediately and is never
|
||||
/// queued. Use [`flush`](Self::flush) to retry the queue on demand.
|
||||
pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> {
|
||||
let pk = unhex(&pubkey_hex)?;
|
||||
self.inner
|
||||
self.node()?
|
||||
.send(&pk, body.as_bytes())
|
||||
.await
|
||||
.map_err(WireError::new)
|
||||
.map_err(WireError::new)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Chat history for a friend, oldest first. Bodies are decrypted here;
|
||||
/// they are stored encrypted at rest.
|
||||
pub async fn messages(&self, pubkey_hex: String) -> WResult<Vec<ChatMessage>> {
|
||||
let pk = unhex(&pubkey_hex)?;
|
||||
let rows = self.inner.list_messages(&pk).map_err(WireError::new)?;
|
||||
let rows = self
|
||||
.node()?
|
||||
.list_messages(&pk)
|
||||
.map_err(WireError::new)?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|m| ChatMessage {
|
||||
|
|
@ -214,7 +359,7 @@ impl Wire {
|
|||
|
||||
/// Delete every message body. Identity and friends survive.
|
||||
pub async fn wipe_messages(&self) -> WResult<()> {
|
||||
self.inner.wipe_messages().map_err(WireError::new)
|
||||
self.node()?.wipe_messages().map_err(WireError::new)
|
||||
}
|
||||
|
||||
/// Publish a NEW onion service and hard-cut the old one, then push a signed
|
||||
|
|
@ -224,7 +369,7 @@ impl Wire {
|
|||
/// you until they rescan your invite — that is the documented v1 behaviour,
|
||||
/// not a bug. Confirm with a typed phrase in the UI; never one tap.
|
||||
pub async fn rotate_onion(&self) -> WResult<RotateOutcome> {
|
||||
let r = self.inner.rotate().await.map_err(WireError::new)?;
|
||||
let r = self.node()?.rotate().await.map_err(WireError::new)?;
|
||||
Ok(RotateOutcome {
|
||||
notified: r.notified as u32,
|
||||
friends: r.friends as u32,
|
||||
|
|
@ -237,6 +382,14 @@ impl Wire {
|
|||
}
|
||||
}
|
||||
|
||||
fn from_core_flush(o: CoreFlushOutcome) -> FlushOutcome {
|
||||
FlushOutcome {
|
||||
attempted: o.attempted as u32,
|
||||
delivered: o.delivered as u32,
|
||||
remaining: o.remaining as u32,
|
||||
}
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
let mut s = String::with_capacity(bytes.len() * 2);
|
||||
for b in bytes {
|
||||
|
|
@ -256,3 +409,72 @@ fn unhex(s: &str) -> WResult<Vec<u8>> {
|
|||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
//! No Tor here on purpose: these exercise the *lifecycle* contract of the
|
||||
//! handle, which is what a shut-down node must guarantee. A `Wire` with no
|
||||
//! node is exactly the state `shutdown()` leaves behind.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn stopped_wire() -> Wire {
|
||||
Wire {
|
||||
node: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn block_on<F: std::future::Future>(f: F) -> F::Output {
|
||||
// No `macros` feature on tokio in this crate, so build the runtime.
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.build()
|
||||
.expect("runtime")
|
||||
.block_on(f)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tor_state_of_a_stopped_handle_is_stopped() {
|
||||
assert_eq!(stopped_wire().tor_state(), TorState::Stopped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calls_after_shutdown_are_typed_errors_not_panics() {
|
||||
let wire = stopped_wire();
|
||||
|
||||
let err = block_on(wire.flush()).expect_err("flush after shutdown must fail");
|
||||
assert!(
|
||||
matches!(err, WireError::Stopped { .. }),
|
||||
"flush returned {err:?}, want WireError::Stopped"
|
||||
);
|
||||
|
||||
let err = block_on(wire.send("00".repeat(32), "hi".to_string()))
|
||||
.expect_err("send after shutdown must fail");
|
||||
assert!(
|
||||
matches!(err, WireError::Stopped { .. }),
|
||||
"send returned {err:?}, want WireError::Stopped"
|
||||
);
|
||||
|
||||
let err = block_on(wire.friends()).expect_err("friends after shutdown must fail");
|
||||
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
|
||||
|
||||
let err = block_on(wire.shutdown()).expect_err("second shutdown must not re-run");
|
||||
assert!(
|
||||
matches!(err, WireError::Stopped { .. }),
|
||||
"second shutdown returned {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tor_state_maps_every_core_state() {
|
||||
assert_eq!(
|
||||
TorState::from(CoreTorState::Bootstrapping),
|
||||
TorState::Bootstrapping
|
||||
);
|
||||
assert_eq!(TorState::from(CoreTorState::Published), TorState::Published);
|
||||
assert_eq!(
|
||||
TorState::from(CoreTorState::DegradedReachable),
|
||||
TorState::DegradedReachable
|
||||
);
|
||||
assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue