mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-27 13:52:16 +00:00
tools: rnstatus reuses its monitor link and rncp shows the physical rate
This commit is contained in:
1 parent
3eec4e0995
commit
b24d70537d
7 files changed
+283
-85
No files matched your search
@@ -1003,6 +1003,7 @@ impl LinkSessionChannelHandle {
|
||||
pub struct LinkSessionHandle {
|
||||
link_id: [u8; 16],
|
||||
mdu: usize,
|
||||
rtt: f64,
|
||||
command_tx: mpsc::Sender<LinkSessionCommand>,
|
||||
phy_stats_rx: watch::Receiver<LinkPhyStats>,
|
||||
}
|
||||
@@ -1016,6 +1017,11 @@ impl LinkSessionHandle {
|
||||
self.mdu
|
||||
}
|
||||
|
||||
/// Round-trip time in seconds measured when the link proof arrived.
|
||||
pub fn rtt(&self) -> f64 {
|
||||
self.rtt
|
||||
}
|
||||
|
||||
/// Latest physical-layer measurements observed for this Link.
|
||||
///
|
||||
/// Values remain empty unless tracking was enabled when the session was
|
||||
@@ -1337,6 +1343,7 @@ impl LinkSession {
|
||||
let handle = LinkSessionHandle {
|
||||
link_id,
|
||||
mdu: link.mdu,
|
||||
rtt: link.rtt_secs(),
|
||||
command_tx: command_tx.clone(),
|
||||
phy_stats_rx,
|
||||
};
|
||||
@@ -5830,6 +5837,7 @@ mod tests {
|
||||
let handle = LinkSessionHandle {
|
||||
link_id,
|
||||
mdu,
|
||||
rtt: 0.0,
|
||||
command_tx: command_tx.clone(),
|
||||
phy_stats_rx,
|
||||
};
|
||||
|
||||
@@ -130,11 +130,20 @@ pub struct RncpSendRequest<'a> {
|
||||
/// ends at the later of this and the link establishment timeout; the
|
||||
/// transfer itself has no deadline.
|
||||
pub path_timeout: Duration,
|
||||
pub progress_tx: Option<mpsc::Sender<f32>>,
|
||||
pub progress_tx: Option<mpsc::Sender<RncpProgress>>,
|
||||
/// Stops the transfer and closes the link, as rncp does on SIGINT.
|
||||
pub shutdown: Option<ShutdownSignal>,
|
||||
}
|
||||
|
||||
/// One transfer progress update: the logical fraction, and the bytes of the
|
||||
/// current segment moved on the link, `get_segment_progress() *
|
||||
/// get_transfer_size()` as rncp's `-P` rate reads them (rncp.py:330-331).
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RncpProgress {
|
||||
pub progress: f32,
|
||||
pub phy_bytes: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum RncpEvent {
|
||||
LinkEstablished {
|
||||
@@ -765,7 +774,7 @@ async fn send_segments(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
rl: &mut RncpLink,
|
||||
mut prepared: PreparedResourceSource,
|
||||
progress_tx: Option<mpsc::Sender<f32>>,
|
||||
progress_tx: Option<mpsc::Sender<RncpProgress>>,
|
||||
) -> Result<usize, RncpError> {
|
||||
let keys = rl
|
||||
.link
|
||||
@@ -1060,7 +1069,7 @@ struct OutboundDrive<'a> {
|
||||
endpoint_lifecycle_rx: &'a mut mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>,
|
||||
attached_interface: InterfaceId,
|
||||
interface_owner: Option<rns_transport::messages::InterfaceOwnerId>,
|
||||
progress_tx: Option<mpsc::Sender<f32>>,
|
||||
progress_tx: Option<mpsc::Sender<RncpProgress>>,
|
||||
progress_base: f32,
|
||||
progress_span: f32,
|
||||
}
|
||||
@@ -1083,10 +1092,13 @@ async fn drive_outbound(request: OutboundDrive<'_>) -> Result<(), RncpError> {
|
||||
transfer.advertisement_mdu = link.mdu;
|
||||
let total = transfer.resource.parts.len();
|
||||
if let Some(ref tx) = progress_tx {
|
||||
let _ = tx.try_send(if total == 0 {
|
||||
progress_base + progress_span
|
||||
} else {
|
||||
progress_base
|
||||
let _ = tx.try_send(RncpProgress {
|
||||
progress: if total == 0 {
|
||||
progress_base + progress_span
|
||||
} else {
|
||||
progress_base
|
||||
},
|
||||
phy_bytes: 0.0,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1159,7 +1171,10 @@ async fn drive_outbound(request: OutboundDrive<'_>) -> Result<(), RncpError> {
|
||||
} else {
|
||||
confirmed_count as f32 / total as f32
|
||||
};
|
||||
let _ = tx.try_send(progress_base + (progress_span * frac));
|
||||
let _ = tx.try_send(RncpProgress {
|
||||
progress: progress_base + (progress_span * frac),
|
||||
phy_bytes: transfer.progress() * transfer.resource.total_size as f64,
|
||||
});
|
||||
}
|
||||
}
|
||||
rns_wire::context::PacketContext::ResourcePrf => {
|
||||
@@ -1171,7 +1186,10 @@ async fn drive_outbound(request: OutboundDrive<'_>) -> Result<(), RncpError> {
|
||||
return Err(RncpError::ResourceFailed("proof mismatch".into()));
|
||||
}
|
||||
if let Some(ref tx) = progress_tx {
|
||||
let _ = tx.try_send(progress_base + progress_span);
|
||||
let _ = tx.try_send(RncpProgress {
|
||||
progress: progress_base + progress_span,
|
||||
phy_bytes: transfer.resource.total_size as f64,
|
||||
});
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
@@ -1457,7 +1475,7 @@ pub struct RncpFetchRequest<'a> {
|
||||
/// ends at the later of this and the link establishment timeout; the
|
||||
/// request uses the Link's default timeout and the transfer has no deadline.
|
||||
pub path_timeout: Duration,
|
||||
pub progress_tx: Option<mpsc::Sender<f32>>,
|
||||
pub progress_tx: Option<mpsc::Sender<RncpProgress>>,
|
||||
/// Stops the fetch and closes the link, as rncp does on SIGINT.
|
||||
pub shutdown: Option<ShutdownSignal>,
|
||||
}
|
||||
@@ -1535,6 +1553,7 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
|
||||
let link_rtt = link.rtt.unwrap_or(Duration::from_millis(500));
|
||||
let mut ack_seen = false;
|
||||
let mut last_phy_bytes = 0.0_f64;
|
||||
let mut transfers: std::collections::HashMap<[u8; 32], InboundTransfer> =
|
||||
std::collections::HashMap::new();
|
||||
let mut split_resources: std::collections::HashMap<[u8; 32], MultiSegmentInbound> =
|
||||
@@ -1721,8 +1740,12 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
let mut completed_rh = None;
|
||||
for (rh, t) in &mut transfers {
|
||||
let action = t.receive_part(body.to_vec());
|
||||
last_phy_bytes = t.resource.progress() * t.resource.total_size as f64;
|
||||
if let Some(ref tx) = progress_tx {
|
||||
let _ = tx.try_send(t.resource.progress() as f32);
|
||||
let _ = tx.try_send(RncpProgress {
|
||||
progress: t.resource.progress() as f32,
|
||||
phy_bytes: last_phy_bytes,
|
||||
});
|
||||
}
|
||||
match action {
|
||||
TransferAction::SendHmu(_) | TransferAction::SendRequest(_) => {
|
||||
@@ -1807,7 +1830,10 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
}
|
||||
if !coord.is_complete() {
|
||||
if let Some(ref tx) = progress_tx {
|
||||
let _ = tx.try_send(coord.progress() as f32);
|
||||
let _ = tx.try_send(RncpProgress {
|
||||
progress: coord.progress() as f32,
|
||||
phy_bytes: last_phy_bytes,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -1828,7 +1854,10 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
};
|
||||
split_resources.remove(&original_hash);
|
||||
if let Some(ref tx) = progress_tx {
|
||||
let _ = tx.try_send(1.0);
|
||||
let _ = tx.try_send(RncpProgress {
|
||||
progress: 1.0,
|
||||
phy_bytes: last_phy_bytes,
|
||||
});
|
||||
}
|
||||
break Ok((file_name, payload));
|
||||
}
|
||||
@@ -1837,7 +1866,10 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
break Err(RncpError::ResourceFailed("invalid data received".into()));
|
||||
};
|
||||
if let Some(ref tx) = progress_tx {
|
||||
let _ = tx.try_send(1.0);
|
||||
let _ = tx.try_send(RncpProgress {
|
||||
progress: 1.0,
|
||||
phy_bytes: last_phy_bytes,
|
||||
});
|
||||
}
|
||||
break Ok((file_name, payload));
|
||||
}
|
||||
|
||||
@@ -42,7 +42,8 @@ use rns_runtime::platform::StoragePaths;
|
||||
use rns_runtime::reticulum::ReticulumHandle;
|
||||
use rns_runtime::rncp::{
|
||||
DEFAULT_RNCP_APP_NAME, RncpError, RncpEvent, RncpFetchRequest, RncpListenerConfig,
|
||||
RncpSendRequest, default_rncp_app_name, rncp_fetch_file, rncp_send_file, spawn_rncp_listener,
|
||||
RncpProgress, RncpSendRequest, default_rncp_app_name, rncp_fetch_file, rncp_send_file,
|
||||
spawn_rncp_listener,
|
||||
};
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: f64 = 15.0;
|
||||
@@ -291,28 +292,36 @@ struct UiState {
|
||||
total_size: Option<f64>,
|
||||
started: Option<Instant>,
|
||||
progress: f64,
|
||||
stats: VecDeque<(Instant, f64)>,
|
||||
stats: VecDeque<(Instant, f64, f64)>,
|
||||
speed: f64,
|
||||
/// `-P`: append the physical-layer rate to the progress line.
|
||||
phy_rates: bool,
|
||||
phy_speed: f64,
|
||||
}
|
||||
|
||||
impl UiState {
|
||||
/// rncp.py:323-356 (`sender_progress`): speed over the last 32 updates.
|
||||
fn update(&mut self, progress: f64) {
|
||||
fn update(&mut self, progress: f64, phy_got: f64) {
|
||||
let now = Instant::now();
|
||||
self.started.get_or_insert(now);
|
||||
self.progress = progress;
|
||||
let got = progress * self.total_size.unwrap_or(0.0);
|
||||
self.stats.push_back((now, got));
|
||||
self.stats.push_back((now, got, phy_got));
|
||||
while self.stats.len() > 32 {
|
||||
self.stats.pop_front();
|
||||
}
|
||||
let (first_at, first_got) = self.stats[0];
|
||||
let (first_at, first_got, first_phy) = self.stats[0];
|
||||
let span = now.duration_since(first_at).as_secs_f64();
|
||||
self.speed = if span == 0.0 {
|
||||
0.0
|
||||
if span == 0.0 {
|
||||
self.speed = 0.0;
|
||||
self.phy_speed = 0.0;
|
||||
} else {
|
||||
(got - first_got) / span
|
||||
};
|
||||
self.speed = (got - first_got) / span;
|
||||
// Segment progress restarts per segment, so only a gain moves the rate.
|
||||
if phy_got - first_phy > 0.0 {
|
||||
self.phy_speed = (phy_got - first_phy) / span;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn stat_str(&self, elapsed: Option<f64>) -> String {
|
||||
@@ -323,9 +332,18 @@ impl UiState {
|
||||
let cs = size_str((self.progress * total).trunc(), 'B');
|
||||
let ts = size_str(total, 'B');
|
||||
let ss = size_str(self.speed, 'b');
|
||||
// rncp.py:577-579, 753-755.
|
||||
let phy_str = if self.phy_rates {
|
||||
format!(" ({}ps at physical layer)", size_str(self.phy_speed, 'b'))
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
match elapsed {
|
||||
Some(dt) => format!("{percent}% - {cs} of {ts} in {} - {ss}ps", prettytime(dt)),
|
||||
None => format!("{percent}% - {cs} of {ts} - {ss}ps"),
|
||||
Some(dt) => format!(
|
||||
"{percent}% - {cs} of {ts} in {} - {ss}ps{phy_str}",
|
||||
prettytime(dt)
|
||||
),
|
||||
None => format!("{percent}% - {cs} of {ts} - {ss}ps{phy_str}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -352,6 +370,8 @@ impl Ui {
|
||||
progress: 0.0,
|
||||
stats: VecDeque::new(),
|
||||
speed: 0.0,
|
||||
phy_rates: false,
|
||||
phy_speed: 0.0,
|
||||
})),
|
||||
};
|
||||
if !silent {
|
||||
@@ -425,8 +445,13 @@ impl Ui {
|
||||
self.lock().total_size = Some(total);
|
||||
}
|
||||
|
||||
fn progress(&self, progress: f32) {
|
||||
self.lock().update(f64::from(progress));
|
||||
fn progress(&self, update: RncpProgress) {
|
||||
self.lock()
|
||||
.update(f64::from(update.progress), update.phy_bytes);
|
||||
}
|
||||
|
||||
fn show_phy_rates(&self, on: bool) {
|
||||
self.lock().phy_rates = on;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -446,11 +471,6 @@ pub(crate) async fn main() {
|
||||
true,
|
||||
std::io::stderr,
|
||||
);
|
||||
if args.phy_rates {
|
||||
tracing::debug!(
|
||||
"Physical layer rates are not available, -P adds nothing to the progress line"
|
||||
);
|
||||
}
|
||||
|
||||
// rncp.py:824-880.
|
||||
let positionals = args.file.is_some() && args.destination.is_some();
|
||||
@@ -564,6 +584,7 @@ async fn run_fetch(args: Args) -> ! {
|
||||
prepare_identity(&handle, args.identity_path.as_deref(), &paths.identity_dir).await;
|
||||
|
||||
let ui = Ui::new(args.silent, true);
|
||||
ui.show_phy_rates(args.phy_rates);
|
||||
let h = pretty_hex_rep(&dest_hash);
|
||||
let link_wait = wait_for_path(&handle, dest_hash, args.timeout, &ui, &interrupt, " ").await;
|
||||
|
||||
@@ -584,7 +605,7 @@ async fn run_fetch(args: Args) -> ! {
|
||||
}
|
||||
};
|
||||
|
||||
let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel::<f32>(32);
|
||||
let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel::<RncpProgress>(32);
|
||||
let progress_task = {
|
||||
let ui = ui.clone();
|
||||
let show_requesting = show_requesting.clone();
|
||||
@@ -746,6 +767,7 @@ async fn run_send(args: Args) -> ! {
|
||||
prepare_identity(&handle, args.identity_path.as_deref(), &paths.identity_dir).await;
|
||||
|
||||
let ui = Ui::new(args.silent, false);
|
||||
ui.show_phy_rates(args.phy_rates);
|
||||
let h = pretty_hex_rep(&dest_hash);
|
||||
let link_wait = wait_for_path(&handle, dest_hash, args.timeout, &ui, &interrupt, " ").await;
|
||||
|
||||
@@ -778,7 +800,7 @@ async fn run_send(args: Args) -> ! {
|
||||
}
|
||||
}
|
||||
};
|
||||
let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel::<f32>(32);
|
||||
let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel::<RncpProgress>(32);
|
||||
let progress_task = {
|
||||
let ui = ui.clone();
|
||||
let show_transferring = show_transferring.clone();
|
||||
@@ -824,6 +846,8 @@ async fn run_send(args: Args) -> ! {
|
||||
let mut st = ui.lock();
|
||||
st.tick = Tick::Off;
|
||||
st.progress = 1.0;
|
||||
// The send's final line drops the physical rate once the resource is done (rncp.py:753).
|
||||
st.phy_rates = false;
|
||||
let total = st.total_size.unwrap_or(0.0);
|
||||
let dt = st.started.map(|t| t.elapsed().as_secs_f64()).unwrap_or(0.0);
|
||||
st.speed = if dt > 0.0 { total / dt } else { 0.0 };
|
||||
|
||||
@@ -1176,16 +1176,7 @@ async fn remote_query(
|
||||
// Upstream's link-closed callback prints, but its exit() runs off the
|
||||
// main thread, so the pending request still fails (rnpath.py:61-76).
|
||||
Err(LinkClientError::RequestFailed(RequestFailure::LinkClosed(reason))) => {
|
||||
use rns_runtime::prelude::CloseReason;
|
||||
let text = match reason {
|
||||
Some(CloseReason::InitiatorClosed) => None,
|
||||
Some(CloseReason::Timeout) => Some("The link timed out, exiting now"),
|
||||
Some(CloseReason::DestinationClosed) => {
|
||||
Some("The link was closed by the server, exiting now")
|
||||
}
|
||||
_ => Some("Link closed unexpectedly, exiting now"),
|
||||
};
|
||||
if let Some(text) = text {
|
||||
if let Some(text) = rns_tools::link_closed_text(reason) {
|
||||
println!("{OUTPUT_RST}{text}");
|
||||
}
|
||||
Ok(Vec::new())
|
||||
|
||||
@@ -21,10 +21,14 @@ use rns_identity::destination::Destination;
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_runtime::lifecycle::ShutdownSignal;
|
||||
use rns_runtime::link_client::{LinkClient, LinkClientError, RequestFailure};
|
||||
use rns_runtime::link_session::{
|
||||
LinkSession, LinkSessionCloseReason, LinkSessionError, LinkSessionEvent, RequestOptions,
|
||||
};
|
||||
use rns_runtime::platform::{StoragePaths, resolve_config_dir};
|
||||
use rns_runtime::prelude::CloseReason;
|
||||
use rns_runtime::reticulum::{
|
||||
InitOptions, InstanceMode, ReticulumConfig, ReticulumHandle, SharedInstanceRpcEndpoint,
|
||||
init_with_options,
|
||||
InitOptions, InstanceMode, LinkConnectError, LinkConnectOptions, ReticulumConfig,
|
||||
ReticulumHandle, SharedInstanceRpcEndpoint, init_with_options,
|
||||
};
|
||||
use rns_runtime::rpc::{self, ManageOperation, RpcRequest};
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
@@ -324,6 +328,21 @@ struct Session {
|
||||
handle: ReticulumHandle,
|
||||
rpc_key: Vec<u8>,
|
||||
first_remote_request: std::sync::atomic::AtomicBool,
|
||||
/// Monitor mode's remote link, reused while it stays up (rnstatus.py:139-146).
|
||||
remote_link: tokio::sync::Mutex<Option<RemoteLink>>,
|
||||
}
|
||||
|
||||
struct RemoteLink {
|
||||
session: LinkSession,
|
||||
closed: tokio::sync::watch::Receiver<Option<LinkSessionCloseReason>>,
|
||||
}
|
||||
|
||||
/// How a remote `/status` query ended without a response.
|
||||
enum RemoteFailure {
|
||||
/// The request failed; carries the link-closed line printed before it.
|
||||
Unanswered(Option<&'static str>),
|
||||
LinkTimeout,
|
||||
LinkLost,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -353,10 +372,14 @@ impl Session {
|
||||
handle,
|
||||
rpc_key,
|
||||
first_remote_request: AtomicBool::new(true),
|
||||
remote_link: tokio::sync::Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
async fn close(self) {
|
||||
if let Some(link) = self.remote_link.lock().await.take() {
|
||||
link.session.handle.close().await;
|
||||
}
|
||||
rns_tools::shut_down(&self.handle).await;
|
||||
}
|
||||
|
||||
@@ -612,32 +635,22 @@ impl Session {
|
||||
} else {
|
||||
Value::Array(vec![Value::Boolean(args.link_stats)])
|
||||
};
|
||||
let mut payload = Vec::new();
|
||||
let _ = rmpv::encode::write_value(&mut payload, &request);
|
||||
let client = LinkClient::new(self.handle.transport_tx.clone(), identity);
|
||||
let answer = client
|
||||
.query(
|
||||
identity_hash,
|
||||
MGMT_APP,
|
||||
"/status",
|
||||
payload,
|
||||
REMOTE_HOPS,
|
||||
REMOTE_LINK_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
let answer = if args.monitor {
|
||||
self.monitor_query(identity_hash, identity, request).await
|
||||
} else {
|
||||
one_shot_query(&self.handle, identity_hash, identity, &request).await
|
||||
};
|
||||
let bytes = match answer {
|
||||
Ok(bytes) => bytes,
|
||||
// No response to the identified request, or the link closed while
|
||||
// it was pending. Upstream's link-closed callback prints its line but
|
||||
// its exit() runs off the main thread, so the request failure follows.
|
||||
Err(e) if request_went_unanswered(&e) => {
|
||||
Err(RemoteFailure::Unanswered(closed_text)) => {
|
||||
if !no_output {
|
||||
if first {
|
||||
outp!(out, "{CLR}Sending request... ");
|
||||
}
|
||||
if let LinkClientError::RequestFailed(RequestFailure::LinkClosed(reason)) = &e
|
||||
&& let Some(text) = link_closed_text(*reason)
|
||||
{
|
||||
if let Some(text) = closed_text {
|
||||
outp!(out, "{CLR}");
|
||||
outln!(out, "{text}");
|
||||
}
|
||||
@@ -649,15 +662,14 @@ impl Session {
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
Err(LinkClientError::Timeout(_)) => {
|
||||
Err(RemoteFailure::LinkTimeout) => {
|
||||
if !no_output {
|
||||
outp!(out, "{CLR}");
|
||||
outln!(out, "The link timed out, exiting now");
|
||||
}
|
||||
return Err(10);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::debug!("remote status query failed: {e}");
|
||||
Err(RemoteFailure::LinkLost) => {
|
||||
if !no_output {
|
||||
outp!(out, "{CLR}");
|
||||
outln!(out, "Link closed unexpectedly, exiting now");
|
||||
@@ -745,20 +757,131 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn request_went_unanswered(error: &LinkClientError) -> bool {
|
||||
matches!(error, LinkClientError::RequestFailed(_))
|
||||
/// One `/status` request on a fresh link, torn down afterwards.
|
||||
async fn one_shot_query(
|
||||
handle: &ReticulumHandle,
|
||||
identity_hash: [u8; 16],
|
||||
identity: Identity,
|
||||
request: &Value,
|
||||
) -> Result<Vec<u8>, RemoteFailure> {
|
||||
let mut payload = Vec::new();
|
||||
let _ = rmpv::encode::write_value(&mut payload, request);
|
||||
let client = LinkClient::new(handle.transport_tx.clone(), identity);
|
||||
client
|
||||
.query(
|
||||
identity_hash,
|
||||
MGMT_APP,
|
||||
"/status",
|
||||
payload,
|
||||
REMOTE_HOPS,
|
||||
REMOTE_LINK_TIMEOUT,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| match e {
|
||||
LinkClientError::RequestFailed(RequestFailure::LinkClosed(reason)) => {
|
||||
RemoteFailure::Unanswered(rns_tools::link_closed_text(reason))
|
||||
}
|
||||
LinkClientError::RequestFailed(RequestFailure::TimedOut) => {
|
||||
RemoteFailure::Unanswered(None)
|
||||
}
|
||||
LinkClientError::Timeout(_) => RemoteFailure::LinkTimeout,
|
||||
e => {
|
||||
tracing::debug!("remote status query failed: {e}");
|
||||
RemoteFailure::LinkLost
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// rnstatus.py:87-100: the line for each `teardown_reason`, none for a local close.
|
||||
fn link_closed_text(reason: Option<rns_runtime::prelude::CloseReason>) -> Option<&'static str> {
|
||||
use rns_runtime::prelude::CloseReason;
|
||||
match reason {
|
||||
Some(CloseReason::InitiatorClosed) => None,
|
||||
Some(CloseReason::Timeout) => Some("The link timed out, exiting now"),
|
||||
Some(CloseReason::DestinationClosed) => {
|
||||
Some("The link was closed by the server, exiting now")
|
||||
impl Session {
|
||||
/// Monitor mode: request on the remote link while it is active, else open
|
||||
/// a new one (rnstatus.py:139-146).
|
||||
async fn monitor_query(
|
||||
&self,
|
||||
identity_hash: [u8; 16],
|
||||
identity: Identity,
|
||||
request: Value,
|
||||
) -> Result<Vec<u8>, RemoteFailure> {
|
||||
let mut cached = self.remote_link.lock().await;
|
||||
if cached
|
||||
.as_ref()
|
||||
.is_some_and(|link| link.closed.borrow().is_some())
|
||||
{
|
||||
*cached = None;
|
||||
}
|
||||
_ => Some("Link closed unexpectedly, exiting now"),
|
||||
if cached.is_none() {
|
||||
*cached = Some(self.open_remote_link(identity_hash, identity).await?);
|
||||
}
|
||||
let link = cached.as_mut().expect("opened above");
|
||||
let result = link
|
||||
.session
|
||||
.handle
|
||||
.request_with_options("/status", request, RequestOptions::default())
|
||||
.await;
|
||||
match result {
|
||||
Ok(response) => {
|
||||
let mut bytes = Vec::new();
|
||||
let _ = rmpv::encode::write_value(&mut bytes, &response.value);
|
||||
Ok(bytes)
|
||||
}
|
||||
Err(LinkSessionError::Timeout(_)) => Err(RemoteFailure::Unanswered(None)),
|
||||
Err(_) => {
|
||||
// The session reports its close reason just after failing the request.
|
||||
let mut closed = link.closed.clone();
|
||||
let reason =
|
||||
tokio::time::timeout(Duration::from_secs(1), closed.wait_for(Option::is_some))
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|r| r.ok().and_then(|reason| *reason));
|
||||
*cached = None;
|
||||
let reason = match reason {
|
||||
Some(LinkSessionCloseReason::Local) => Some(CloseReason::InitiatorClosed),
|
||||
Some(LinkSessionCloseReason::Remote) => Some(CloseReason::DestinationClosed),
|
||||
Some(LinkSessionCloseReason::Timeout) => Some(CloseReason::Timeout),
|
||||
_ => None,
|
||||
};
|
||||
Err(RemoteFailure::Unanswered(rns_tools::link_closed_text(
|
||||
reason,
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn open_remote_link(
|
||||
&self,
|
||||
identity_hash: [u8; 16],
|
||||
identity: Identity,
|
||||
) -> Result<RemoteLink, RemoteFailure> {
|
||||
let destination = Destination::hash_from_name_and_identity(MGMT_APP, Some(&identity_hash));
|
||||
let options = LinkConnectOptions {
|
||||
client_label: "rnstatus".to_string(),
|
||||
identify: true,
|
||||
..LinkConnectOptions::default()
|
||||
};
|
||||
let connected = tokio::time::timeout(
|
||||
REMOTE_LINK_TIMEOUT,
|
||||
self.handle.connect_link(destination, identity, options),
|
||||
)
|
||||
.await;
|
||||
let mut session = match connected {
|
||||
Ok(Ok(session)) => session,
|
||||
Err(_) | Ok(Err(LinkConnectError::Session(LinkSessionError::Timeout(_)))) => {
|
||||
return Err(RemoteFailure::LinkTimeout);
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
tracing::debug!("remote link failed: {e}");
|
||||
return Err(RemoteFailure::LinkLost);
|
||||
}
|
||||
};
|
||||
let (closed_tx, closed) = tokio::sync::watch::channel(None);
|
||||
let mut events = std::mem::replace(&mut session.events, tokio::sync::mpsc::channel(1).1);
|
||||
tokio::spawn(async move {
|
||||
while let Some(event) = events.recv().await {
|
||||
if let LinkSessionEvent::Closed { reason } = event {
|
||||
closed_tx.send_replace(Some(reason));
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(RemoteLink { session, closed })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::Parser;
|
||||
use tokio::sync::mpsc;
|
||||
@@ -517,7 +517,6 @@ impl Client<'_> {
|
||||
..LinkConnectOptions::default()
|
||||
};
|
||||
let msg = format!("Establishing link with <{}>", hex::encode(hash));
|
||||
let started = Instant::now();
|
||||
let connected = spin(
|
||||
&msg,
|
||||
handle.connect_link(hash, self.identity.clone(), options),
|
||||
@@ -525,7 +524,7 @@ impl Client<'_> {
|
||||
.await;
|
||||
match connected {
|
||||
Ok(mut session) => {
|
||||
let rtt = started.elapsed().as_secs_f64();
|
||||
let rtt = session.handle.rtt();
|
||||
let events = std::mem::replace(&mut session.events, mpsc::channel(1).1);
|
||||
tokio::spawn(drain(events));
|
||||
Some((session, rtt))
|
||||
@@ -570,25 +569,32 @@ impl Client<'_> {
|
||||
}
|
||||
}
|
||||
let (session, rtt) = self.session.as_ref().expect("connected above");
|
||||
let (link, rtt) = (session.handle.clone(), *rtt);
|
||||
let data = rns_tools::rnx::request_value(command, timeout, args.stdout, args.stderr, stdin);
|
||||
let request_size = packed_request_size(&data);
|
||||
let rexec_timeout = timeout.seconds() + rtt * 4.0 + REMOTE_EXEC_GRACE;
|
||||
let request = session.handle.request_with_options(
|
||||
let (progress_tx, mut progress_rx) = tokio::sync::watch::channel(0.0);
|
||||
let request = link.request_with_options(
|
||||
COMMAND_PATH,
|
||||
data,
|
||||
RequestOptions {
|
||||
timeout: Some(secs(rexec_timeout)),
|
||||
progress: Some(progress_tx),
|
||||
..RequestOptions::default()
|
||||
},
|
||||
);
|
||||
tokio::pin!(request);
|
||||
// `-W` bounds only the result transfer; when it passes, the receipt
|
||||
// still holds no response (rnx.py:425-430, 443, 527-532).
|
||||
let result = match args.result_timeout {
|
||||
Some(w) => tokio::time::timeout(secs(rexec_timeout + w), request)
|
||||
.await
|
||||
.ok(),
|
||||
Some(w) => tokio::select! {
|
||||
r = &mut request => Some(r),
|
||||
_ = progress_rx.changed() => tokio::time::timeout(secs(w), &mut request).await.ok(),
|
||||
},
|
||||
None => Some(request.await),
|
||||
};
|
||||
let response = match result {
|
||||
None => return fail("Receiving result failed", 246),
|
||||
None => return fail("No response", 249),
|
||||
Some(Ok(response)) => response,
|
||||
Some(Err(LinkSessionError::SessionClosed | LinkSessionError::LinkNotActive)) => {
|
||||
self.session = None;
|
||||
|
||||
@@ -188,6 +188,20 @@ where
|
||||
};
|
||||
}
|
||||
|
||||
/// The line rnstatus and rnpath print for a remote link's `teardown_reason`,
|
||||
/// none for a local close (rnstatus.py:87-100, rnpath.py:62-76).
|
||||
pub fn link_closed_text(reason: Option<rns_runtime::prelude::CloseReason>) -> Option<&'static str> {
|
||||
use rns_runtime::prelude::CloseReason;
|
||||
match reason {
|
||||
Some(CloseReason::InitiatorClosed) => None,
|
||||
Some(CloseReason::Timeout) => Some("The link timed out, exiting now"),
|
||||
Some(CloseReason::DestinationClosed) => {
|
||||
Some("The link was closed by the server, exiting now")
|
||||
}
|
||||
_ => Some("Link closed unexpectedly, exiting now"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest a tool waits for its runtime to shut down before exiting.
|
||||
const EXIT_SHUTDOWN_DEADLINE: Duration = Duration::from_secs(10);
|
||||
|
||||
|
||||
Reference in new issue
Block a user