1use std::io;
31
32use crate::{
33 component::{self, Address, Component},
34 components::Internet,
35 error::{Error, Result},
36 value::{Handle, Value},
37};
38
39const CHUNK: i64 = 2048;
41
42fn card(card: Option<&Address>) -> Result<Internet> {
44 match card {
45 Some(address) => Ok(Internet::from_address(address.clone())),
46 None => Internet::first().ok_or_else(|| Error::Failed("no internet card".into())),
47 }
48}
49
50#[derive(Debug)]
52struct Connection {
53 handle: Handle,
54 eof: bool,
55}
56
57impl Connection {
58 fn call(&self, method: &str, args: Vec<Value>) -> Result<Vec<Value>> {
59 component::invoke_value(self.handle, method, args)
60 }
61
62 fn finish_connect(&self) -> Result<()> {
65 loop {
66 let reply = self.call("finishConnect", Vec::new())?;
67 match reply.first() {
68 Some(Value::Bool(true)) => return Ok(()),
69 Some(Value::Bool(false)) => {}
70 _ => {
72 let reason = reply.get(1).and_then(Value::as_str).unwrap_or("connection failed");
73 return Err(Error::Failed(reason.to_owned()));
74 }
75 }
76 }
77 }
78
79 fn read_chunk(&mut self, max: usize) -> io::Result<Vec<u8>> {
81 loop {
82 if let Some(chunk) = self.read_once(max)? {
83 return Ok(chunk);
84 }
85 }
86 }
87
88 fn read_once(&mut self, max: usize) -> io::Result<Option<Vec<u8>>> {
91 if self.eof {
92 return Ok(Some(Vec::new()));
93 }
94 let n = (max as i64).clamp(1, CHUNK);
95 let reply = self.call("read", vec![Value::from(n)]).map_err(io::Error::other)?;
96 match reply.first() {
97 Some(Value::String(bytes)) if !bytes.0.is_empty() => Ok(Some(bytes.0.clone())),
98 Some(Value::String(_)) => Ok(None),
99 None | Some(Value::Nil) => {
100 self.eof = true;
101 match reply.get(1).and_then(Value::as_str) {
102 Some(reason) => Err(io::Error::other(reason.to_owned())),
103 None => Ok(Some(Vec::new())),
104 }
105 }
106 Some(other) => Err(io::Error::other(format!("unexpected read result {other:?}"))),
107 }
108 }
109}
110
111impl Drop for Connection {
112 fn drop(&mut self) {
113 let _ = self.call("close", Vec::new());
114 component::release_value(self.handle);
115 }
116}
117
118#[derive(Debug, Default)]
120struct Pending {
121 data: Vec<u8>,
122 pos: usize,
123}
124
125fn read_buffered(conn: &mut Connection, pending: &mut Pending, buf: &mut [u8]) -> io::Result<usize> {
126 if buf.is_empty() {
127 return Ok(0);
128 }
129 if pending.pos >= pending.data.len() {
130 pending.data = conn.read_chunk(buf.len())?;
131 pending.pos = 0;
132 }
133 let n = (pending.data.len() - pending.pos).min(buf.len());
134 buf[..n].copy_from_slice(&pending.data[pending.pos..pending.pos + n]);
135 pending.pos += n;
136 Ok(n)
137}
138
139#[derive(Clone, Debug)]
141pub struct Request {
142 url: String,
143 method: Option<String>,
144 headers: Vec<(String, String)>,
145 body: Option<Vec<u8>>,
146 card: Option<Address>,
147}
148
149impl Request {
150 pub fn new(url: impl Into<String>) -> Request {
152 Request { url: url.into(), method: None, headers: Vec::new(), body: None, card: None }
153 }
154
155 pub fn method(mut self, method: impl Into<String>) -> Request {
157 self.method = Some(method.into());
158 self
159 }
160
161 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Request {
162 self.headers.push((name.into(), value.into()));
163 self
164 }
165
166 pub fn body(mut self, body: impl Into<Vec<u8>>) -> Request {
167 self.body = Some(body.into());
168 self
169 }
170
171 pub fn card(mut self, card: impl Into<Address>) -> Request {
173 self.card = Some(card.into());
174 self
175 }
176
177 pub fn send(&self) -> Result<Response> {
181 let card = card(self.card.as_ref())?;
182 let headers = (!self.headers.is_empty()).then(|| {
183 Value::Map(self.headers.iter().map(|(k, v)| (Value::from(k.as_str()), Value::from(v.as_str()))).collect())
184 });
185 let args = vec![
186 Value::from(self.url.as_str()),
187 self.body.as_deref().map_or(Value::Nil, Value::text),
188 headers.unwrap_or(Value::Nil),
189 self.method.as_deref().map_or(Value::Nil, Value::from),
190 ];
191 let reply = card.invoke("request", args)?;
192 let handle = match reply.first() {
193 Some(Value::Handle(handle)) => *handle,
194 _ => {
195 let reason = reply.get(1).and_then(Value::as_str).unwrap_or("request failed");
196 return Err(Error::Failed(reason.to_owned()));
197 }
198 };
199 let conn = Connection { handle, eof: false };
200 conn.finish_connect()?;
201 loop {
203 let reply = conn.call("response", Vec::new())?;
204 if let Some(status) = reply.first().and_then(Value::as_i64) {
205 let message = reply.get(1).and_then(Value::as_str).unwrap_or_default().to_owned();
206 let headers = reply.get(2).map(parse_headers).unwrap_or_default();
207 return Ok(Response { status: status as u16, message, headers, conn, pending: Pending::default() });
208 }
209 }
212 }
213}
214
215fn parse_headers(value: &Value) -> Vec<(String, String)> {
217 let mut headers = Vec::new();
218 for (name, values) in value.as_map().unwrap_or_default() {
219 let Some(name) = name.as_str() else { continue };
220 match values {
221 Value::String(_) => headers.push((name.to_owned(), values.as_str().unwrap_or_default().to_owned())),
222 _ => {
223 for v in values.as_array().unwrap_or_default() {
224 headers.push((name.to_owned(), v.as_str().unwrap_or_default().to_owned()));
225 }
226 }
227 }
228 }
229 headers
230}
231
232pub fn get(url: impl Into<String>) -> Result<Response> {
234 Request::new(url).send()
235}
236
237#[derive(Debug)]
239pub struct Response {
240 status: u16,
241 message: String,
242 headers: Vec<(String, String)>,
243 conn: Connection,
244 pending: Pending,
245}
246
247impl Response {
248 pub fn status(&self) -> u16 {
250 self.status
251 }
252
253 pub fn message(&self) -> &str {
255 &self.message
256 }
257
258 pub fn headers(&self) -> &[(String, String)] {
261 &self.headers
262 }
263
264 pub fn header(&self, name: &str) -> Option<&str> {
266 self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
267 }
268}
269
270impl io::Read for Response {
271 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
272 read_buffered(&mut self.conn, &mut self.pending, buf)
273 }
274}
275
276#[derive(Debug)]
278pub struct TcpStream {
279 conn: Connection,
280 pending: Pending,
281}
282
283impl TcpStream {
284 pub fn connect(host: &str, port: u16) -> Result<TcpStream> {
287 TcpStream::connect_with(&card(None)?, host, port)
288 }
289
290 pub fn connect_with(card: &Internet, host: &str, port: u16) -> Result<TcpStream> {
291 let handle = card.connect(host, Some(i64::from(port).into()))?;
292 let conn = Connection { handle, eof: false };
293 conn.finish_connect()?;
294 Ok(TcpStream { conn, pending: Pending::default() })
295 }
296
297 pub fn try_read(&mut self, buf: &mut [u8]) -> io::Result<Option<usize>> {
301 if self.pending.pos >= self.pending.data.len() {
302 match self.conn.read_once(buf.len())? {
303 Some(chunk) => self.pending = Pending { data: chunk, pos: 0 },
304 None => return Ok(None),
305 }
306 }
307 read_buffered(&mut self.conn, &mut self.pending, buf).map(Some)
308 }
309}
310
311impl io::Read for TcpStream {
312 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
313 read_buffered(&mut self.conn, &mut self.pending, buf)
314 }
315}
316
317impl io::Write for TcpStream {
318 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
319 if buf.is_empty() {
320 return Ok(0);
321 }
322 loop {
323 let reply = self.conn.call("write", vec![Value::text(buf)]).map_err(io::Error::other)?;
324 match reply.first().and_then(Value::as_i64) {
325 Some(0) => {}
328 Some(n) => return Ok(n as usize),
329 None => {
330 let reason = reply.get(1).and_then(Value::as_str).unwrap_or("write failed");
331 return Err(io::Error::other(reason.to_owned()));
332 }
333 }
334 }
335 }
336
337 fn flush(&mut self) -> io::Result<()> {
338 Ok(())
339 }
340}
341
342#[cfg(feature = "async")]
345impl Connection {
346 async fn call_async(&self, method: &str, args: Vec<Value>) -> Result<Vec<Value>> {
347 component::invoke_value_async(self.handle, method, args).await
348 }
349
350 async fn finish_connect_async(&self) -> Result<()> {
351 loop {
352 let reply = self.call_async("finishConnect", Vec::new()).await?;
353 match reply.first() {
354 Some(Value::Bool(true)) => return Ok(()),
355 Some(Value::Bool(false)) => {}
356 _ => {
357 let reason = reply.get(1).and_then(Value::as_str).unwrap_or("connection failed");
358 return Err(Error::Failed(reason.to_owned()));
359 }
360 }
361 }
362 }
363
364 async fn read_chunk_async(&mut self, max: usize) -> io::Result<Vec<u8>> {
367 loop {
368 if self.eof {
369 return Ok(Vec::new());
370 }
371 let n = (max as i64).clamp(1, CHUNK);
372 let reply = self.call_async("read", vec![Value::from(n)]).await.map_err(io::Error::other)?;
373 match reply.first() {
374 Some(Value::String(bytes)) if !bytes.0.is_empty() => return Ok(bytes.0.clone()),
375 Some(Value::String(_)) => {}
376 None | Some(Value::Nil) => {
377 self.eof = true;
378 if let Some(reason) = reply.get(1).and_then(Value::as_str) {
379 return Err(io::Error::other(reason.to_owned()));
380 }
381 }
382 Some(other) => return Err(io::Error::other(format!("unexpected read result {other:?}"))),
383 }
384 }
385 }
386}
387
388#[cfg(feature = "async")]
389async fn read_buffered_async(conn: &mut Connection, pending: &mut Pending, buf: &mut [u8]) -> io::Result<usize> {
390 if buf.is_empty() {
391 return Ok(0);
392 }
393 if pending.pos >= pending.data.len() {
394 pending.data = conn.read_chunk_async(buf.len()).await?;
395 pending.pos = 0;
396 }
397 let n = (pending.data.len() - pending.pos).min(buf.len());
398 buf[..n].copy_from_slice(&pending.data[pending.pos..pending.pos + n]);
399 pending.pos += n;
400 Ok(n)
401}
402
403#[cfg(feature = "async")]
404impl Request {
405 pub async fn send_async(&self) -> Result<Response> {
408 let card = card(self.card.as_ref())?;
409 let headers = (!self.headers.is_empty()).then(|| {
410 Value::Map(self.headers.iter().map(|(k, v)| (Value::from(k.as_str()), Value::from(v.as_str()))).collect())
411 });
412 let args = vec![
413 Value::from(self.url.as_str()),
414 self.body.as_deref().map_or(Value::Nil, Value::text),
415 headers.unwrap_or(Value::Nil),
416 self.method.as_deref().map_or(Value::Nil, Value::from),
417 ];
418 let reply = card.invoke_async("request", args).await?;
419 let handle = match reply.first() {
420 Some(Value::Handle(handle)) => *handle,
421 _ => {
422 let reason = reply.get(1).and_then(Value::as_str).unwrap_or("request failed");
423 return Err(Error::Failed(reason.to_owned()));
424 }
425 };
426 let conn = Connection { handle, eof: false };
427 conn.finish_connect_async().await?;
428 loop {
429 let reply = conn.call_async("response", Vec::new()).await?;
430 if let Some(status) = reply.first().and_then(Value::as_i64) {
431 let message = reply.get(1).and_then(Value::as_str).unwrap_or_default().to_owned();
432 let headers = reply.get(2).map(parse_headers).unwrap_or_default();
433 return Ok(Response { status: status as u16, message, headers, conn, pending: Pending::default() });
434 }
435 crate::task::yield_now().await;
436 }
437 }
438}
439
440#[cfg(feature = "async")]
442pub async fn get_async(url: impl Into<String>) -> Result<Response> {
443 Request::new(url).send_async().await
444}
445
446#[cfg(feature = "async")]
447impl Response {
448 pub async fn read_async(&mut self, buf: &mut [u8]) -> io::Result<usize> {
451 read_buffered_async(&mut self.conn, &mut self.pending, buf).await
452 }
453
454 pub async fn read_to_end_async(&mut self, out: &mut Vec<u8>) -> io::Result<usize> {
456 let start = out.len();
457 let mut buf = [0u8; CHUNK as usize];
458 loop {
459 match self.read_async(&mut buf).await? {
460 0 => return Ok(out.len() - start),
461 n => out.extend_from_slice(&buf[..n]),
462 }
463 }
464 }
465}
466
467#[cfg(feature = "async")]
468impl TcpStream {
469 pub async fn connect_async(host: &str, port: u16) -> Result<TcpStream> {
471 let card = card(None)?;
472 let reply = card.invoke_async("connect", vec![Value::from(host), Value::from(i64::from(port))]).await?;
473 let handle = match reply.first() {
474 Some(Value::Handle(handle)) => *handle,
475 _ => {
476 let reason = reply.get(1).and_then(Value::as_str).unwrap_or("connection failed");
477 return Err(Error::Failed(reason.to_owned()));
478 }
479 };
480 let conn = Connection { handle, eof: false };
481 conn.finish_connect_async().await?;
482 Ok(TcpStream { conn, pending: Pending::default() })
483 }
484
485 pub async fn read_async(&mut self, buf: &mut [u8]) -> io::Result<usize> {
488 read_buffered_async(&mut self.conn, &mut self.pending, buf).await
489 }
490
491 pub async fn write_async(&mut self, buf: &[u8]) -> io::Result<usize> {
493 if buf.is_empty() {
494 return Ok(0);
495 }
496 loop {
497 let reply = self.conn.call_async("write", vec![Value::text(buf)]).await.map_err(io::Error::other)?;
498 match reply.first().and_then(Value::as_i64) {
499 Some(0) => {}
500 Some(n) => return Ok(n as usize),
501 None => {
502 let reason = reply.get(1).and_then(Value::as_str).unwrap_or("write failed");
503 return Err(io::Error::other(reason.to_owned()));
504 }
505 }
506 }
507 }
508
509 pub async fn write_all_async(&mut self, mut buf: &[u8]) -> io::Result<()> {
511 while !buf.is_empty() {
512 let n = self.write_async(buf).await?;
513 buf = &buf[n..];
514 }
515 Ok(())
516 }
517}