feat(sdk): explicit Tor lifecycle — Wire.shutdown / flush / torState + observable state #49
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/tor-lifecycle"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
What
The UniFFI SDK had no lifecycle:
Wirewas a bare handle over aNodewith nostop, no flush, and 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 shutdown strategy.
This PR adds the missing verbs, end to end:
Wire)shutdown()Wire)flush(): FlushOutcomeattempted/delivered/remaining.Wire)torState(): TorStateTorStateBOOTSTRAPPING,PUBLISHED,DEGRADED_REACHABLE,STOPPED.Node)Node::shutdown(),Node::flush() -> FlushOutcome,Node::tor_state() -> TorStatehs)TorState,tor_state_of(State, stopped, reachable)Errors stay typed:
WireErrorgains a second flat variantStopped { message }(
WireException.Stoppedin Kotlin), so "you must unlock again" is a distinct UIstate from
Failed(network/protocol). Nounwrap()on a poisoned mutexanywhere — a poisoned handle reports
Stopped, which is the correct recoveryanyway (unlock again).
Kotlin signatures (generated)
Exact teardown contract (child cards:
t_5bf32cd3,t_f46a9863)Node::shutdown()is idempotent: a second call returnsOk(()).Wire.shutdown()is safe to call twice, but the second call returns the typedWireException.Stopped— the handle is spent, and a silentOkwould hide adouble-teardown bug. Treat
Stoppedas success.Wire(includingsend) throwsWireException.Stopped.Wire.torState()returnsSTOPPED(it does not throw).flush()on a spent handle throwsWireException.Stopped.Before / after on Android
Before:
WireViewModel.lock()setwire = nullandPhase.Locked, andonCleared()did not exist. Dropping the Kotlin reference did not stopanything — Arti kept its client and the hosted v3 onion service alive, the
outbox worker kept dialing peers, and the sqlite connection stayed open until the
JVM collector got around to the JNI handle. Nothing told the network the node was
gone; the onion service simply answered until the process died.
After:
lock()andonCleared()both go throughstopNode(Wire):flush()— one last bounded drain, so a queued message gets its chancebefore the process may lose its socket.
shutdown()— drain again (10s budget), drop the onion service (rendezvoustask aborted), abort the outbox retry worker (
WorkerHandlenow lives in aMutex<Option<…>>so it can be aborted, not just dropped at the end ofNode), checkpoint the sqlite WAL, and take the node handle out of theWire.Dropping the handle is what releases the last
Arcto the Tor client and thestore, so Arti's runtime and the sqlite connection actually go away when the UI
does. Both steps run on a process-scoped
TEARDOWNscope becauseonCleared()runs after
viewModelScopeis cancelled.unlock()joins that teardownbefore opening again — the old node holds the sqlite file and Arti's state lock
until
shutdown()returns, and racing it made the next open fail.A process killed outright never runs any of this. That is exactly why the
outbox lives in sqlite (parent card) and why
flush()exists.Why the WAL checkpoint is a second connection
Storeowns itsConnectionand does not lend it out, andsrc/store.rsisexplicitly out of this card's scope. A checkpoint is a property of the
database, not of one connection, so
checkpoint_wal()opens a short-livedsecond connection to
onionwire.dband runsPRAGMA wal_checkpoint(TRUNCATE).It needs no passphrase (it moves committed pages; it does not decrypt them), it
is best-effort (a failure is logged, never fatal — WAL replay on open recovers
anything committed), and it is covered by an offline test against a real WAL:
src/node.rs::lifecycle_tests::checkpoint_wal_truncates_a_live_wal.⚠️ Forward-looking caveat — SQLCipher (#43/PR merged on
mainbefore thisbranch's base): on an encrypted store the key lives only inside
Store, so asecond plain connection cannot read the file at all. The helper detects that
(
SQLITE_NOTADB→ "store is SQLCipher-encrypted — skipped") instead ofreporting a bogus error, and nothing is lost — sqlite folds the WAL into the db
when the last connection closes — but the explicit truncation has to move inside
Storeto happen there. Follow-up card t_65c73d5a filed for the store owner(
Store::checkpoint_wal()), rather than reaching into a file this card forbids.Base branch
Rebased onto
main@c39259b(the parent outbox PR #45 is merged, andthis branch now carries the keystore
WireViewModelfrommain, not the olderone). Diff against
mainis exactly 6 files / 834 insertions:Child cards stack here:
t_5bf32cd3(foreground service) andt_f46a9863(Android outbox UI — it wants
Wire.flush()/FlushOutcome).The bug the live test caught (read this one)
The first
tor_state()implementation projected Arti's raw combined status.tests/tor_lifecycle.rs— run for real against the Tor network, not just--ignored— failed with:Two distinct reasons, both device-visible:
wait_until_publishedaccepts either a ready status or a successfulprobe of our own onion — that mismatch is the whole reason the 360s publish
wait exists. Arti's combined status can sit at
Bootstrappingfor minutesafter the descriptor is already downloadable, so a node friends could reach
reported "still starting".
Shutdownbefore its publish reactorstarts (visible in the log:
Shutdownfor ~4s, thenBootstrapping, thenprobe ok). Projecting that toStoppedwould make every unlock brieflylook like a dead node — the worst possible answer from a lifecycle API.
Fix:
Nodekeeps anonion_reachableflag (AtomicBool) set when the publishbar is crossed in
start/rotateand cleared whenrotatehard-cuts the oldservice.
tor_state_of(state, stopped, reachable)then mirrorshs_is_readyexactly:
Running→Published,DegradedReachable→DegradedReachable,Broken/Shutdownon a live node →Bootstrapping(transient, not terminal),Bootstrapping/DegradedUnreachable+ reachable →Published, and only theexplicit stop flag (or a stopped service) yields
Stopped. Covered bytests/hs.rs::reachable_statuses_report_published_while_arti_says_bootstrappingand
tor_state_maps_every_arti_status.Verification (real output, head
48c06df, rebased ontomain@c39259b)Artifact (throwaway debug build, but it proves the toolchain and the regenerated
bindings):
Generated Kotlin surface actually compiled into the AAR
(
android/sdk/build/generated/uniffi/uniffi/onionwire_sdk/onionwire_sdk.kt):CI: green on
48c06df2cff7a265cce2dcabdd33d878b9857f41—https://forgejo.siriusdevops.com/sirius/onionwire/actions/runs/174 (
ci / test,pull_request,
cargo test --locked+cargo clippy --locked --all-targets -- -D warningsinside the rust container on the arm64 Pi runner).Tests
Offline (runs in CI /
cargo test):tests/hs.rs—tor_state_maps_every_arti_status,stopped_outranks_whatever_arti_reports,ready_states_are_the_published_ones.src/node.rs—checkpoint_wal_truncates_a_live_wal,checkpoint_wal_is_a_no_op_without_a_database.crates/onionwire-sdk/src/lib.rs—tor_state_of_a_stopped_handle_is_stopped,calls_after_shutdown_are_typed_errors_not_panics,tor_state_maps_every_core_state.Live Tor (
#[ignore], same convention astests/tor_hs.rs):tests/tor_lifecycle.rs— starts a node, assertsPublished, flushes an emptyoutbox, shuts down, asserts
Stopped, asserts the secondshutdown()and apost-shutdown
flush()/send()/rotate()all return errors instead ofpanicking.
Naming decisions (as requested)
Wire.shutdown()/Node::shutdown()— notstop()/close(): it is alifecycle transition, and
Stoppedis already the terminal state name.Wire.flush()/Node::flush()— same word the TUI/card uses; returnsFlushOutcome { attempted, delivered, remaining }.Wire.tor_state()/Node::tor_state()— sync, read-only, no I/O.Not in this PR
README.mdwording is deferred (PR #38 owns the file) — see below.crates/onionwire-sdk/README.mdstill says "No outbox, no spool in v1" andits "Locked protocol facts" table predates the outbox. Both are outside this
card's allowed files; suggesting it here rather than silently editing.
src/tui.rs/docs/TUI.md(PR #27) untouched.crates/onionwire-sdkdid not compile on thebase —
Node::sendreturnsResult<OutboxStatus, String>after #45 whilethe SDK still mapped it to
Result<(), String>, socargo build --release --libfailed with E0308. CI's path allowlist excludescrates/**from theRust job, which is why #45's
cargo testrun stayed green. Fixed here.README (deferred)
Exact wording to apply to
README.mdafter #38 lands — a lifecycle paragraphfor the Android/SDK section:
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.3d41ffceb3b053bed702b053bed70248c06df2cfqueued (try 3/8, retry 45s)from the SDK outbox rows #59queued (try 3/8, retry 45s)from the SDK outbox rows #59