use alloc::collections::VecDeque;
use alloc::vec::Vec;
use core::future::Future;
use core::pin::pin;
use core::task::{Context, Poll, Waker};
use bytes::BytesMut;
use crate::base::channel::ChannelId;
use crate::base::connection::Connection;
use crate::base::protocol::command::Command;
use crate::base::protocol::Packet;
use crate::base::protocol::{command, Checksum};
#[derive(Debug, PartialEq, Eq)]
pub struct MockError;
impl core::fmt::Display for MockError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("mock transport error")
}
}
impl embedded_io::Error for MockError {
fn kind(&self) -> embedded_io::ErrorKind {
embedded_io::ErrorKind::Other
}
}
pub(crate) struct Mock {
inbound: VecDeque<u8>,
writes: Vec<Vec<u8>>,
stall_write: Option<usize>,
slow_reads: usize,
cancel_safe: bool,
}
impl Mock {
pub(crate) fn new() -> Self {
Self {
inbound: VecDeque::new(),
writes: Vec::new(),
stall_write: None,
slow_reads: 0,
cancel_safe: true,
}
}
pub(crate) fn feed(&mut self, pkt: &Packet) -> &mut Self {
let mut buf = BytesMut::new();
pkt.encode(&mut buf, Checksum::Compute).unwrap();
self.inbound.extend(buf.iter().copied());
self
}
pub(crate) fn slow_reads(&mut self, n: usize) -> &mut Self {
self.slow_reads = n;
self
}
pub(crate) fn loses_cancelled_reads(&mut self) -> &mut Self {
self.cancel_safe = false;
self
}
pub(crate) fn stall_write(&mut self, index: usize) -> &mut Self {
self.stall_write = Some(index);
self
}
}
impl embedded_io::ErrorType for Mock {
type Error = MockError;
}
impl Mock {
fn pull(&mut self, buf: &mut [u8]) -> usize {
let n = buf.len().min(self.inbound.len());
for slot in buf.iter_mut().take(n) {
*slot = self.inbound.pop_front().unwrap();
}
n
}
fn stalls_now(&self) -> bool {
self.stall_write == Some(self.writes.len())
}
fn push(&mut self, buf: &[u8]) -> usize {
self.writes.push(buf.to_vec());
buf.len()
}
}
impl embedded_io_async::Read for Mock {
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, MockError> {
if self.slow_reads > 0 {
self.slow_reads -= 1;
park_once().await;
}
Ok(self.pull(buf))
}
}
impl crate::transport::ReadCancelSafety for Mock {
fn read_cancel_safe(&self) -> bool {
self.cancel_safe
}
}
async fn park_once() {
let mut done = false;
core::future::poll_fn(move |cx| {
if done {
core::task::Poll::Ready(())
} else {
done = true;
cx.waker().wake_by_ref();
core::task::Poll::Pending
}
})
.await
}
impl embedded_io_async::Write for Mock {
async fn write(&mut self, buf: &[u8]) -> Result<usize, MockError> {
if self.stalls_now() {
core::future::pending::<()>().await;
}
Ok(self.push(buf))
}
async fn flush(&mut self) -> Result<(), MockError> {
Ok(())
}
}
#[cfg(feature = "split")]
#[derive(Clone)]
pub(crate) struct SharedMock(alloc::sync::Arc<std::sync::Mutex<Mock>>);
#[cfg(feature = "split")]
impl SharedMock {
pub(crate) fn acks_for(&self, local_id: u32) -> Vec<u32> {
self.lock().acks_for(local_id)
}
pub(crate) fn sent(&self) -> Vec<(Command, u32, u32, Vec<u8>)> {
self.lock().sent()
}
pub(crate) fn feed(&self, pkt: &Packet) {
self.lock().feed(pkt);
}
pub(crate) fn new(mock: Mock) -> Self {
Self(alloc::sync::Arc::new(std::sync::Mutex::new(mock)))
}
fn lock(&self) -> std::sync::MutexGuard<'_, Mock> {
self.0.lock().unwrap_or_else(|p| p.into_inner())
}
}
#[cfg(feature = "split")]
impl embedded_io::ErrorType for SharedMock {
type Error = MockError;
}
#[cfg(feature = "split")]
impl embedded_io_async::Read for SharedMock {
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, MockError> {
Ok(self.lock().pull(buf))
}
}
#[cfg(feature = "split")]
impl embedded_io_async::Write for SharedMock {
async fn write(&mut self, buf: &[u8]) -> Result<usize, MockError> {
if self.lock().stalls_now() {
core::future::pending::<()>().await;
}
Ok(self.lock().push(buf))
}
async fn flush(&mut self) -> Result<(), MockError> {
Ok(())
}
}
#[cfg(feature = "split")]
impl crate::transport::Splittable for SharedMock {
type ReadHalf = SharedMock;
type WriteHalf = SharedMock;
fn split(self) -> Result<(Self::ReadHalf, Self::WriteHalf), MockError> {
Ok((self.clone(), self))
}
}
impl Mock {
pub(crate) fn sent(&self) -> Vec<(Command, u32, u32, Vec<u8>)> {
let mut stream: Vec<u8> = Vec::new();
for w in &self.writes {
stream.extend_from_slice(w);
}
let mut out = Vec::new();
let mut pos = 0;
while pos + 24 <= stream.len() {
let word = |at: usize| {
u32::from_le_bytes([stream[at], stream[at + 1], stream[at + 2], stream[at + 3]])
};
let command = Command::try_from(word(pos)).expect("valid command");
let (arg0, arg1) = (word(pos + 4), word(pos + 8));
let len = word(pos + 12) as usize;
pos += 24;
let payload = stream[pos..pos + len].to_vec();
pos += len;
out.push((command, arg0, arg1, payload));
}
out
}
pub(crate) fn acks_for(&self, local_id: u32) -> Vec<u32> {
self.sent()
.into_iter()
.filter(|(cmd, arg0, _, _)| *cmd == Command::Ready && *arg0 == local_id)
.map(|(_, _, _, payload)| {
if payload.len() >= 4 {
u32::from_le_bytes([payload[0], payload[1], payload[2], payload[3]])
} else {
0
}
})
.collect()
}
}
pub(crate) fn now<F: Future>(fut: F) -> F::Output {
let mut fut = pin!(fut);
let mut cx = Context::from_waker(Waker::noop());
for _ in 0..64 {
if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
return v;
}
}
panic!("future never finished against the mock transport");
}
pub(crate) fn abandon<F: Future>(fut: F) {
let mut fut = pin!(fut);
let mut cx = Context::from_waker(Waker::noop());
for _ in 0..8 {
if fut.as_mut().poll(&mut cx).is_ready() {
panic!("future finished; it was supposed to stall");
}
}
}
pub(crate) struct NoAuth;
pub(crate) struct NoKey;
impl core::fmt::Display for NoKey {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("no key")
}
}
impl crate::auth::Authenticator for NoAuth {
type Error = NoKey;
async fn sign(&mut self, _token: &[u8]) -> Result<Vec<u8>, NoKey> {
Err(NoKey)
}
fn public_key(&self) -> &[u8] {
b"\0"
}
}
pub(crate) fn cnxn() -> Packet {
Packet::new(
Command::Connect,
command::ADB_VERSION,
256 * 1024,
b"device::features=shell_v2".to_vec(),
)
}
pub(crate) fn okay(local_id: u32) -> Packet {
Packet::new(Command::Ready, 42, local_id, Vec::new())
}
pub(crate) fn connected_with_channel(stall: Option<usize>) -> (Connection<Mock>, ChannelId) {
let mut mock = Mock::new();
mock.feed(&cnxn())
.feed(&okay(1))
.feed(&okay(1))
.feed(&okay(1));
if let Some(index) = stall {
mock.stall_write(4 + index);
}
let mut conn = now(Connection::<_>::connect(mock, NoAuth, &[])).unwrap();
let ch = now(conn.open_channel(b"shell:\0")).unwrap();
(conn, ch)
}
#[cfg(feature = "split")]
#[allow(clippy::type_complexity)]
pub(crate) fn split_with_channel(
stall: Option<usize>,
) -> (
crate::split::Reader<SharedMock, SharedMock>,
crate::split::Writer<SharedMock>,
ChannelId,
) {
let mut mock = Mock::new();
mock.feed(&cnxn()).feed(&okay(1)).feed(&okay(1));
if let Some(index) = stall {
mock.stall_write(4 + index);
}
let conn = now(Connection::<_>::connect(SharedMock::new(mock), NoAuth, &[])).unwrap();
let (mut reader, writer) = conn.split().unwrap();
let ch = now(reader.open_channel(b"shell:\0")).unwrap();
(reader, writer, ch)
}
#[cfg(feature = "split")]
#[allow(clippy::type_complexity)]
pub(crate) fn split_one_channel_delayed_ack(
budget: u32,
extra: &[Packet],
) -> (
crate::split::Reader<SharedMock, SharedMock>,
crate::split::Writer<SharedMock>,
ChannelId,
SharedMock,
) {
let mut mock = Mock::new();
mock.feed(&cnxn_with("shell_v2,delayed_ack"))
.feed(&okay_with_budget(1, budget));
for pkt in extra {
mock.feed(pkt);
}
let transport = SharedMock::new(mock);
let seen = transport.clone();
let conn = now(Connection::<_>::connect_with_raw_banner(
transport,
NoAuth,
b"host::features=shell_v2,delayed_ack",
))
.unwrap();
let (mut reader, writer) = conn.split().unwrap();
let ch = now(reader.open_channel(b"shell:\0")).unwrap();
(reader, writer, ch, seen)
}
pub(crate) fn cnxn_with(features: &str) -> Packet {
Packet::new(
Command::Connect,
command::ADB_VERSION,
256 * 1024,
alloc::format!("device::features={features}").into_bytes(),
)
}
pub(crate) fn okay_with_budget(local_id: u32, budget: u32) -> Packet {
Packet::new(Command::Ready, 42, local_id, budget.to_le_bytes().to_vec())
}
pub(crate) fn wrte(local_id: u32, payload: &[u8]) -> Packet {
Packet::new(Command::Write, 42, local_id, payload.to_vec())
}
pub(crate) fn connected_for_select(
configure: impl FnOnce(&mut Mock),
) -> (Connection<Mock>, ChannelId) {
let mut mock = Mock::new();
mock.feed(&cnxn()).feed(&okay(1));
let mut conn = now(Connection::<_>::connect(mock, NoAuth, &[])).unwrap();
let ch = now(conn.open_channel(b"shell:\0")).unwrap();
let transport = conn.transport_mut();
transport.feed(&wrte(1, b"hello"));
configure(transport);
(conn, ch)
}
pub(crate) fn two_channels_delayed_ack(
budget: u32,
pushes: &[Packet],
) -> (Connection<Mock>, ChannelId, ChannelId) {
let mut mock = Mock::new();
mock.feed(&cnxn_with("shell_v2,delayed_ack"))
.feed(&okay_with_budget(1, budget))
.feed(&okay_with_budget(2, budget));
for pkt in pushes {
mock.feed(pkt);
}
let mut conn = now(Connection::<_>::connect_with_raw_banner(
mock,
NoAuth,
b"host::features=shell_v2,delayed_ack",
))
.unwrap();
let a = now(conn.open_channel(b"shell:a\0")).unwrap();
let b = now(conn.open_channel(b"shell:b\0")).unwrap();
(conn, a, b)
}
pub(crate) fn two_channels_classic(
config: crate::base::connection::ConnectionConfig,
pushes: &[Packet],
) -> (Connection<Mock>, ChannelId, ChannelId) {
let mut mock = Mock::new();
mock.feed(&cnxn_with("shell_v2"))
.feed(&okay(1))
.feed(&okay(2));
for pkt in pushes {
mock.feed(pkt);
}
let mut conn = now(Connection::<_>::connect_with_raw_banner_and_config(
mock,
NoAuth,
b"host::features=shell_v2",
config,
))
.unwrap();
let a = now(conn.open_channel(b"shell:a\0")).unwrap();
let b = now(conn.open_channel(b"shell:b\0")).unwrap();
(conn, a, b)
}
#[cfg(feature = "split")]
#[allow(clippy::type_complexity)]
pub(crate) fn split_two_channels_delayed_ack(
pushes: &[Packet],
) -> (
crate::split::Reader<SharedMock, SharedMock>,
ChannelId,
ChannelId,
SharedMock,
) {
let mut mock = Mock::new();
mock.feed(&cnxn_with("shell_v2,delayed_ack"))
.feed(&okay_with_budget(1, 64 * 1024))
.feed(&okay_with_budget(2, 64 * 1024));
for pkt in pushes {
mock.feed(pkt);
}
let transport = SharedMock::new(mock);
let seen = transport.clone();
let conn = now(Connection::<_>::connect_with_raw_banner(
transport,
NoAuth,
b"host::features=shell_v2,delayed_ack",
))
.unwrap();
let (mut reader, _writer) = conn.split().unwrap();
let a = now(reader.open_channel(b"shell:a\0")).unwrap();
let b = now(reader.open_channel(b"shell:b\0")).unwrap();
(reader, a, b, seen)
}