Make joining a network idempotent and shut down cleanly on every path
Running `tsunagi up` twice with the same arguments failed with "network ... is already active", and then dropped the iroh endpoint without closing it. A configured network is activated automatically at startup, so the second run found it already up. `join_network` is declarative — "be a member of this network" — so joining one that is already active now succeeds and changes nothing. `activate_network` stays strict for callers that specifically want to know whether an inactive network was started. The CLI now closes the agent on the error path too, and handles SIGTERM as well as Ctrl-C, so a service manager stopping the agent gets the same clean shutdown an interactive user does. Also documents the two lookups people conflate: resolving one endpoint's address is iroh's public pkarr/DNS service and works today, which is why `--peer <endpoint-id>` needs no address; finding who is in a network is this project's `NetworkDiscovery` and is still static bootstrap only. Notes in the README and the threat model that `n0` and `direct` publish this endpoint's addresses to a public third-party service. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
+16
-3
@@ -242,10 +242,17 @@ impl Agent {
|
||||
self.inner.events.subscribe()
|
||||
}
|
||||
|
||||
/// Adds a network to the persistent configuration and activates it.
|
||||
/// Makes this agent a member of a network, activating it.
|
||||
///
|
||||
/// The same `(name, secret)` always produces the same [`NetworkId`], on
|
||||
/// every device.
|
||||
///
|
||||
/// This is declarative and therefore **idempotent**: joining a network
|
||||
/// that is already active succeeds and changes nothing. That matters
|
||||
/// because a configured network is activated automatically at startup, so
|
||||
/// running the same command twice must not be an error. Use
|
||||
/// [`Agent::activate_network`] when you specifically want to know whether
|
||||
/// an inactive network was started.
|
||||
pub async fn join_network(
|
||||
&self,
|
||||
name: &NetworkName,
|
||||
@@ -257,11 +264,17 @@ impl Agent {
|
||||
.storage
|
||||
.upsert_network(network_id, name.clone(), secret.clone(), true)
|
||||
.await?;
|
||||
self.activate_with_keys(keys).await?;
|
||||
Ok(network_id)
|
||||
match self.activate_with_keys(keys).await {
|
||||
// Already a member of exactly this network space: nothing to do.
|
||||
Ok(()) | Err(Error::NetworkAlreadyActive(_)) => Ok(network_id),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
/// Activates a configured network that is currently inactive.
|
||||
///
|
||||
/// Fails with [`Error::NetworkAlreadyActive`] if it is already running.
|
||||
/// [`Agent::join_network`] is the forgiving version.
|
||||
pub async fn activate_network(&self, network_id: NetworkId) -> Result<()> {
|
||||
let stored = self
|
||||
.inner
|
||||
|
||||
+45
-8
@@ -71,13 +71,17 @@ impl PathArgs {
|
||||
}
|
||||
|
||||
/// How much external connectivity machinery the endpoint may use.
|
||||
///
|
||||
/// `direct` and `n0` publish this endpoint's addresses, keyed by its endpoint
|
||||
/// id, to Number 0's public lookup service, and resolve peers through it.
|
||||
/// That is what makes `--peer <endpoint-id>` work without an address.
|
||||
#[derive(Debug, Clone, Copy, ValueEnum)]
|
||||
enum Transport {
|
||||
/// Loopback and the local network only. No relays, no address lookup.
|
||||
/// Loopback and the local network only. Publishes nothing.
|
||||
Local,
|
||||
/// Public address lookup, but no relays.
|
||||
Direct,
|
||||
/// iroh's defaults: address lookup plus the public n0 relays.
|
||||
/// iroh's defaults: public address lookup plus the public n0 relays.
|
||||
N0,
|
||||
}
|
||||
|
||||
@@ -378,8 +382,16 @@ async fn up(args: UpArgs) -> Result<(), Box<dyn std::error::Error>> {
|
||||
};
|
||||
|
||||
let agent = Agent::spawn(config).await?;
|
||||
// From here on every exit goes through `agent.shutdown()`, so the endpoint
|
||||
// is never dropped without being closed.
|
||||
let mut events = agent.subscribe();
|
||||
let network = agent.join_network(&name, &secret).await?;
|
||||
let network = match agent.join_network(&name, &secret).await {
|
||||
Ok(network) => network,
|
||||
Err(err) => {
|
||||
agent.shutdown().await;
|
||||
return Err(err.into());
|
||||
}
|
||||
};
|
||||
|
||||
println!("tsunagi is up");
|
||||
println!(" endpoint id {}", agent.endpoint_id());
|
||||
@@ -401,11 +413,8 @@ async fn up(args: UpArgs) -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
signal = tokio::signal::ctrl_c() => {
|
||||
if let Err(err) = signal {
|
||||
eprintln!("cannot listen for Ctrl-C: {err}");
|
||||
}
|
||||
println!("\nstopping...");
|
||||
reason = stop_signal() => {
|
||||
println!("\nstopping ({reason})...");
|
||||
break;
|
||||
}
|
||||
event = events.recv() => match event {
|
||||
@@ -431,6 +440,34 @@ async fn up(args: UpArgs) -> Result<(), Box<dyn std::error::Error>> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolves when the process is asked to stop.
|
||||
///
|
||||
/// Both Ctrl-C and `SIGTERM` are handled, so a service manager stopping the
|
||||
/// agent gets the same clean shutdown an interactive user does.
|
||||
async fn stop_signal() -> &'static str {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
let mut terminate = match signal(SignalKind::terminate()) {
|
||||
Ok(stream) => stream,
|
||||
Err(err) => {
|
||||
eprintln!("cannot listen for SIGTERM: {err}");
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
return "interrupted";
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => "interrupted",
|
||||
_ = terminate.recv() => "terminated",
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
"interrupted"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "tun-device")]
|
||||
fn system_tun_factory() -> Result<Arc<dyn TunFactory>, Box<dyn std::error::Error>> {
|
||||
use tsunagi::dataplane::wireguard::SystemTunFactory;
|
||||
|
||||
+9
-6
@@ -8,14 +8,17 @@
|
||||
//! A discovery backend must not carry control messages between agents, must not
|
||||
//! confirm authentication and must not mutate agent state directly.
|
||||
//!
|
||||
//! Two concerns are kept apart:
|
||||
//! Two concerns are kept apart, and only the first one is this module's:
|
||||
//!
|
||||
//! * *Finding members of a network* — [`NetworkDiscovery::resolve`], keyed by
|
||||
//! the secret-derived [`DiscoveryKey`].
|
||||
//! * *Resolving the address of one iroh endpoint* — an
|
||||
//! [`iroh::EndpointAddr`] either already carries addresses, or iroh's own
|
||||
//! address lookup service must be enabled. Dialling a bare [`EndpointId`]
|
||||
//! with neither is expected to fail.
|
||||
//! the secret-derived [`DiscoveryKey`]. That is what lives here, and today
|
||||
//! it is [`StaticBootstrap`] plus a test backend; a DHT backend is future
|
||||
//! work.
|
||||
//! * *Resolving the address of one iroh endpoint* — **iroh's job, not ours**.
|
||||
//! With [`crate::config::TransportPolicy::N0Defaults`] or `DirectOnly`, iroh
|
||||
//! publishes and resolves endpoint addresses through Number 0's public
|
||||
//! service, so dialling a bare [`EndpointId`] works. With `LocalOnly` there
|
||||
//! is no lookup, and a candidate must carry addresses of its own.
|
||||
//!
|
||||
//! No empty result ever proves a network is empty. It only means "nobody found
|
||||
//! yet".
|
||||
|
||||
Reference in New Issue
Block a user