386 lines
16 KiB
Rust
386 lines
16 KiB
Rust
//! USB reset and eye-hub coverage for server main relay branches.
|
|
//!
|
|
//! Scope: include `server/src/main.rs` and exercise USB recovery plus shared
|
|
//! eye-feed hub behavior with synthetic endpoints.
|
|
//! Targets: `server/src/main.rs`.
|
|
//! Why: USB recovery and shared downstream video hubs are operational escape
|
|
//! hatches; regressions here can leave HID or eye feeds unavailable.
|
|
|
|
#[allow(warnings)]
|
|
mod server_main_binary_extra {
|
|
include!(env!("LESAVKA_SERVER_MAIN_SRC"));
|
|
|
|
use futures_util::stream;
|
|
use lesavka_common::lesavka::relay_client::RelayClient;
|
|
use serial_test::serial;
|
|
use std::os::unix::fs::PermissionsExt;
|
|
use std::path::Path;
|
|
use temp_env::with_var;
|
|
use tempfile::tempdir;
|
|
|
|
async fn connect_with_retry(addr: std::net::SocketAddr) -> tonic::transport::Channel {
|
|
let endpoint = tonic::transport::Endpoint::from_shared(format!("http://{addr}"))
|
|
.expect("endpoint")
|
|
.tcp_nodelay(true);
|
|
for _ in 0..40 {
|
|
if let Ok(channel) = endpoint.clone().connect().await {
|
|
return channel;
|
|
}
|
|
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
|
|
}
|
|
panic!("failed to connect to local tonic server");
|
|
}
|
|
|
|
fn write_file(path: &Path, content: &str) {
|
|
if let Some(parent) = path.parent() {
|
|
std::fs::create_dir_all(parent).expect("create parent");
|
|
}
|
|
std::fs::write(path, content).expect("write file");
|
|
}
|
|
|
|
fn with_fake_gadget_roots(sys_root: &Path, cfg_root: &Path, f: impl FnOnce()) {
|
|
let sys_root = sys_root.to_string_lossy().to_string();
|
|
let cfg_root = cfg_root.to_string_lossy().to_string();
|
|
with_var("LESAVKA_GADGET_SYSFS_ROOT", Some(sys_root), || {
|
|
with_var("LESAVKA_GADGET_CONFIGFS_ROOT", Some(cfg_root), f);
|
|
});
|
|
}
|
|
|
|
fn with_capture_power_disabled(f: impl FnOnce()) {
|
|
with_var("LESAVKA_CAPTURE_POWER_UNIT", Some("none"), f);
|
|
}
|
|
|
|
fn build_fake_gadget_tree(base: &Path, ctrl: &str, gadget_name: &str, state: &str) {
|
|
write_file(
|
|
&base.join(format!("sys/class/udc/{ctrl}/state")),
|
|
&format!("{state}\n"),
|
|
);
|
|
write_file(
|
|
&base.join(format!("cfg/{gadget_name}/UDC")),
|
|
&format!("{ctrl}\n"),
|
|
);
|
|
write_file(&base.join("sys/bus/platform/drivers/dwc3/unbind"), "");
|
|
write_file(&base.join("sys/bus/platform/drivers/dwc3/bind"), "");
|
|
}
|
|
|
|
fn write_helper(path: &Path, body: &str) {
|
|
write_file(path, body);
|
|
let mut perms = std::fs::metadata(path)
|
|
.expect("helper metadata")
|
|
.permissions();
|
|
perms.set_mode(0o755);
|
|
std::fs::set_permissions(path, perms).expect("chmod helper");
|
|
}
|
|
|
|
fn with_fast_usb_recovery(helper: &Path, f: impl FnOnce()) {
|
|
let helper = helper.to_string_lossy().to_string();
|
|
with_var("LESAVKA_CORE_HELPER", Some(helper), || {
|
|
with_var("LESAVKA_USB_RECOVERY_CYCLE_WAIT_MS", Some("0"), || {
|
|
with_var("LESAVKA_USB_RECOVERY_REBUILD_WAIT_MS", Some("0"), || {
|
|
with_var("LESAVKA_USB_RECOVERY_FINAL_WAIT_MS", Some("0"), f);
|
|
})
|
|
})
|
|
});
|
|
}
|
|
|
|
fn build_handler_for_tests_with_modes(
|
|
kb_writable: bool,
|
|
ms_writable: bool,
|
|
) -> (tempfile::TempDir, Handler) {
|
|
let dir = tempdir().expect("tempdir");
|
|
let kb_path = dir.path().join("hidg0.bin");
|
|
let ms_path = dir.path().join("hidg1.bin");
|
|
std::fs::write(&kb_path, []).expect("create kb file");
|
|
std::fs::write(&ms_path, []).expect("create ms file");
|
|
|
|
let kb_std = std::fs::OpenOptions::new()
|
|
.read(true)
|
|
.write(kb_writable)
|
|
.create(kb_writable)
|
|
.truncate(kb_writable)
|
|
.open(&kb_path)
|
|
.expect("open kb");
|
|
let ms_std = std::fs::OpenOptions::new()
|
|
.read(true)
|
|
.write(ms_writable)
|
|
.create(ms_writable)
|
|
.truncate(ms_writable)
|
|
.open(&ms_path)
|
|
.expect("open ms");
|
|
let kb = tokio::fs::File::from_std(kb_std);
|
|
let ms = tokio::fs::File::from_std(ms_std);
|
|
|
|
(
|
|
dir,
|
|
Handler {
|
|
kb: std::sync::Arc::new(tokio::sync::Mutex::new(Some(kb))),
|
|
ms: std::sync::Arc::new(tokio::sync::Mutex::new(Some(ms))),
|
|
gadget: UsbGadget::new("lesavka"),
|
|
did_cycle: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
|
|
camera_rt: std::sync::Arc::new(CameraRuntime::new()),
|
|
capture_power: CapturePowerManager::new(),
|
|
eye_hubs: std::sync::Arc::new(tokio::sync::Mutex::new(
|
|
std::collections::HashMap::new(),
|
|
)),
|
|
},
|
|
)
|
|
}
|
|
|
|
fn build_handler_for_tests() -> (tempfile::TempDir, Handler) {
|
|
build_handler_for_tests_with_modes(true, true)
|
|
}
|
|
|
|
#[test]
|
|
#[serial]
|
|
fn reset_usb_reports_host_not_attached_after_fake_cycle() {
|
|
let dir = tempdir().expect("tempdir");
|
|
let hid_dir = dir.path().join("hid");
|
|
std::fs::create_dir_all(&hid_dir).expect("create hid dir");
|
|
std::fs::write(hid_dir.join("hidg0"), "").expect("create hidg0");
|
|
std::fs::write(hid_dir.join("hidg1"), "").expect("create hidg1");
|
|
build_fake_gadget_tree(dir.path(), "fake-ctrl.usb", "lesavka", "not attached");
|
|
let helper = dir.path().join("noop-core.sh");
|
|
write_helper(
|
|
&helper,
|
|
r#"#!/usr/bin/env bash
|
|
set -euo pipefail
|
|
echo noop core helper >&2
|
|
"#,
|
|
);
|
|
|
|
with_fake_gadget_roots(&dir.path().join("sys"), &dir.path().join("cfg"), || {
|
|
with_var(
|
|
"LESAVKA_HID_DIR",
|
|
Some(hid_dir.to_string_lossy().to_string()),
|
|
|| {
|
|
with_fast_usb_recovery(&helper, || {
|
|
let kb = tokio::fs::File::from_std(
|
|
std::fs::OpenOptions::new()
|
|
.read(true)
|
|
.write(true)
|
|
.open(hid_dir.join("hidg0"))
|
|
.expect("open hidg0"),
|
|
);
|
|
let ms = tokio::fs::File::from_std(
|
|
std::fs::OpenOptions::new()
|
|
.read(true)
|
|
.write(true)
|
|
.open(hid_dir.join("hidg1"))
|
|
.expect("open hidg1"),
|
|
);
|
|
let handler = Handler {
|
|
kb: std::sync::Arc::new(tokio::sync::Mutex::new(Some(kb))),
|
|
ms: std::sync::Arc::new(tokio::sync::Mutex::new(Some(ms))),
|
|
gadget: UsbGadget::new("lesavka"),
|
|
did_cycle: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(
|
|
false,
|
|
)),
|
|
camera_rt: std::sync::Arc::new(CameraRuntime::new()),
|
|
capture_power: CapturePowerManager::new(),
|
|
eye_hubs: std::sync::Arc::new(tokio::sync::Mutex::new(
|
|
std::collections::HashMap::new(),
|
|
)),
|
|
};
|
|
let rt = tokio::runtime::Runtime::new().expect("runtime");
|
|
let err = rt
|
|
.block_on(async {
|
|
handler.reset_usb(tonic::Request::new(Empty {})).await
|
|
})
|
|
.expect_err("reset usb should report a host that never enumerates");
|
|
assert_eq!(err.code(), tonic::Code::FailedPrecondition);
|
|
assert!(
|
|
err.message().contains("still not attached"),
|
|
"unexpected reset error: {}",
|
|
err.message()
|
|
);
|
|
});
|
|
},
|
|
);
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
#[serial]
|
|
fn reset_usb_forced_rebuild_can_recover_unattached_fake_udc() {
|
|
let dir = tempdir().expect("tempdir");
|
|
let hid_dir = dir.path().join("hid");
|
|
std::fs::create_dir_all(&hid_dir).expect("create hid dir");
|
|
std::fs::write(hid_dir.join("hidg0"), "").expect("create hidg0");
|
|
std::fs::write(hid_dir.join("hidg1"), "").expect("create hidg1");
|
|
build_fake_gadget_tree(dir.path(), "fake-ctrl.usb", "lesavka", "not attached");
|
|
let helper = dir.path().join("recover-core.sh");
|
|
write_helper(
|
|
&helper,
|
|
r#"#!/usr/bin/env bash
|
|
set -euo pipefail
|
|
echo recover core helper >&2
|
|
printf 'configured\n' > "$LESAVKA_GADGET_SYSFS_ROOT/class/udc/fake-ctrl.usb/state"
|
|
"#,
|
|
);
|
|
|
|
with_fake_gadget_roots(&dir.path().join("sys"), &dir.path().join("cfg"), || {
|
|
with_var(
|
|
"LESAVKA_HID_DIR",
|
|
Some(hid_dir.to_string_lossy().to_string()),
|
|
|| {
|
|
with_fast_usb_recovery(&helper, || {
|
|
let kb = tokio::fs::File::from_std(
|
|
std::fs::OpenOptions::new()
|
|
.read(true)
|
|
.write(true)
|
|
.open(hid_dir.join("hidg0"))
|
|
.expect("open hidg0"),
|
|
);
|
|
let ms = tokio::fs::File::from_std(
|
|
std::fs::OpenOptions::new()
|
|
.read(true)
|
|
.write(true)
|
|
.open(hid_dir.join("hidg1"))
|
|
.expect("open hidg1"),
|
|
);
|
|
let handler = Handler {
|
|
kb: std::sync::Arc::new(tokio::sync::Mutex::new(Some(kb))),
|
|
ms: std::sync::Arc::new(tokio::sync::Mutex::new(Some(ms))),
|
|
gadget: UsbGadget::new("lesavka"),
|
|
did_cycle: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(
|
|
false,
|
|
)),
|
|
camera_rt: std::sync::Arc::new(CameraRuntime::new()),
|
|
capture_power: CapturePowerManager::new(),
|
|
eye_hubs: std::sync::Arc::new(tokio::sync::Mutex::new(
|
|
std::collections::HashMap::new(),
|
|
)),
|
|
};
|
|
let rt = tokio::runtime::Runtime::new().expect("runtime");
|
|
let reply = rt
|
|
.block_on(async {
|
|
handler.reset_usb(tonic::Request::new(Empty {})).await
|
|
})
|
|
.expect("reset usb should recover fake host")
|
|
.into_inner();
|
|
assert!(reply.ok);
|
|
});
|
|
},
|
|
);
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn shared_eye_hub_forwards_inner_packets() {
|
|
let rt = tokio::runtime::Runtime::new().expect("runtime");
|
|
with_capture_power_disabled(|| {
|
|
rt.block_on(async {
|
|
let lease = CapturePowerManager::new().acquire().await;
|
|
let packet = VideoPacket {
|
|
id: 2,
|
|
pts: 42,
|
|
data: vec![9, 8, 7],
|
|
..Default::default()
|
|
};
|
|
let (packet_tx, packet_rx) = tokio::sync::mpsc::channel(1);
|
|
let hub = EyeHub::spawn(ReceiverStream::new(packet_rx), lease);
|
|
hub.subscribers
|
|
.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
|
|
let mut rx = hub.tx.subscribe();
|
|
packet_tx
|
|
.send(Ok(packet.clone()))
|
|
.await
|
|
.expect("send synthetic packet");
|
|
let observed = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())
|
|
.await
|
|
.expect("hub packet timeout")
|
|
.expect("hub packet");
|
|
assert_eq!(observed.id, packet.id);
|
|
assert_eq!(observed.pts, packet.pts);
|
|
assert_eq!(observed.data, packet.data);
|
|
drop(packet_tx);
|
|
for _ in 0..20 {
|
|
if !hub.running.load(std::sync::atomic::Ordering::Relaxed) {
|
|
return;
|
|
}
|
|
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
|
}
|
|
assert!(
|
|
!hub.running.load(std::sync::atomic::Ordering::Relaxed),
|
|
"hub should stop after the synthetic packet stream closes"
|
|
);
|
|
});
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn conflicting_eye_hubs_for_the_same_source_are_pruned_before_reopen() {
|
|
let rt = tokio::runtime::Runtime::new().expect("runtime");
|
|
with_capture_power_disabled(|| {
|
|
rt.block_on(async {
|
|
let requested_key = EyeHubKey {
|
|
source_id: 1,
|
|
requested_width: 1280,
|
|
requested_height: 720,
|
|
requested_fps: 60,
|
|
};
|
|
let stale_same_source_key = EyeHubKey {
|
|
source_id: 1,
|
|
requested_width: 1920,
|
|
requested_height: 1080,
|
|
requested_fps: 60,
|
|
};
|
|
let keep_other_source_key = EyeHubKey {
|
|
source_id: 0,
|
|
requested_width: 1920,
|
|
requested_height: 1080,
|
|
requested_fps: 60,
|
|
};
|
|
let stale_same_source = EyeHub::spawn(
|
|
stream::pending::<Result<VideoPacket, tonic::Status>>(),
|
|
CapturePowerManager::new().acquire().await,
|
|
);
|
|
let stopped_other_source = EyeHub::spawn(
|
|
stream::pending::<Result<VideoPacket, tonic::Status>>(),
|
|
CapturePowerManager::new().acquire().await,
|
|
);
|
|
stopped_other_source.shutdown();
|
|
let keep_other_source = EyeHub::spawn(
|
|
stream::pending::<Result<VideoPacket, tonic::Status>>(),
|
|
CapturePowerManager::new().acquire().await,
|
|
);
|
|
|
|
let mut hubs = std::collections::HashMap::new();
|
|
hubs.insert(stale_same_source_key, stale_same_source.clone());
|
|
hubs.insert(
|
|
EyeHubKey {
|
|
source_id: 0,
|
|
requested_width: 1280,
|
|
requested_height: 720,
|
|
requested_fps: 60,
|
|
},
|
|
stopped_other_source,
|
|
);
|
|
hubs.insert(keep_other_source_key, keep_other_source.clone());
|
|
|
|
let removed = take_conflicting_eye_hubs(&mut hubs, requested_key);
|
|
|
|
assert_eq!(removed.len(), 2);
|
|
assert!(!hubs.contains_key(&stale_same_source_key));
|
|
assert!(hubs.contains_key(&keep_other_source_key));
|
|
});
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn eye_hub_shutdown_marks_the_hub_as_not_running() {
|
|
let rt = tokio::runtime::Runtime::new().expect("runtime");
|
|
with_capture_power_disabled(|| {
|
|
rt.block_on(async {
|
|
let hub = EyeHub::spawn(
|
|
stream::pending::<Result<VideoPacket, tonic::Status>>(),
|
|
CapturePowerManager::new().acquire().await,
|
|
);
|
|
assert!(hub.running.load(std::sync::atomic::Ordering::Relaxed));
|
|
hub.shutdown();
|
|
assert!(!hub.running.load(std::sync::atomic::Ordering::Relaxed));
|
|
});
|
|
});
|
|
}
|
|
}
|