diff --git a/crates/rns-interface/src/android_usb.rs b/crates/rns-interface/src/android_usb.rs index 51d934e..630d909 100644 --- a/crates/rns-interface/src/android_usb.rs +++ b/crates/rns-interface/src/android_usb.rs @@ -9,11 +9,11 @@ use bytes::Bytes; use tokio::sync::{mpsc, watch}; use crate::android_usb_lifecycle::{ - OwnedUsbIo, UsbConnectionCleanup, UsbConnectionLifecycle, UsbDeviceCandidate, - UsbDeviceResolutionError, UsbDeviceSelector, UsbInboundOutcome, UsbInboundState, UsbIoEvent, - UsbLeaseTable, UsbRNodeCapabilityAdmission, UsbRNodeCapabilityStartupError, + OwnedUsbIo, UsbApplicationQueue, UsbConnectionCleanup, UsbConnectionLifecycle, + UsbDeviceCandidate, UsbDeviceResolutionError, UsbDeviceSelector, UsbInboundOutcome, + UsbInboundState, UsbIoEvent, UsbLeaseTable, UsbRNodeCapabilityStartupError, UsbReadDrainOutcome, UsbReadResult, UsbReaderBackend, UsbShutdownReport, UsbTransferError, - UsbTxPumpExit, UsbWriterBackend, drain_usb_reader_tail, forward_usb_read_chunk, + UsbTxGate, UsbTxPumpExit, UsbWriterBackend, drain_usb_reader_tail, forward_usb_read_chunk, resolve_usb_device, run_usb_rnode_capability_startup, run_usb_rnode_startup, run_usb_tx_pump, spawn_owned_usb_io, }; @@ -23,7 +23,8 @@ use crate::rnode::{ self, RNodeDriverShutdown, RNodeRuntimeReason, RNodeSpawnError, RNodeStartupOptions, RNodeTransportClass, SpawnedRNodeInterface, }; -use crate::rnode_protocol::RNodeProtocolTarget; +use crate::rnode_capabilities::RNodeRadioAdmission; +use crate::rnode_protocol::{RNodeProtocolState, RNodeProtocolTarget}; use crate::traits::{ InterfaceDirection, InterfaceError, InterfaceHandle, InterfaceId, InterfaceMode, }; @@ -1439,7 +1440,8 @@ async fn shutdown_failed_android_usb_startup( struct AndroidUsbGeneration { usb: OwnedUsbIo, - protocol_state: Option, + protocol_state: RNodeProtocolState, + admission: Option, selector: UsbDeviceSelector, } @@ -1458,7 +1460,7 @@ async fn start_android_usb_generation( let (mut usb, _worker_online) = open_usb_serial(&device_name, config.baud_rate).await?; let rnode_cfg = rnode_config_from_android_usb_config(config); let init_bytes = rnode::build_init_sequence(&rnode_cfg); - let protocol_state = if options.requires_capability_admission() { + let (protocol_state, admission) = if options.requires_capability_admission() { match run_usb_rnode_capability_startup( &mut usb, rnode::RNodeRadioSettings::from(&rnode_cfg), @@ -1469,7 +1471,7 @@ async fn start_android_usb_generation( ) .await { - Ok(admission) => Some(admission), + Ok(admission) => (admission.protocol_state, Some(admission.admission)), Err(error) => { let init_may_have_started = matches!(&error, UsbRNodeCapabilityStartupError::Initialise(_)); @@ -1513,31 +1515,42 @@ async fn start_android_usb_generation( }); } } - } else if let Err(error) = run_usb_rnode_startup( - &usb.writer, - rnode::build_detect_sequence(), - init_bytes, - USB_STARTUP_ACK_DEADLINE, - ) - .await - { - // The legacy startup helper can enqueue part of the initialisation - // sequence before reporting failure. Always attempt the terminal - // detach here so a retry does not inherit an active radio session. - let cleanup = shutdown_failed_android_usb_startup(usb, true).await; - let cleanup = cleanup - .map(|cleanup| format!("; cleanup: {cleanup}")) - .unwrap_or_default(); - return Err(RNodeSpawnError::Interface(InterfaceError::SendFailed( - format!("Android USB RNode startup failed: {error}{cleanup}"), - ))); } else { - None + match run_usb_rnode_startup( + &mut usb, + RNodeProtocolTarget::new( + config.frequency, + config.bandwidth, + config.spreading_factor, + config.coding_rate, + config.tx_power, + ), + rnode::build_detect_sequence(), + init_bytes, + USB_STARTUP_ACK_DEADLINE, + ) + .await + { + Ok(protocol) => (protocol, None), + Err(error) => { + // The legacy startup helper can enqueue part of the initialisation + // sequence before reporting failure. Always attempt the terminal + // detach here so a retry does not inherit an active radio session. + let cleanup = shutdown_failed_android_usb_startup(usb, true).await; + let cleanup = cleanup + .map(|cleanup| format!("; cleanup: {cleanup}")) + .unwrap_or_default(); + return Err(RNodeSpawnError::Interface(InterfaceError::SendFailed( + format!("Android USB RNode startup failed: {error}{cleanup}"), + ))); + } + } }; Ok(AndroidUsbGeneration { usb, protocol_state, + admission, selector, }) } @@ -1591,14 +1604,6 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( let initial_generation = start_android_usb_generation(&config, options).await?; let name = config.name.clone(); - let protocol_target = RNodeProtocolTarget::new( - config.frequency, - config.bandwidth, - config.spreading_factor, - config.coding_rate, - config.tx_power, - ); - let shared_txb = Arc::new(AtomicU64::new(0)); let shared_rxb = Arc::new(AtomicU64::new(0)); let beacon = config @@ -1621,7 +1626,7 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( // Match the serial and BLE RNode application queue. The queue is logical // interface state and survives physical Android USB reconnects. let (tx, app_rx) = mpsc::channel::(256); - let app_rx = Arc::new(tokio::sync::Mutex::new(app_rx)); + let app_rx = Arc::new(tokio::sync::Mutex::new(UsbApplicationQueue::new(app_rx))); let (stop_tx, mut stop_rx) = mpsc::channel::<()>(1); let (snapshot_publisher, driver) = rnode::new_rnode_driver_observation_with_shutdown( RNodeTransportClass::Usb, @@ -1634,7 +1639,7 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( let read_name = name.clone(); let txb = shared_txb.clone(); let rxb = shared_rxb.clone(); - let online = Arc::new(AtomicBool::new(true)); + let online = Arc::new(AtomicBool::new(false)); let online_task = online.clone(); let mut reconnect_config = config.clone(); reconnect_config.apply_selector(initial_generation.selector.clone()); @@ -1703,26 +1708,22 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( let AndroidUsbGeneration { mut usb, protocol_state, + admission, selector, } = generation; reconnect_config.apply_selector(selector); let mut publisher = snapshot_publisher .take() .expect("Android USB generation publisher missing"); - let mut inbound = match protocol_state { - Some(UsbRNodeCapabilityAdmission { - protocol_state, - admission, - }) => { - publisher.capability_connection_established(&protocol_state, admission); - UsbInboundState::projected_with_protocol_state(protocol_state, publisher) - } - None => { - publisher.connection_established(); - UsbInboundState::projected(protocol_target, publisher) - } - }; - online_task.store(true, Ordering::SeqCst); + if let Some(admission) = admission { + publisher.capability_connection_established(&protocol_state, admission); + } else { + publisher.connection_established(); + } + let mut inbound = + UsbInboundState::projected_with_protocol_state(protocol_state, publisher); + let gate = UsbTxGate::new(reconnect_config.flow_control, online_task.clone()); + inbound.attach_tx_gate(gate.clone()); let (tx_pump_stop_tx, tx_pump_stop_rx) = tokio::sync::oneshot::channel(); let (tx_pump_exit_tx, mut tx_pump_exit_rx) = tokio::sync::oneshot::channel(); @@ -1730,10 +1731,17 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( let pump_txb = txb.clone(); let pump_rx = app_rx.clone(); let pump_beacon = beacon.clone(); + let pump_gate = gate.clone(); let mut tx_pump = tokio::spawn(async move { - let exit = - run_usb_tx_pump(pump_rx, pump_writer, pump_txb, pump_beacon, tx_pump_stop_rx) - .await; + let exit = run_usb_tx_pump( + pump_rx, + pump_writer, + pump_txb, + pump_beacon, + pump_gate, + tx_pump_stop_rx, + ) + .await; let _ = tx_pump_exit_tx.send(exit); }); let mut stop_requested = false; @@ -1761,10 +1769,14 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( tracing::warn!( name = %read_name, error = %error, - "Android USB packet could not be queued" + "Android USB packet write did not complete" ); drain_reader_tail = true; } + Ok(UsbTxPumpExit::ReadinessTimedOut) => { + tracing::warn!(name = %read_name, + "Android USB fresh protocol readiness timed out"); + } Ok(UsbTxPumpExit::ApplicationClosed) => { terminal_reason = RNodeRuntimeReason::TransportConsumerClosed; } @@ -1803,14 +1815,41 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( break; } Some(UsbIoEvent::Read(bytes)) => { - match forward_usb_read_chunk( + let forwarding = forward_usb_read_chunk( &mut inbound, &bytes, id, rxb.as_ref(), &transport_tx, &mut stop_rx, - ).await { + ); + // Transport backpressure must not conceal a + // failed/timed-out writer or prevent its owner + // from reaching bounded physical cleanup. + // The pump owns the current generation's + // readiness-episode deadline, including a new + // Ready -> notReady transition after idle. + let outcome = tokio::select! { + biased; + pump = &mut tx_pump_exit_rx => { + match pump { + Ok(UsbTxPumpExit::ApplicationClosed) => { + terminal_reason = RNodeRuntimeReason::TransportConsumerClosed; + } + Ok(UsbTxPumpExit::StopRequested) => { + stop_requested = true; + terminal_reason = RNodeRuntimeReason::StopRequested; + } + Ok(UsbTxPumpExit::ReadinessTimedOut) => {} + Ok(UsbTxPumpExit::WriterRejected(_)) | Err(_) => { + drain_reader_tail = true; + } + } + break; + } + outcome = forwarding => outcome, + }; + match outcome { UsbInboundOutcome::Complete => {} UsbInboundOutcome::StopRequested => { stop_requested = true; @@ -1835,6 +1874,9 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options( } } + // Close the operational gate before any drain/detach work. Late + // frames from this generation may update diagnostics, not reopen TX. + gate.close(); let _ = tx_pump_stop_tx.send(()); if tokio::time::timeout(USB_WORKER_JOIN_DEADLINE, &mut tx_pump) .await diff --git a/crates/rns-interface/src/android_usb_lifecycle.rs b/crates/rns-interface/src/android_usb_lifecycle.rs index 148e525..a5ac34b 100644 --- a/crates/rns-interface/src/android_usb_lifecycle.rs +++ b/crates/rns-interface/src/android_usb_lifecycle.rs @@ -10,7 +10,7 @@ use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant}; use bytes::Bytes; -use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc, oneshot}; +use tokio::sync::{Notify, OwnedSemaphorePermit, Semaphore, mpsc, oneshot}; use tokio::task::JoinHandle; use crate::kiss; @@ -20,12 +20,16 @@ use crate::rnode::{ }; use crate::rnode_capabilities::RNodeRadioAdmission; use crate::rnode_capability_preflight::RNodeCapabilityPreflight; -use crate::rnode_protocol::{RNodeProtocolState, RNodeProtocolTarget}; +use crate::rnode_protocol::{ + RNodeProtocolFrame, RNodeProtocolState, RNodeProtocolTarget, RNodeReadiness, +}; use crate::traits::InterfaceId; use rns_transport::messages::TransportMessage; const MIN_TRANSFER_TIMEOUT: Duration = Duration::from_millis(1); const USB_READER_BOUNDARY_POLL_INTERVAL: Duration = Duration::from_millis(1); +const USB_PACKET_WRITE_DEADLINE: Duration = Duration::from_secs(2); +pub(crate) const USB_PROTOCOL_READINESS_DEADLINE: Duration = Duration::from_secs(10); /// Stable identity retained across Android's transient `/dev/bus/usb` names. #[derive(Clone, Debug, Eq, PartialEq)] @@ -331,6 +335,7 @@ pub(crate) enum UsbWriteFailureKind { QueueClosed, AcknowledgementDropped, DeadlineElapsed, + AdmissionClosed, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -389,6 +394,13 @@ impl std::fmt::Display for UsbWriteFailure { self.phase.label() ) } + UsbWriteFailureKind::AdmissionClosed => { + write!( + formatter, + "{} protocol/flow admission closed", + self.phase.label() + ) + } } } } @@ -399,9 +411,139 @@ struct UsbWriteRequest { deadline: Option, acknowledgement: Option>>, await_terminal_detach_on_failure: bool, + packet: Option, _permit: Option, } +struct UsbPacketWrite { + transmitted_bytes: Arc, + payload_len: u64, + gate: Option>, + completed: Arc, +} + +/// Operational state belongs to one physical generation, never to an observer +/// snapshot. The shared online flag describes typed protocol readiness; READY +/// is an independent, saturating one-packet permission when configured. +pub(crate) struct UsbTxGate { + state: Mutex, + flow_control: bool, + online: Arc, + changed: Notify, +} + +struct UsbTxGateState { + ready: bool, + permit: bool, + closed: bool, + readiness_deadline: tokio::time::Instant, +} + +impl UsbTxGate { + pub(crate) fn new(flow_control: bool, online: Arc) -> Arc { + online.store(false, Ordering::Release); + Arc::new(Self { + state: Mutex::new(UsbTxGateState { + ready: false, + permit: true, + closed: false, + readiness_deadline: tokio::time::Instant::now() + USB_PROTOCOL_READINESS_DEADLINE, + }), + flow_control, + online, + changed: Notify::new(), + }) + } + + fn observe(&self, protocol: &RNodeProtocolState, command: u8, frame: &[u8]) { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if state.closed { + return; + } + let ready = protocol.readiness() == RNodeReadiness::Ready; + if state.ready && !ready { + // A later loss of RF readiness owns a new bounded recovery + // episode, even after hours of healthy idle time. Repeated bad + // evidence must not extend that episode or preserve an old grant. + state.readiness_deadline = + tokio::time::Instant::now() + USB_PROTOCOL_READINESS_DEADLINE; + state.permit = false; + } + state.ready = ready; + // Decode every valid READY, including an identical repeated positive + // response: the diagnostic reducer may call it NoChange after we used + // the prior permit. Malformed widths never grant or revoke permission. + match RNodeProtocolFrame::decode(command, frame) { + Ok(RNodeProtocolFrame::FlowPermission(permitted)) => state.permit = permitted, + Ok(RNodeProtocolFrame::Reset) => state.permit = false, + _ => {} + } + self.online.store(state.ready, Ordering::Release); + drop(state); + self.changed.notify_one(); + } + + fn can_send(&self) -> bool { + let state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + !state.closed && state.ready && (!self.flow_control || state.permit) + } + + #[cfg(test)] + fn is_ready(&self) -> bool { + let state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + !state.closed && state.ready + } + + fn readiness_deadline(&self) -> Option { + let state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + (!state.closed && !state.ready).then_some(state.readiness_deadline) + } + + fn readiness_expired(&self) -> bool { + self.readiness_deadline() + .is_some_and(|deadline| tokio::time::Instant::now() >= deadline) + } + + fn take_permit(&self) -> bool { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if state.closed || !state.ready || (self.flow_control && !state.permit) { + return false; + } + if self.flow_control { + state.permit = false; + } + true + } + + pub(crate) fn close(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + state.closed = true; + state.ready = false; + state.permit = false; + self.online.store(false, Ordering::Release); + drop(state); + self.changed.notify_one(); + } +} + struct UsbWriteQueueState { requests: VecDeque, accepting: bool, @@ -436,17 +578,6 @@ impl UsbWriteQueue { } } - async fn enqueue( - &self, - phase: UsbWritePhase, - bytes: Vec, - deadline: Option, - acknowledgement: Option>>, - ) -> Result<(), UsbWriteFailure> { - self.enqueue_with_failure_policy(phase, bytes, deadline, acknowledgement, false) - .await - } - async fn enqueue_with_failure_policy( &self, phase: UsbWritePhase, @@ -454,6 +585,7 @@ impl UsbWriteQueue { deadline: Option, acknowledgement: Option>>, await_terminal_detach_on_failure: bool, + packet: Option, ) -> Result<(), UsbWriteFailure> { let permit = self .inner @@ -482,6 +614,7 @@ impl UsbWriteQueue { deadline, acknowledgement, await_terminal_detach_on_failure, + packet, _permit: Some(permit), }); drop(state); @@ -519,6 +652,7 @@ impl UsbWriteQueue { deadline: Some(deadline), acknowledgement: Some(acknowledgement), await_terminal_detach_on_failure: false, + packet: None, _permit: None, }); drop(state); @@ -615,6 +749,7 @@ pub(crate) struct UsbInboundState { last_rssi: Option, last_snr: Option, projection: Option, + tx_gate: Option>, } struct UsbRNodeProjection { @@ -629,9 +764,11 @@ impl UsbInboundState { last_rssi: None, last_snr: None, projection: None, + tx_gate: None, } } + #[cfg(test)] pub(crate) fn projected( target: RNodeProtocolTarget, publisher: RNodeSnapshotPublisher, @@ -663,18 +800,33 @@ impl UsbInboundState { return; }; let effect = projection.protocol.apply_frame(command, frame); + if let Some(gate) = &self.tx_gate { + gate.observe(&projection.protocol, command, frame); + } projection .publisher .protocol_effect(&projection.protocol, effect); } + pub(crate) fn attach_tx_gate(&mut self, gate: Arc) { + // A gate is never seeded from retained diagnostics. Fresh protocol + // frames in this exact physical generation own its admission state. + self.tx_gate = Some(gate); + } + pub(crate) fn shutting_down(&self, reason: RNodeRuntimeReason) { + if let Some(gate) = &self.tx_gate { + gate.close(); + } if let Some(projection) = &self.projection { projection.publisher.shutting_down(reason); } } pub(crate) fn stopped(&mut self, reason: RNodeRuntimeReason) { + if let Some(gate) = &self.tx_gate { + gate.close(); + } if let Some(projection) = self.projection.as_mut() { projection.publisher.stopped(reason); } @@ -905,6 +1057,17 @@ where } offset += transferred as usize; } + // Positive completion evidence is independent of the caller's deadline. + // A final bulkTransfer may return all bytes just after its waiter timed + // out. Publish exactly this physical result before classifying the late + // acknowledgement, so the logical queue will not replay a known-complete + // payload after the old physical generation has been fully joined. + if let Some(packet) = &request.packet { + packet + .transmitted_bytes + .fetch_add(packet.payload_len, Ordering::Relaxed); + packet.completed.store(true, Ordering::Release); + } if request .deadline .is_some_and(|deadline| Instant::now() > deadline) @@ -956,7 +1119,22 @@ where !request.await_terminal_detach_on_failure || phase == UsbWritePhase::Initialise ); let await_terminal_detach_on_failure = request.await_terminal_detach_on_failure; - let result = write_request(&mut backend, &request, default_timeout); + let result = if request + .packet + .as_ref() + .and_then(|packet| packet.gate.as_ref()) + .is_some_and(|gate| !gate.take_permit()) + { + Err(UsbWriteFailure { + phase, + kind: UsbWriteFailureKind::AdmissionClosed, + }) + } else { + write_request(&mut backend, &request, default_timeout) + }; + // write_request publishes known complete packet writes even if the + // async waiter disappeared or its deadline elapsed. This is USB + // completion, never proof of RF TX or recipient delivery. if let Some(acknowledgement) = request.acknowledgement { let _ = acknowledgement.send(result.clone()); } @@ -1093,15 +1271,22 @@ impl UsbWriterHandle { ) -> Result<(), UsbWriteFailure> { let deadline = Instant::now() + timeout; let (acknowledgement, result) = oneshot::channel(); - self.queue - .enqueue_with_failure_policy( + tokio::time::timeout_at( + tokio::time::Instant::from_std(deadline), + self.queue.enqueue_with_failure_policy( phase, bytes, Some(deadline), Some(acknowledgement), await_terminal_detach_on_failure, - ) - .await?; + None, + ), + ) + .await + .map_err(|_| UsbWriteFailure { + phase, + kind: UsbWriteFailureKind::DeadlineElapsed, + })??; let remaining = deadline.saturating_duration_since(Instant::now()); if remaining.is_zero() { return Err(UsbWriteFailure { @@ -1121,17 +1306,84 @@ impl UsbWriterHandle { })? } - pub(crate) async fn queue_packet_and_account( + #[cfg(test)] + async fn queue_packet_and_account( &self, bytes: Vec, - transmitted_bytes: &AtomicU64, - ) -> Result<(), UsbWriteFailure> { + transmitted_bytes: &Arc, + ) -> Result>, UsbWriteFailure> { let length = bytes.len() as u64; + self.queue_packet( + bytes, + length, + transmitted_bytes.clone(), + None, + None, + Arc::new(AtomicBool::new(false)), + ) + .await + } + + async fn queue_packet( + &self, + bytes: Vec, + payload_len: u64, + transmitted_bytes: Arc, + gate: Option>, + deadline: Option, + completed: Arc, + ) -> Result>, UsbWriteFailure> { + let (acknowledgement, result) = oneshot::channel(); self.queue - .enqueue(UsbWritePhase::Packet, bytes, None, None) + .enqueue_with_failure_policy( + UsbWritePhase::Packet, + bytes, + deadline, + Some(acknowledgement), + false, + Some(UsbPacketWrite { + transmitted_bytes, + payload_len, + gate, + completed, + }), + ) .await?; - transmitted_bytes.fetch_add(length, Ordering::Relaxed); - Ok(()) + Ok(result) + } + + async fn write_application_packet( + &self, + payload: &Bytes, + transmitted_bytes: Arc, + gate: Arc, + completed: Arc, + ) -> Result<(), UsbWriteFailure> { + // One absolute bound includes queue admission, all short transfers and + // the completion acknowledgement. A timed-out generation must be joined + // before its retained logical payload can be offered to another writer. + let deadline = Instant::now() + USB_PACKET_WRITE_DEADLINE; + tokio::time::timeout(USB_PACKET_WRITE_DEADLINE, async { + self.queue_packet( + kiss::frame(payload), + payload.len() as u64, + transmitted_bytes, + Some(gate), + Some(deadline), + completed, + ) + .await? + .await + .map_err(|_| UsbWriteFailure { + phase: UsbWritePhase::Packet, + kind: UsbWriteFailureKind::AcknowledgementDropped, + })? + }) + .await + .map_err(|_| UsbWriteFailure { + phase: UsbWritePhase::Packet, + kind: UsbWriteFailureKind::DeadlineElapsed, + })? } } @@ -1139,18 +1391,61 @@ impl UsbWriterHandle { /// /// Each phase gets its own queue-to-transfer deadline. These are control /// writes, so they intentionally bypass application-payload accounting. -pub(crate) async fn run_usb_rnode_startup( - writer: &UsbWriterHandle, +pub(crate) async fn run_usb_rnode_startup( + usb: &mut OwnedUsbIo, + target: RNodeProtocolTarget, detect_bytes: Vec, init_bytes: Vec, phase_timeout: Duration, -) -> Result<(), UsbWriteFailure> { - writer +) -> Result { + usb.writer .request_before(UsbWritePhase::Detect, detect_bytes, phase_timeout) .await?; - writer - .request_before(UsbWritePhase::Initialise, init_bytes, phase_timeout) - .await + + // Close the same pre-init freshness boundary used by strict capability + // admission, without making ROM availability a normal-startup requirement. + // Preserve only detect/firmware evidence; queued RF echoes, READY permits, + // DATA and partial framing cannot establish post-init operational readiness. + let mut protocol = RNodeProtocolState::new(target); + let mut deframer = kiss::RawKissDeframer::new(); + let mut observe = |event| -> Result<(), UsbWriteFailure> { + let UsbIoEvent::Read(bytes) = event else { + return Err(UsbWriteFailure { + phase: UsbWritePhase::Detect, + kind: UsbWriteFailureKind::QueueClosed, + }); + }; + for (command, frame) in deframer.feed(&bytes) { + if matches!(command, rnode::CMD_DETECT | rnode::CMD_FW_VERSION) { + protocol.apply_frame(command, &frame); + } + } + Ok(()) + }; + usb.request_reader_boundary(); + let deadline = tokio::time::Instant::now() + phase_timeout; + while !usb.reader_boundary_reached() { + tokio::select! { + biased; + _ = tokio::time::sleep_until(deadline) => { + return Err(UsbWriteFailure { phase: UsbWritePhase::Detect, + kind: UsbWriteFailureKind::DeadlineElapsed }); + } + event = usb.events.recv() => { + observe(event.ok_or(UsbWriteFailure { phase: UsbWritePhase::Detect, + kind: UsbWriteFailureKind::QueueClosed })?)?; + } + _ = tokio::time::sleep(USB_READER_BOUNDARY_POLL_INTERVAL) => {} + } + } + while let Ok(event) = usb.events.try_recv() { + observe(event)?; + } + usb.writer + .request_initialise_before_terminal_detach(init_bytes, phase_timeout) + .await?; + usb.resume_reader(); + Ok(protocol) } /// Successful strict startup evidence retained for the active USB session. @@ -1304,62 +1599,154 @@ where pub(crate) enum UsbTxPumpExit { StopRequested, ApplicationClosed, + ReadinessTimedOut, WriterRejected(UsbWriteFailure), } +pub(crate) struct UsbApplicationQueue { + receiver: mpsc::Receiver, + pending: Option, +} + +struct UsbPendingPacket { + payload: Bytes, + station_id: bool, + completed: Arc, +} + +impl UsbPendingPacket { + fn new(payload: Bytes, station_id: bool) -> Self { + Self { + payload, + station_id, + completed: Arc::new(AtomicBool::new(false)), + } + } +} + +impl UsbApplicationQueue { + pub(crate) fn new(receiver: mpsc::Receiver) -> Self { + Self { + receiver, + pending: None, + } + } +} + +struct UsbTxPumpGateGuard(Arc); + +impl Drop for UsbTxPumpGateGuard { + fn drop(&mut self) { + self.0.close(); + } +} + /// Independent application-to-USB pump. Inbound transport backpressure cannot /// stall writer admission, and a full writer queue cannot stall inbound /// forwarding in the driver task. pub(crate) async fn run_usb_tx_pump( - application_rx: Arc>>, + application_rx: Arc>, writer: UsbWriterHandle, transmitted_bytes: Arc, beacon: Option<(Duration, Bytes)>, + gate: Arc, mut stop: oneshot::Receiver<()>, ) -> UsbTxPumpExit { // A fresh physical USB generation borrows the same application queue. // The lock is released when that generation's pump exits, preserving the // stable InterfaceHandle across reconnects without duplicating queues. - let mut application_rx = application_rx.lock().await; + let _gate_guard = UsbTxPumpGateGuard(gate.clone()); + let mut application_rx = tokio::select! { + biased; + _ = &mut stop => return UsbTxPumpExit::StopRequested, + queue = application_rx.lock() => queue, + }; let mut first_tx: Option = None; loop { - let (payload, station_id) = if let Some((interval, ref callsign)) = beacon { + if application_rx + .pending + .as_ref() + .is_some_and(|packet| packet.completed.load(Ordering::Acquire)) + { + // A cancelled waiter may have missed a later positive physical + // completion. Reconnects reach here only after old workers join; + // incomplete/unknown writes keep their original payload instead. + let packet = application_rx.pending.take().expect("completed USB packet"); + if packet.station_id { + first_tx = None; + } else if first_tx.is_none() { + first_tx = Some(tokio::time::Instant::now()); + } + } + if application_rx.pending.is_none() + && application_rx.receiver.is_closed() + && application_rx.receiver.is_empty() + { + return UsbTxPumpExit::ApplicationClosed; + } + let changed = gate.changed.notified(); + let readiness_deadline = gate.readiness_deadline(); + if !gate.can_send() { tokio::select! { biased; _ = &mut stop => return UsbTxPumpExit::StopRequested, - payload = application_rx.recv() => (payload, false), - _ = tokio::time::sleep(Duration::from_secs(1)) => { - if first_tx.is_some_and(|started| started.elapsed() >= interval) { - (Some(callsign.clone()), true) + // Invalid-frame notifications cannot starve this deadline. + _ = async { + if let Some(deadline) = readiness_deadline { + tokio::time::sleep_until(deadline).await; } else { - continue; + std::future::pending::<()>().await; + } + } => { + // Readiness may have recovered since the timer snapshot; + // flow-permission waiting alone has no protocol timeout. + if gate.readiness_expired() { + return UsbTxPumpExit::ReadinessTimedOut; } } + _ = changed => {}, + }; + continue; + } + + if application_rx.pending.is_none() { + // A due beacon follows an already-pending application packet but + // does not starve behind continuous later application traffic. + if let Some((interval, ref callsign)) = beacon { + if first_tx.is_some_and(|started| started.elapsed() >= interval) { + application_rx.pending = Some(UsbPendingPacket::new(callsign.clone(), true)); + } } - } else { - tokio::select! { - biased; - _ = &mut stop => return UsbTxPumpExit::StopRequested, - payload = application_rx.recv() => (payload, false), + if application_rx.pending.is_none() { + let payload = tokio::select! { + biased; + _ = &mut stop => return UsbTxPumpExit::StopRequested, + _ = changed => continue, + payload = application_rx.receiver.recv() => payload, + _ = tokio::time::sleep(Duration::from_secs(1)), if first_tx.is_some() => continue, + }; + let Some(payload) = payload else { + return UsbTxPumpExit::ApplicationClosed; + }; + application_rx.pending = Some(UsbPendingPacket::new(payload, false)); + continue; } - }; - let Some(payload) = payload else { - return UsbTxPumpExit::ApplicationClosed; - }; - let frame = kiss::frame(&payload); - let queued = tokio::select! { + } + + let packet = application_rx.pending.as_ref().expect("pending USB packet"); + let written = tokio::select! { biased; _ = &mut stop => return UsbTxPumpExit::StopRequested, - result = writer.queue_packet_and_account(frame, transmitted_bytes.as_ref()) => result, + result = writer.write_application_packet( + &packet.payload, transmitted_bytes.clone(), gate.clone(), packet.completed.clone() + ) => result, }; - if let Err(error) = queued { + if let Err(error) = written { return UsbTxPumpExit::WriterRejected(error); } - if station_id { - first_tx = None; - } else if first_tx.is_none() { - first_tx = Some(tokio::time::Instant::now()); - } + // The next iteration retires the positive completion token. Stop, + // rejected admission and partial/unknown writes retain their payload; + // the next generation cannot borrow it until physical workers join. } } @@ -2044,6 +2431,725 @@ mod tests { ) } + fn ready_tx_gate(flow_control: bool) -> Arc { + let gate = UsbTxGate::new(flow_control, Arc::new(AtomicBool::new(false))); + let mut protocol = RNodeProtocolState::new(USB_TEST_TARGET); + for (command, frame) in required_protocol_frames(USB_TEST_TARGET) { + protocol.apply_frame(command, &frame); + gate.observe(&protocol, command, &frame); + } + assert!(gate.is_ready()); + gate + } + + async fn wait_for_count(counter: &AtomicU64, expected: u64) { + tokio::time::timeout(Duration::from_secs(1), async { + while counter.load(Ordering::Relaxed) != expected { + tokio::task::yield_now().await; + } + }) + .await + .expect("USB completed-write count did not converge"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn usb_packet_writes_require_fresh_protocol_and_configured_flow_permission() { + for flow_control in [false, true] { + let writer = ScriptedWriter::new([]); + let calls = writer.calls.clone(); + let io = test_io(writer, Arc::new(Mutex::new(Vec::new()))); + let online = Arc::new(AtomicBool::new(false)); + let gate = UsbTxGate::new(flow_control, online.clone()); + let (mut inbound, _driver) = projected_inbound(); + inbound.attach_tx_gate(gate.clone()); + let (tx, rx) = mpsc::channel(2); + let queue = Arc::new(tokio::sync::Mutex::new(UsbApplicationQueue::new(rx))); + let counter = Arc::new(AtomicU64::new(0)); + let (stop_tx, stop_rx) = oneshot::channel(); + let pump = tokio::spawn(run_usb_tx_pump( + queue, + io.writer.clone(), + counter.clone(), + None, + gate.clone(), + stop_rx, + )); + tx.send(Bytes::from_static(&[kiss::FEND, kiss::FESC])) + .await + .unwrap(); + tx.send(Bytes::from_static(&[1, 2, 3])).await.unwrap(); + inbound.project_frame(rnode::CMD_READY, &[1]); + tokio::time::sleep(Duration::from_millis(10)).await; + assert!(!online.load(Ordering::Acquire)); + assert!( + calls.lock().unwrap().is_empty(), + "CMD_READY alone is not protocol Ready" + ); + + inbound.project_frame(rnode::CMD_READY, &[0]); + let (_stop_tx, mut inbound_stop) = mpsc::channel(1); + let (transport, _transport_rx) = mpsc::channel(1); + let mut evidence = required_protocol_frames(USB_TEST_TARGET); + evidence[2].1 = 100_000_000u32.to_be_bytes().to_vec(); + assert_eq!( + forward_usb_read_chunk( + &mut inbound, + &framed_protocol_frames(evidence), + 1, + &AtomicU64::new(0), + &transport, + &mut inbound_stop + ) + .await, + UsbInboundOutcome::Complete + ); + assert!( + !gate.can_send(), + "mismatched RF evidence must not admit a packet" + ); + inbound.project_frame( + rnode::CMD_FREQUENCY, + &USB_TEST_TARGET.frequency.to_be_bytes(), + ); + assert!(online.load(Ordering::Acquire)); + if flow_control { + tokio::time::sleep(Duration::from_millis(10)).await; + assert_eq!(counter.load(Ordering::Relaxed), 0); + inbound.project_frame(rnode::CMD_READY, &[1]); + wait_for_count(&counter, 2).await; + inbound.project_frame(rnode::CMD_READY, &[1, 1]); + tokio::time::sleep(Duration::from_millis(10)).await; + assert_eq!( + counter.load(Ordering::Relaxed), + 2, + "malformed grant must not release packet two" + ); + // Repeated valid READY=1 must replenish a consumed permit even + // when the diagnostic reducer classifies it as NoChange. + inbound.project_frame(rnode::CMD_READY, &[1]); + } + wait_for_count(&counter, 5).await; + assert_eq!( + calls + .lock() + .unwrap() + .iter() + .map(|(bytes, _)| bytes.clone()) + .collect::>(), + vec![ + kiss::frame(&[kiss::FEND, kiss::FESC]), + kiss::frame(&[1, 2, 3]) + ] + ); + stop_tx.send(()).unwrap(); + assert_eq!(pump.await.unwrap(), UsbTxPumpExit::StopRequested); + assert!(!online.load(Ordering::Acquire)); + let _ = io + .shutdown(None, Duration::from_millis(20), Duration::from_secs(1)) + .await; + } + } + + #[tokio::test(start_paused = true)] + async fn usb_absent_protocol_readiness_has_a_bounded_generation_deadline() { + let (tx, rx) = mpsc::channel(1); + tx.send(Bytes::from_static(b"held")).await.unwrap(); + let queue = Arc::new(tokio::sync::Mutex::new(UsbApplicationQueue::new(rx))); + let writer = UsbWriterHandle { + queue: UsbWriteQueue::new(1), + }; + let gate = UsbTxGate::new(false, Arc::new(AtomicBool::new(false))); + let counter = Arc::new(AtomicU64::new(0)); + let (_stop, stopped) = oneshot::channel(); + let pump = tokio::spawn(run_usb_tx_pump( + queue.clone(), + writer, + counter.clone(), + None, + gate.clone(), + stopped, + )); + tokio::task::yield_now().await; + tokio::time::advance(USB_PROTOCOL_READINESS_DEADLINE + Duration::from_millis(1)).await; + assert_eq!(pump.await.unwrap(), UsbTxPumpExit::ReadinessTimedOut); + assert!(!gate.is_ready()); + assert_eq!(counter.load(Ordering::Relaxed), 0); + assert_eq!( + queue.lock().await.receiver.try_recv().unwrap(), + Bytes::from_static(b"held") + ); + } + + #[tokio::test(start_paused = true)] + async fn usb_readiness_recovers_after_long_idle_without_reusing_a_flow_grant() { + for fault in [rnode::CMD_RESET, rnode::CMD_FREQUENCY] { + let (_tx, rx) = mpsc::channel(1); + let queue = Arc::new(tokio::sync::Mutex::new(UsbApplicationQueue::new(rx))); + let gate = UsbTxGate::new(true, Arc::new(AtomicBool::new(false))); + let (mut inbound, _driver) = projected_inbound(); + inbound.attach_tx_gate(gate.clone()); + for (command, frame) in required_protocol_frames(USB_TEST_TARGET) { + inbound.project_frame(command, &frame); + } + assert!(gate.can_send()); + let (stop_tx, stop_rx) = oneshot::channel(); + let pump = tokio::spawn(run_usb_tx_pump( + queue, + UsbWriterHandle { + queue: UsbWriteQueue::new(1), + }, + Arc::new(AtomicU64::new(0)), + None, + gate.clone(), + stop_rx, + )); + tokio::task::yield_now().await; + tokio::time::advance(Duration::from_secs(60)).await; + let frame = if fault == rnode::CMD_RESET { + vec![0xF8] + } else { + 100_000_000u32.to_be_bytes().to_vec() + }; + inbound.project_frame(fault, &frame); + assert!( + !gate.take_permit(), + "readiness loss fences the writer immediately" + ); + tokio::task::yield_now().await; + assert!( + !pump.is_finished(), + "idle startup age is not a new recovery deadline" + ); + tokio::time::advance(Duration::from_secs(5)).await; + for (command, frame) in required_protocol_frames(USB_TEST_TARGET) { + inbound.project_frame(command, &frame); + } + assert!(gate.is_ready()); + assert!( + !gate.can_send(), + "a pre-fault flow permit must not survive recovery" + ); + inbound.project_frame(rnode::CMD_READY, &[1]); + assert!(gate.can_send()); + tokio::task::yield_now().await; + tokio::time::advance(Duration::from_secs(20)).await; + assert!( + !pump.is_finished(), + "successful recovery retires its deadline" + ); + stop_tx.send(()).unwrap(); + assert_eq!(pump.await.unwrap(), UsbTxPumpExit::StopRequested); + } + } + + #[tokio::test(start_paused = true)] + async fn usb_readiness_loss_gets_one_fresh_bounded_episode_after_idle() { + let (_tx, rx) = mpsc::channel(1); + let queue = Arc::new(tokio::sync::Mutex::new(UsbApplicationQueue::new(rx))); + let gate = UsbTxGate::new(false, Arc::new(AtomicBool::new(false))); + let (mut inbound, _driver) = projected_inbound(); + inbound.attach_tx_gate(gate.clone()); + for (command, frame) in required_protocol_frames(USB_TEST_TARGET) { + inbound.project_frame(command, &frame); + } + let (_stop_tx, stop_rx) = oneshot::channel(); + let pump = tokio::spawn(run_usb_tx_pump( + queue, + UsbWriterHandle { + queue: UsbWriteQueue::new(1), + }, + Arc::new(AtomicU64::new(0)), + None, + gate.clone(), + stop_rx, + )); + tokio::task::yield_now().await; + tokio::time::advance(Duration::from_secs(60)).await; + inbound.project_frame(rnode::CMD_RESET, &[0xF8]); + let deadline = gate.readiness_deadline().unwrap(); + tokio::task::yield_now().await; + assert!(!pump.is_finished()); + tokio::time::advance(Duration::from_secs(9)).await; + assert!(!pump.is_finished()); + inbound.project_frame(rnode::CMD_RESET, &[0xF8]); + inbound.project_frame(rnode::CMD_FREQUENCY, &[1]); // Malformed evidence. + assert_eq!(gate.readiness_deadline(), Some(deadline)); + tokio::time::advance(Duration::from_secs(2)).await; + assert_eq!(pump.await.unwrap(), UsbTxPumpExit::ReadinessTimedOut); + assert!(!gate.can_send()); + } + + #[tokio::test(start_paused = true)] + async fn usb_readiness_episode_expires_even_while_rx_transport_is_backpressured() { + let (_tx, rx) = mpsc::channel(1); + let queue = Arc::new(tokio::sync::Mutex::new(UsbApplicationQueue::new(rx))); + let gate = UsbTxGate::new(false, Arc::new(AtomicBool::new(false))); + let (mut inbound, _driver) = projected_inbound(); + inbound.attach_tx_gate(gate.clone()); + for (command, frame) in required_protocol_frames(USB_TEST_TARGET) { + inbound.project_frame(command, &frame); + } + let (_stop_tx, stop_rx) = oneshot::channel(); + let pump = tokio::spawn(run_usb_tx_pump( + queue, + UsbWriterHandle { + queue: UsbWriteQueue::new(1), + }, + Arc::new(AtomicU64::new(0)), + None, + gate.clone(), + stop_rx, + )); + tokio::task::yield_now().await; + tokio::time::advance(Duration::from_secs(60)).await; + let (transport, _transport_rx) = mpsc::channel(1); + transport.try_send(TransportMessage::Shutdown).unwrap(); + let (_inbound_stop_tx, mut inbound_stop_rx) = mpsc::channel(1); + let mut bytes = Vec::new(); + kiss::frame_with_command_into(rnode::CMD_RESET, &[0xF8], &mut bytes); + kiss::frame_with_command_into(kiss::CMD_DATA, &[1, 2, 3], &mut bytes); + let received = AtomicU64::new(0); + let episode_start = tokio::time::Instant::now(); + tokio::time::timeout(USB_PROTOCOL_READINESS_DEADLINE * 2, async { + tokio::select! { + exit = pump => assert_eq!(exit.unwrap(), UsbTxPumpExit::ReadinessTimedOut), + result = forward_usb_read_chunk( + &mut inbound, &bytes, 1, &received, &transport, &mut inbound_stop_rx + ) => panic!("full transport queue cannot conclude before pump expiry: {result:?}"), + } + }) + .await + .expect("readiness episode did not expire while transport was backpressured"); + assert!(episode_start.elapsed() >= USB_PROTOCOL_READINESS_DEADLINE); + assert!(episode_start.elapsed() < USB_PROTOCOL_READINESS_DEADLINE + Duration::from_secs(1)); + assert!(!gate.can_send()); + } + + #[tokio::test(start_paused = true)] + async fn usb_control_deadline_includes_a_full_writer_queue() { + let writer = UsbWriterHandle { + queue: UsbWriteQueue::new(0), + }; + let error = writer + .request_before(UsbWritePhase::Detect, vec![1], Duration::from_millis(20)) + .await + .expect_err("queue pressure must not escape the control deadline"); + assert_eq!(error.kind, UsbWriteFailureKind::DeadlineElapsed); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn usb_unadmitted_pending_packet_survives_stop_and_requires_new_generation_ready() { + let (tx, rx) = mpsc::channel(2); + tx.send(Bytes::from_static(b"first")).await.unwrap(); + tx.send(Bytes::from_static(b"second")).await.unwrap(); + let queue = Arc::new(tokio::sync::Mutex::new(UsbApplicationQueue::new(rx))); + let counter = Arc::new(AtomicU64::new(0)); + let old_gate = ready_tx_gate(false); + let (stop_tx, stop_rx) = oneshot::channel(); + let pump = tokio::spawn(run_usb_tx_pump( + queue.clone(), + UsbWriterHandle { + queue: UsbWriteQueue::new(0), + }, + counter.clone(), + None, + old_gate.clone(), + stop_rx, + )); + tokio::time::sleep(Duration::from_millis(10)).await; + stop_tx.send(()).unwrap(); + assert_eq!(pump.await.unwrap(), UsbTxPumpExit::StopRequested); + assert_eq!( + queue.lock().await.pending.as_ref().unwrap().payload, + Bytes::from_static(b"first") + ); + + let writer = ScriptedWriter::new([]); + let calls = writer.calls.clone(); + let io = test_io(writer, Arc::new(Mutex::new(Vec::new()))); + let gate = UsbTxGate::new(false, Arc::new(AtomicBool::new(false))); + let (stop_tx, stop_rx) = oneshot::channel(); + let pump = tokio::spawn(run_usb_tx_pump( + queue, + io.writer.clone(), + counter.clone(), + None, + gate.clone(), + stop_rx, + )); + let mut fresh = RNodeProtocolState::new(USB_TEST_TARGET); + for (command, frame) in required_protocol_frames(USB_TEST_TARGET) { + fresh.apply_frame(command, &frame); + old_gate.observe(&fresh, command, &frame); + } + tokio::time::sleep(Duration::from_millis(10)).await; + assert!( + calls.lock().unwrap().is_empty(), + "old generation evidence must not admit retained data" + ); + assert!(!old_gate.is_ready()); + let (mut inbound, _driver) = projected_inbound(); + inbound.attach_tx_gate(gate); + for (command, frame) in required_protocol_frames(USB_TEST_TARGET) { + inbound.project_frame(command, &frame); + } + wait_for_count(&counter, 11).await; + assert_eq!( + calls + .lock() + .unwrap() + .iter() + .map(|(bytes, _)| bytes.clone()) + .collect::>(), + vec![kiss::frame(b"first"), kiss::frame(b"second")] + ); + stop_tx.send(()).unwrap(); + assert_eq!(pump.await.unwrap(), UsbTxPumpExit::StopRequested); + let _ = io + .shutdown(None, Duration::from_millis(20), Duration::from_secs(1)) + .await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn usb_failed_packet_write_is_not_counted_and_retains_complete_payload() { + let io = test_io( + ScriptedWriter::new([ + Ok(2), + Err(UsbTransferError::Backend("test write failed".into())), + ]), + Arc::new(Mutex::new(Vec::new())), + ); + let (tx, rx) = mpsc::channel(1); + tx.send(Bytes::from_static(b"retry")).await.unwrap(); + let queue = Arc::new(tokio::sync::Mutex::new(UsbApplicationQueue::new(rx))); + let counter = Arc::new(AtomicU64::new(0)); + let (_stop_tx, stop_rx) = oneshot::channel(); + let result = run_usb_tx_pump( + queue.clone(), + io.writer.clone(), + counter.clone(), + None, + ready_tx_gate(false), + stop_rx, + ) + .await; + assert!(matches!(result, UsbTxPumpExit::WriterRejected(_))); + assert_eq!(counter.load(Ordering::Relaxed), 0); + assert_eq!( + queue.lock().await.pending.as_ref().unwrap().payload, + Bytes::from_static(b"retry") + ); + assert!( + !queue + .lock() + .await + .pending + .as_ref() + .unwrap() + .completed + .load(Ordering::Acquire), + "a partial failed write cannot claim physical completion" + ); + let report = io + .shutdown(None, Duration::from_millis(20), Duration::from_secs(1)) + .await; + assert_eq!(report.report.disposition, UsbCleanupDisposition::Released); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn usb_writer_checks_generation_gate_at_physical_write_boundary() { + let io = test_io(ScriptedWriter::new([]), Arc::new(Mutex::new(Vec::new()))); + let gate = ready_tx_gate(false); + gate.close(); + let count = Arc::new(AtomicU64::new(0)); + let error = io + .writer + .write_application_packet( + &Bytes::from_static(b"stale"), + count.clone(), + gate, + Arc::new(AtomicBool::new(false)), + ) + .await + .expect_err("closed generation must reject writer-level packet admission"); + assert_eq!(error.kind, UsbWriteFailureKind::AdmissionClosed); + assert_eq!(count.load(Ordering::Relaxed), 0); + let _ = io + .shutdown(None, Duration::from_millis(20), Duration::from_secs(1)) + .await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn usb_tx_counter_waits_for_complete_physical_write_even_if_ack_is_dropped() { + let started = Arc::new(AtomicBool::new(false)); + let write_gate = Arc::new((Mutex::new(false), Condvar::new())); + let events = Arc::new(Mutex::new(Vec::new())); + let io = spawn_owned_usb_io( + GatedWriter { + calls: Arc::new(Mutex::new(Vec::new())), + first_started: started.clone(), + first_gate: write_gate.clone(), + }, + IdleReader { + polls: Arc::new(AtomicUsize::new(0)), + events: Some(events.clone()), + }, + RecordingOwner { + events, + release_result: Ok(()), + }, + Arc::new(AtomicBool::new(true)), + 8, + 8, + Duration::from_millis(100), + ); + let counter = Arc::new(AtomicU64::new(0)); + let acknowledgement = io + .writer + .queue_packet( + vec![0xAA], + 1, + counter.clone(), + Some(ready_tx_gate(false)), + None, + Arc::new(AtomicBool::new(false)), + ) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(1), async { + while !started.load(Ordering::Acquire) { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!( + counter.load(Ordering::Relaxed), + 0, + "active bulk transfer is not completion" + ); + drop(acknowledgement); + let (lock, wake) = &*write_gate; + *lock.lock().unwrap() = true; + wake.notify_all(); + wait_for_count(&counter, 1).await; + let _ = io + .shutdown(None, Duration::from_millis(20), Duration::from_secs(1)) + .await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn usb_late_complete_write_is_counted_once_and_not_replayed_after_join() { + struct ReleaseOnDrop(Arc<(Mutex, Condvar)>); + impl Drop for ReleaseOnDrop { + fn drop(&mut self) { + let (lock, wake) = &*self.0; + *lock.lock().unwrap() = true; + wake.notify_all(); + } + } + struct LatePacketWriter { + started: Arc, + release: Arc<(Mutex, Condvar)>, + } + impl UsbWriterBackend for LatePacketWriter { + fn transfer( + &mut self, + bytes: &[u8], + _timeout: Duration, + ) -> Result { + self.started.store(true, Ordering::Release); + let (lock, wake) = &*self.release; + let mut released = lock.lock().unwrap(); + while !*released { + released = wake.wait(released).unwrap(); + } + // Deliberately model a backend reporting positive completion + // later than its timeout, not an unknown/partial result. + Ok(bytes.len() as i32) + } + } + let started = Arc::new(AtomicBool::new(false)); + let release = Arc::new((Mutex::new(false), Condvar::new())); + let _release_on_failure = ReleaseOnDrop(release.clone()); + let events = Arc::new(Mutex::new(Vec::new())); + let old_io = spawn_owned_usb_io( + LatePacketWriter { + started: started.clone(), + release: release.clone(), + }, + IdleReader { + polls: Arc::new(AtomicUsize::new(0)), + events: Some(events.clone()), + }, + RecordingOwner { + events, + release_result: Ok(()), + }, + Arc::new(AtomicBool::new(true)), + 8, + 8, + Duration::from_millis(100), + ); + let (tx, rx) = mpsc::channel(2); + tx.send(Bytes::from_static(b"first")).await.unwrap(); + tx.send(Bytes::from_static(b"second")).await.unwrap(); + let queue = Arc::new(tokio::sync::Mutex::new(UsbApplicationQueue::new(rx))); + let counter = Arc::new(AtomicU64::new(0)); + let (_stop_tx, stop_rx) = oneshot::channel(); + let pump = tokio::spawn(run_usb_tx_pump( + queue.clone(), + old_io.writer.clone(), + counter.clone(), + None, + ready_tx_gate(false), + stop_rx, + )); + tokio::time::timeout(Duration::from_secs(1), async { + while !started.load(Ordering::Acquire) { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + let outcome = + tokio::time::timeout(USB_PACKET_WRITE_DEADLINE + Duration::from_secs(1), pump) + .await + .expect("caller deadline must remain bounded") + .unwrap(); + assert!(matches!( + outcome, + UsbTxPumpExit::WriterRejected(UsbWriteFailure { + kind: UsbWriteFailureKind::DeadlineElapsed, + .. + }) + )); + assert_eq!(counter.load(Ordering::Relaxed), 0); + let completed = queue + .lock() + .await + .pending + .as_ref() + .unwrap() + .completed + .clone(); + assert!(!completed.load(Ordering::Acquire)); + let (lock, wake) = &*release; + *lock.lock().unwrap() = true; + wake.notify_all(); + wait_for_count(&counter, 5).await; + let old_shutdown = old_io + .shutdown(None, Duration::from_millis(20), Duration::from_secs(1)) + .await; + assert_eq!( + old_shutdown.report.disposition, + UsbCleanupDisposition::Released + ); + assert!(completed.load(Ordering::Acquire)); + + // Only the fully joined old owner can hand its logical queue to a new + // generation. That generation must skip first, not transmit it twice. + let writer = ScriptedWriter::new([]); + let calls = writer.calls.clone(); + let new_io = test_io(writer, Arc::new(Mutex::new(Vec::new()))); + let gate = UsbTxGate::new(false, Arc::new(AtomicBool::new(false))); + let (mut inbound, _driver) = projected_inbound(); + inbound.attach_tx_gate(gate.clone()); + let (stop_tx, stop_rx) = oneshot::channel(); + let pump = tokio::spawn(run_usb_tx_pump( + queue, + new_io.writer.clone(), + counter.clone(), + None, + gate, + stop_rx, + )); + tokio::task::yield_now().await; + assert!(calls.lock().unwrap().is_empty()); + for (command, frame) in required_protocol_frames(USB_TEST_TARGET) { + inbound.project_frame(command, &frame); + } + wait_for_count(&counter, 11).await; + assert_eq!( + calls + .lock() + .unwrap() + .iter() + .map(|(bytes, _)| bytes.clone()) + .collect::>(), + vec![kiss::frame(b"second")] + ); + stop_tx.send(()).unwrap(); + assert_eq!(pump.await.unwrap(), UsbTxPumpExit::StopRequested); + let _ = new_io + .shutdown(None, Duration::from_millis(20), Duration::from_secs(1)) + .await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn ordinary_usb_startup_discards_preinit_rf_ready_and_partial_frames() { + struct PreinitReader(Option>); + impl UsbReaderBackend for PreinitReader { + fn read(&mut self) -> Result { + if let Some(bytes) = self.0.take() { + return Ok(UsbReadResult::Data(bytes)); + } + std::thread::sleep(Duration::from_millis(1)); + Ok(UsbReadResult::Idle) + } + } + let mut stale = framed_protocol_frames(required_protocol_frames(USB_TEST_TARGET)); + kiss::frame_with_command_into(rnode::CMD_READY, &[1], &mut stale); + stale.extend_from_slice(&[kiss::FEND, rnode::CMD_FREQUENCY, 0x36]); + let events = Arc::new(Mutex::new(Vec::new())); + let mut io = spawn_owned_usb_io( + ScriptedWriter::new([]), + PreinitReader(Some(stale)), + RecordingOwner { + events, + release_result: Ok(()), + }, + Arc::new(AtomicBool::new(true)), + 8, + 8, + Duration::from_millis(100), + ); + let seed = run_usb_rnode_startup( + &mut io, + USB_TEST_TARGET, + vec![1], + vec![2], + Duration::from_secs(1), + ) + .await + .unwrap(); + assert!(seed.evidence().detected); + assert!(seed.evidence().firmware.is_some()); + assert_eq!(seed.evidence().frequency, None); + assert!(!seed.flow_permission_observed()); + assert_ne!(seed.readiness(), RNodeReadiness::Ready); + let (mut publisher, _driver) = + rnode::new_rnode_driver_observation(rnode::RNodeTransportClass::Usb); + publisher.connection_established(); + let mut inbound = UsbInboundState::projected_with_protocol_state(seed, publisher); + let gate = UsbTxGate::new(false, Arc::new(AtomicBool::new(false))); + inbound.attach_tx_gate(gate.clone()); + assert!(!gate.can_send()); + for (command, frame) in required_protocol_frames(USB_TEST_TARGET) + .into_iter() + .skip(2) + { + inbound.project_frame(command, &frame); + } + assert!( + gate.can_send(), + "only fresh post-init RF echoes complete readiness" + ); + let _ = io + .shutdown(None, Duration::from_millis(20), Duration::from_secs(1)) + .await; + } + fn required_protocol_frames(target: RNodeProtocolTarget) -> [(u8, Vec); 8] { [ (rnode::CMD_DETECT, vec![rnode::DETECT_RESP]), @@ -2105,8 +3211,8 @@ mod tests { let writer = ScriptedWriter::new([]); let calls = writer.calls.clone(); let events = Arc::new(Mutex::new(Vec::new())); - let io = test_io(writer, events); - let transmitted = AtomicU64::new(0); + let mut io = test_io(writer, events); + let transmitted = Arc::new(AtomicU64::new(0)); let mut config = rnode::RNodeConfig::new("android-usb-test", "/dev/bus/usb/test"); config.frequency = USB_TEST_TARGET.frequency; @@ -2118,7 +3224,8 @@ mod tests { let init = rnode::build_init_sequence(&config); run_usb_rnode_startup( - &io.writer, + &mut io, + USB_TEST_TARGET, detect.clone(), init.clone(), Duration::from_secs(1), @@ -2136,7 +3243,10 @@ mod tests { io.writer .queue_packet_and_account(packet.clone(), &transmitted) .await - .expect("packet should be admitted after startup"); + .expect("packet should be admitted after startup") + .await + .expect("writer acknowledgement") + .expect("packet write"); assert_eq!( transmitted.load(Ordering::Relaxed), packet.len() as u64, @@ -2783,8 +3893,10 @@ mod tests { } #[tokio::test] - async fn cmd_ready_is_observation_only_and_does_not_gate_tx_admission() { + async fn cmd_ready_diagnostics_do_not_substitute_for_protocol_readiness() { let (mut inbound, driver) = projected_inbound(); + let gate = UsbTxGate::new(false, Arc::new(AtomicBool::new(false))); + inbound.attach_tx_gate(gate.clone()); let mut ready_blocked = Vec::new(); kiss::frame_with_command_into(rnode::CMD_READY, &[0], &mut ready_blocked); let (_stop_tx, mut stop_rx) = mpsc::channel(1); @@ -2807,15 +3919,10 @@ mod tests { rnode::RNodeTransmitFlowState::Blocked ); - let writer = UsbWriterHandle { - queue: UsbWriteQueue::new(1), - }; - let transmitted = AtomicU64::new(0); - writer - .queue_packet_and_account(vec![1, 2, 3], &transmitted) - .await - .expect("observed CMD_READY=false must not gate USB packet admission"); - assert_eq!(transmitted.load(Ordering::Relaxed), 3); + assert!( + !gate.can_send(), + "flow-control off still requires typed readiness" + ); } #[tokio::test] @@ -2976,12 +4083,15 @@ mod tests { let calls = writer.calls.clone(); let events = Arc::new(Mutex::new(Vec::new())); let io = test_io(writer, events); - let transmitted = AtomicU64::new(0); + let transmitted = Arc::new(AtomicU64::new(0)); for packet in [vec![1], vec![2, 2], vec![3, 3, 3]] { io.writer .queue_packet_and_account(packet, &transmitted) .await - .expect("packet queue"); + .expect("packet queue") + .await + .expect("writer acknowledgement") + .expect("packet write"); } assert_eq!(transmitted.load(Ordering::Relaxed), 6); tokio::time::timeout(Duration::from_secs(1), async { @@ -3139,7 +4249,7 @@ mod tests { 8, Duration::from_millis(100), ); - let transmitted = AtomicU64::new(0); + let transmitted = Arc::new(AtomicU64::new(0)); io.writer .queue_packet_and_account(vec![0xAA], &transmitted) .await @@ -3227,6 +4337,7 @@ mod tests { deadline: Some(Instant::now() + Duration::from_millis(15)), acknowledgement: None, await_terminal_detach_on_failure: false, + packet: None, _permit: None, }; let error = write_request( @@ -3355,17 +4466,19 @@ mod tests { }); let (application_tx, application_rx) = mpsc::channel(1); - let application_rx = Arc::new(tokio::sync::Mutex::new(application_rx)); + let application_rx = Arc::new(tokio::sync::Mutex::new(UsbApplicationQueue::new( + application_rx, + ))); let (pump_stop_tx, pump_stop_rx) = oneshot::channel(); let transmitted = Arc::new(AtomicU64::new(0)); - let expected_frame_length = kiss::frame(&[4, 5, 6]).len() as u64; + let expected_frame_length = 3; + let io = test_io(ScriptedWriter::new([]), Arc::new(Mutex::new(Vec::new()))); let pump = tokio::spawn(run_usb_tx_pump( application_rx, - UsbWriterHandle { - queue: UsbWriteQueue::new(1), - }, + io.writer.clone(), transmitted.clone(), None, + ready_tx_gate(false), pump_stop_rx, )); application_tx @@ -3389,12 +4502,17 @@ mod tests { ); let _ = pump_stop_tx.send(()); assert_eq!(pump.await.expect("pump join"), UsbTxPumpExit::StopRequested); + let _ = io + .shutdown(None, Duration::from_millis(20), Duration::from_secs(1)) + .await; } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn application_queue_survives_sequential_usb_generations() { let (application_tx, application_rx) = mpsc::channel(2); - let application_rx = Arc::new(tokio::sync::Mutex::new(application_rx)); + let application_rx = Arc::new(tokio::sync::Mutex::new(UsbApplicationQueue::new( + application_rx, + ))); let transmitted = Arc::new(AtomicU64::new(0)); let (first_stop_tx, first_stop_rx) = oneshot::channel(); @@ -3405,6 +4523,7 @@ mod tests { }, transmitted.clone(), None, + ready_tx_gate(false), first_stop_rx, )); first_stop_tx.send(()).expect("stop first generation"); @@ -3414,20 +4533,20 @@ mod tests { ); let payload = Bytes::from_static(&[4, 2, 4, 2]); - let expected_frame_length = kiss::frame(&payload).len() as u64; + let expected_frame_length = payload.len() as u64; application_tx .send(payload) .await .expect("queue payload between generations"); let (second_stop_tx, second_stop_rx) = oneshot::channel(); + let io = test_io(ScriptedWriter::new([]), Arc::new(Mutex::new(Vec::new()))); let second_pump = tokio::spawn(run_usb_tx_pump( application_rx, - UsbWriterHandle { - queue: UsbWriteQueue::new(1), - }, + io.writer.clone(), transmitted.clone(), None, + ready_tx_gate(false), second_stop_rx, )); tokio::time::timeout(Duration::from_secs(1), async { @@ -3443,24 +4562,29 @@ mod tests { second_pump.await.expect("second pump join"), UsbTxPumpExit::StopRequested ); + let _ = io + .shutdown(None, Duration::from_millis(20), Duration::from_secs(1)) + .await; } #[tokio::test] async fn android_usb_station_id_is_armed_only_after_application_tx() { let (application_tx, application_rx) = mpsc::channel(1); - let application_rx = Arc::new(tokio::sync::Mutex::new(application_rx)); + let application_rx = Arc::new(tokio::sync::Mutex::new(UsbApplicationQueue::new( + application_rx, + ))); let transmitted = Arc::new(AtomicU64::new(0)); let (stop_tx, stop_rx) = oneshot::channel(); let payload = Bytes::from_static(b"payload"); let callsign = Bytes::from_static(b"N0CALL"); - let expected = (kiss::frame(&payload).len() + kiss::frame(&callsign).len()) as u64; + let expected = (payload.len() + callsign.len()) as u64; + let io = test_io(ScriptedWriter::new([]), Arc::new(Mutex::new(Vec::new()))); let pump = tokio::spawn(run_usb_tx_pump( application_rx, - UsbWriterHandle { - queue: UsbWriteQueue::new(2), - }, + io.writer.clone(), transmitted.clone(), Some((Duration::ZERO, callsign)), + ready_tx_gate(false), stop_rx, )); assert_eq!(transmitted.load(Ordering::Relaxed), 0); @@ -3474,12 +4598,17 @@ mod tests { .expect("station ID did not follow application TX"); let _ = stop_tx.send(()); assert_eq!(pump.await.expect("pump join"), UsbTxPumpExit::StopRequested); + let _ = io + .shutdown(None, Duration::from_millis(20), Duration::from_secs(1)) + .await; } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn blocked_tx_admission_does_not_stall_inbound_forwarding() { let (application_tx, application_rx) = mpsc::channel(1); - let application_rx = Arc::new(tokio::sync::Mutex::new(application_rx)); + let application_rx = Arc::new(tokio::sync::Mutex::new(UsbApplicationQueue::new( + application_rx, + ))); let (pump_stop_tx, pump_stop_rx) = oneshot::channel(); let transmitted = Arc::new(AtomicU64::new(0)); let pump = tokio::spawn(run_usb_tx_pump( @@ -3489,6 +4618,7 @@ mod tests { }, transmitted.clone(), None, + ready_tx_gate(false), pump_stop_rx, )); application_tx @@ -3779,7 +4909,7 @@ mod tests { Duration::from_millis(100), ); io.writer - .queue_packet_and_account(vec![0xAA], &AtomicU64::new(0)) + .queue_packet_and_account(vec![0xAA], &Arc::new(AtomicU64::new(0))) .await .expect("writer admission"); @@ -3879,7 +5009,7 @@ mod tests { let rejected_writer = UsbWriterHandle { queue: rejected_queue, }; - let rejected_bytes = AtomicU64::new(0); + let rejected_bytes = Arc::new(AtomicU64::new(0)); assert!( rejected_writer .queue_packet_and_account(vec![1, 2, 3], &rejected_bytes) @@ -3891,7 +5021,7 @@ mod tests { let blocked_writer = UsbWriterHandle { queue: UsbWriteQueue::new(0), }; - let preempted_bytes = AtomicU64::new(0); + let preempted_bytes = Arc::new(AtomicU64::new(0)); let (stop_tx, mut stop_rx) = mpsc::channel(1); stop_tx.send(()).await.expect("stop signal"); let admitted = tokio::select! {