use std::io;
use crate::{
component::{self, Address, Component},
components::Internet,
error::{Error, Result},
value::{Handle, Value},
};
const CHUNK: i64 = 2048;
fn card(card: Option<&Address>) -> Result<Internet> {
match card {
Some(address) => Ok(Internet::from_address(address.clone())),
None => Internet::first().ok_or_else(|| Error::Failed("no internet card".into())),
}
}
#[derive(Debug)]
struct Connection {
handle: Handle,
eof: bool,
}
impl Connection {
fn call(&self, method: &str, args: Vec<Value>) -> Result<Vec<Value>> {
component::invoke_value(self.handle, method, args)
}
fn finish_connect(&self) -> Result<()> {
loop {
let reply = self.call("finishConnect", Vec::new())?;
match reply.first() {
Some(Value::Bool(true)) => return Ok(()),
Some(Value::Bool(false)) => {}
_ => {
let reason = reply.get(1).and_then(Value::as_str).unwrap_or("connection failed");
return Err(Error::Failed(reason.to_owned()));
}
}
}
}
fn read_chunk(&mut self, max: usize) -> io::Result<Vec<u8>> {
loop {
if let Some(chunk) = self.read_once(max)? {
return Ok(chunk);
}
}
}
fn read_once(&mut self, max: usize) -> io::Result<Option<Vec<u8>>> {
if self.eof {
return Ok(Some(Vec::new()));
}
let n = (max as i64).clamp(1, CHUNK);
let reply = self.call("read", vec![Value::from(n)]).map_err(io::Error::other)?;
match reply.first() {
Some(Value::String(bytes)) if !bytes.0.is_empty() => Ok(Some(bytes.0.clone())),
Some(Value::String(_)) => Ok(None),
None | Some(Value::Nil) => {
self.eof = true;
match reply.get(1).and_then(Value::as_str) {
Some(reason) => Err(io::Error::other(reason.to_owned())),
None => Ok(Some(Vec::new())),
}
}
Some(other) => Err(io::Error::other(format!("unexpected read result {other:?}"))),
}
}
}
impl Drop for Connection {
fn drop(&mut self) {
let _ = self.call("close", Vec::new());
component::release_value(self.handle);
}
}
#[derive(Debug, Default)]
struct Pending {
data: Vec<u8>,
pos: usize,
}
fn read_buffered(conn: &mut Connection, pending: &mut Pending, buf: &mut [u8]) -> io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
if pending.pos >= pending.data.len() {
pending.data = conn.read_chunk(buf.len())?;
pending.pos = 0;
}
let n = (pending.data.len() - pending.pos).min(buf.len());
buf[..n].copy_from_slice(&pending.data[pending.pos..pending.pos + n]);
pending.pos += n;
Ok(n)
}
#[derive(Clone, Debug)]
pub struct Request {
url: String,
method: Option<String>,
headers: Vec<(String, String)>,
body: Option<Vec<u8>>,
card: Option<Address>,
}
impl Request {
pub fn new(url: impl Into<String>) -> Request {
Request { url: url.into(), method: None, headers: Vec::new(), body: None, card: None }
}
pub fn method(mut self, method: impl Into<String>) -> Request {
self.method = Some(method.into());
self
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Request {
self.headers.push((name.into(), value.into()));
self
}
pub fn body(mut self, body: impl Into<Vec<u8>>) -> Request {
self.body = Some(body.into());
self
}
pub fn card(mut self, card: impl Into<Address>) -> Request {
self.card = Some(card.into());
self
}
pub fn send(&self) -> Result<Response> {
let card = card(self.card.as_ref())?;
let headers = (!self.headers.is_empty()).then(|| {
Value::Map(self.headers.iter().map(|(k, v)| (Value::from(k.as_str()), Value::from(v.as_str()))).collect())
});
let args = vec![
Value::from(self.url.as_str()),
self.body.as_deref().map_or(Value::Nil, Value::text),
headers.unwrap_or(Value::Nil),
self.method.as_deref().map_or(Value::Nil, Value::from),
];
let reply = card.invoke("request", args)?;
let handle = match reply.first() {
Some(Value::Handle(handle)) => *handle,
_ => {
let reason = reply.get(1).and_then(Value::as_str).unwrap_or("request failed");
return Err(Error::Failed(reason.to_owned()));
}
};
let conn = Connection { handle, eof: false };
conn.finish_connect()?;
loop {
let reply = conn.call("response", Vec::new())?;
if let Some(status) = reply.first().and_then(Value::as_i64) {
let message = reply.get(1).and_then(Value::as_str).unwrap_or_default().to_owned();
let headers = reply.get(2).map(parse_headers).unwrap_or_default();
return Ok(Response { status: status as u16, message, headers, conn, pending: Pending::default() });
}
}
}
}
fn parse_headers(value: &Value) -> Vec<(String, String)> {
let mut headers = Vec::new();
for (name, values) in value.as_map().unwrap_or_default() {
let Some(name) = name.as_str() else { continue };
match values {
Value::String(_) => headers.push((name.to_owned(), values.as_str().unwrap_or_default().to_owned())),
_ => {
for v in values.as_array().unwrap_or_default() {
headers.push((name.to_owned(), v.as_str().unwrap_or_default().to_owned()));
}
}
}
}
headers
}
pub fn get(url: impl Into<String>) -> Result<Response> {
Request::new(url).send()
}
#[derive(Debug)]
pub struct Response {
status: u16,
message: String,
headers: Vec<(String, String)>,
conn: Connection,
pending: Pending,
}
impl Response {
pub fn status(&self) -> u16 {
self.status
}
pub fn message(&self) -> &str {
&self.message
}
pub fn headers(&self) -> &[(String, String)] {
&self.headers
}
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
}
impl io::Read for Response {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
read_buffered(&mut self.conn, &mut self.pending, buf)
}
}
#[derive(Debug)]
pub struct TcpStream {
conn: Connection,
pending: Pending,
}
impl TcpStream {
pub fn connect(host: &str, port: u16) -> Result<TcpStream> {
TcpStream::connect_with(&card(None)?, host, port)
}
pub fn connect_with(card: &Internet, host: &str, port: u16) -> Result<TcpStream> {
let handle = card.connect(host, Some(i64::from(port).into()))?;
let conn = Connection { handle, eof: false };
conn.finish_connect()?;
Ok(TcpStream { conn, pending: Pending::default() })
}
pub fn try_read(&mut self, buf: &mut [u8]) -> io::Result<Option<usize>> {
if self.pending.pos >= self.pending.data.len() {
match self.conn.read_once(buf.len())? {
Some(chunk) => self.pending = Pending { data: chunk, pos: 0 },
None => return Ok(None),
}
}
read_buffered(&mut self.conn, &mut self.pending, buf).map(Some)
}
}
impl io::Read for TcpStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
read_buffered(&mut self.conn, &mut self.pending, buf)
}
}
impl io::Write for TcpStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
loop {
let reply = self.conn.call("write", vec![Value::text(buf)]).map_err(io::Error::other)?;
match reply.first().and_then(Value::as_i64) {
Some(0) => {}
Some(n) => return Ok(n as usize),
None => {
let reason = reply.get(1).and_then(Value::as_str).unwrap_or("write failed");
return Err(io::Error::other(reason.to_owned()));
}
}
}
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[cfg(feature = "async")]
impl Connection {
async fn call_async(&self, method: &str, args: Vec<Value>) -> Result<Vec<Value>> {
component::invoke_value_async(self.handle, method, args).await
}
async fn finish_connect_async(&self) -> Result<()> {
loop {
let reply = self.call_async("finishConnect", Vec::new()).await?;
match reply.first() {
Some(Value::Bool(true)) => return Ok(()),
Some(Value::Bool(false)) => {}
_ => {
let reason = reply.get(1).and_then(Value::as_str).unwrap_or("connection failed");
return Err(Error::Failed(reason.to_owned()));
}
}
}
}
async fn read_chunk_async(&mut self, max: usize) -> io::Result<Vec<u8>> {
loop {
if self.eof {
return Ok(Vec::new());
}
let n = (max as i64).clamp(1, CHUNK);
let reply = self.call_async("read", vec![Value::from(n)]).await.map_err(io::Error::other)?;
match reply.first() {
Some(Value::String(bytes)) if !bytes.0.is_empty() => return Ok(bytes.0.clone()),
Some(Value::String(_)) => {}
None | Some(Value::Nil) => {
self.eof = true;
if let Some(reason) = reply.get(1).and_then(Value::as_str) {
return Err(io::Error::other(reason.to_owned()));
}
}
Some(other) => return Err(io::Error::other(format!("unexpected read result {other:?}"))),
}
}
}
}
#[cfg(feature = "async")]
async fn read_buffered_async(conn: &mut Connection, pending: &mut Pending, buf: &mut [u8]) -> io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
if pending.pos >= pending.data.len() {
pending.data = conn.read_chunk_async(buf.len()).await?;
pending.pos = 0;
}
let n = (pending.data.len() - pending.pos).min(buf.len());
buf[..n].copy_from_slice(&pending.data[pending.pos..pending.pos + n]);
pending.pos += n;
Ok(n)
}
#[cfg(feature = "async")]
impl Request {
pub async fn send_async(&self) -> Result<Response> {
let card = card(self.card.as_ref())?;
let headers = (!self.headers.is_empty()).then(|| {
Value::Map(self.headers.iter().map(|(k, v)| (Value::from(k.as_str()), Value::from(v.as_str()))).collect())
});
let args = vec![
Value::from(self.url.as_str()),
self.body.as_deref().map_or(Value::Nil, Value::text),
headers.unwrap_or(Value::Nil),
self.method.as_deref().map_or(Value::Nil, Value::from),
];
let reply = card.invoke_async("request", args).await?;
let handle = match reply.first() {
Some(Value::Handle(handle)) => *handle,
_ => {
let reason = reply.get(1).and_then(Value::as_str).unwrap_or("request failed");
return Err(Error::Failed(reason.to_owned()));
}
};
let conn = Connection { handle, eof: false };
conn.finish_connect_async().await?;
loop {
let reply = conn.call_async("response", Vec::new()).await?;
if let Some(status) = reply.first().and_then(Value::as_i64) {
let message = reply.get(1).and_then(Value::as_str).unwrap_or_default().to_owned();
let headers = reply.get(2).map(parse_headers).unwrap_or_default();
return Ok(Response { status: status as u16, message, headers, conn, pending: Pending::default() });
}
crate::task::yield_now().await;
}
}
}
#[cfg(feature = "async")]
pub async fn get_async(url: impl Into<String>) -> Result<Response> {
Request::new(url).send_async().await
}
#[cfg(feature = "async")]
impl Response {
pub async fn read_async(&mut self, buf: &mut [u8]) -> io::Result<usize> {
read_buffered_async(&mut self.conn, &mut self.pending, buf).await
}
pub async fn read_to_end_async(&mut self, out: &mut Vec<u8>) -> io::Result<usize> {
let start = out.len();
let mut buf = [0u8; CHUNK as usize];
loop {
match self.read_async(&mut buf).await? {
0 => return Ok(out.len() - start),
n => out.extend_from_slice(&buf[..n]),
}
}
}
}
#[cfg(feature = "async")]
impl TcpStream {
pub async fn connect_async(host: &str, port: u16) -> Result<TcpStream> {
let card = card(None)?;
let reply = card.invoke_async("connect", vec![Value::from(host), Value::from(i64::from(port))]).await?;
let handle = match reply.first() {
Some(Value::Handle(handle)) => *handle,
_ => {
let reason = reply.get(1).and_then(Value::as_str).unwrap_or("connection failed");
return Err(Error::Failed(reason.to_owned()));
}
};
let conn = Connection { handle, eof: false };
conn.finish_connect_async().await?;
Ok(TcpStream { conn, pending: Pending::default() })
}
pub async fn read_async(&mut self, buf: &mut [u8]) -> io::Result<usize> {
read_buffered_async(&mut self.conn, &mut self.pending, buf).await
}
pub async fn write_async(&mut self, buf: &[u8]) -> io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
loop {
let reply = self.conn.call_async("write", vec![Value::text(buf)]).await.map_err(io::Error::other)?;
match reply.first().and_then(Value::as_i64) {
Some(0) => {}
Some(n) => return Ok(n as usize),
None => {
let reason = reply.get(1).and_then(Value::as_str).unwrap_or("write failed");
return Err(io::Error::other(reason.to_owned()));
}
}
}
}
pub async fn write_all_async(&mut self, mut buf: &[u8]) -> io::Result<()> {
while !buf.is_empty() {
let n = self.write_async(buf).await?;
buf = &buf[n..];
}
Ok(())
}
}