wackasm-opencomputers 0.1.0

Typed Rust bindings to OpenComputers components, for WASI programs running on the wackasm architecture
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! HTTP(S) requests and TCP connections through an internet card.
//!
//! ```no_run
//! use std::io::Read;
//! use wackasm_opencomputers::internet;
//!
//! let mut response = internet::get("https://example.com/")?;
//! println!("{} {}", response.status(), response.message());
//! let mut body = String::new();
//! response.read_to_string(&mut body)?;
//!
//! // Or build the request.
//! let response = internet::Request::new("https://httpbin.org/post")
//!     .method("POST")
//!     .header("Content-Type", "application/json")
//!     .body(r#"{"hello": "world"}"#)
//!     .send()?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! The card does the networking on the server. HTTP and TCP have to be
//! enabled in OpenComputers' config (they are by default), which also limits
//! which hosts can be reached; by default, local and private addresses are
//! blocked. Reads come in chunks of at most 2 KiB (`maxReadBuffer`), one per
//! server tick, so expect about 40 KB/s.
//!
//! [`Response`] and [`TcpStream`] are `std::io` streams. Dropping one closes
//! the connection and releases it on the host.

use std::io;

use crate::{
    component::{self, Address, Component},
    components::Internet,
    error::{Error, Result},
    value::{Handle, Value},
};

/// The most a single `read` returns (OpenComputers' default `maxReadBuffer`).
const CHUNK: i64 = 2048;

/// The internet card to use: `card`, or the first one.
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())),
    }
}

/// A request or socket object on the host.
#[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)
    }

    /// Waits until the connection is up; errors if it failed. Each try is an
    /// indirect call, so this waits a tick per try without using fuel.
    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)) => {}
                // `nil, reason`
                _ => {
                    let reason = reply.get(1).and_then(Value::as_str).unwrap_or("connection failed");
                    return Err(Error::Failed(reason.to_owned()));
                }
            }
        }
    }

    /// The next chunk of data, waiting for one; empty at the end.
    fn read_chunk(&mut self, max: usize) -> io::Result<Vec<u8>> {
        loop {
            if let Some(chunk) = self.read_once(max)? {
                return Ok(chunk);
            }
        }
    }

    /// One `read` call (a tick): `None` if nothing has arrived yet, empty at
    /// the end.
    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);
    }
}

/// Bytes left over from a chunk that didn't fit the caller's buffer.
#[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)
}

/// An HTTP request to send.
#[derive(Clone, Debug)]
pub struct Request {
    url: String,
    method: Option<String>,
    headers: Vec<(String, String)>,
    body: Option<Vec<u8>>,
    card: Option<Address>,
}

impl Request {
    /// A `GET` of `url` (`http://` or `https://`).
    pub fn new(url: impl Into<String>) -> Request {
        Request { url: url.into(), method: None, headers: Vec::new(), body: None, card: None }
    }

    /// The HTTP method. Without one it's `GET`, or `POST` if there's a body.
    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
    }

    /// Use this internet card instead of the first one.
    pub fn card(mut self, card: impl Into<Address>) -> Request {
        self.card = Some(card.into());
        self
    }

    /// Sends the request and waits for the status line and headers. Any
    /// status, 404 included, is a `Response`; errors are for requests that
    /// failed (unknown host, refused, blocked by the config, ...).
    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()?;
        // The response line is there once connected, but allow for a lag.
        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() });
            }
            // `response` is a direct call: once this tick's call budget is
            // spent, the machine sleeps until the next one.
        }
    }
}

/// `{name = {value, ...}}`, skipping Java's null key for the status line.
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
}

/// A shortcut for `Request::new(url).send()`.
pub fn get(url: impl Into<String>) -> Result<Response> {
    Request::new(url).send()
}

/// An HTTP response. Reading it reads the body.
#[derive(Debug)]
pub struct Response {
    status: u16,
    message: String,
    headers: Vec<(String, String)>,
    conn: Connection,
    pending: Pending,
}

impl Response {
    /// The status code, such as 200.
    pub fn status(&self) -> u16 {
        self.status
    }

    /// The reason phrase, such as `OK`.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Every header, in the order the server sent them (repeated names
    /// appear once per value).
    pub fn headers(&self) -> &[(String, String)] {
        &self.headers
    }

    /// The first value of the header `name` (case-insensitive).
    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)
    }
}

/// A TCP connection.
#[derive(Debug)]
pub struct TcpStream {
    conn: Connection,
    pending: Pending,
}

impl TcpStream {
    /// Connects to `host` on `port` with the first internet card, and waits
    /// until the connection is up.
    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() })
    }

    /// Reads what has arrived without waiting for more: `Ok(None)` if
    /// nothing has, `Ok(Some(0))` once the other side has closed. Each call
    /// takes a server tick.
    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) {
                // 0: the socket isn't writable yet; `write` is indirect, so
                // trying again waits a tick.
                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(())
    }
}

// ---------------------------------------------------------------- async

#[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()));
                }
            }
        }
    }

    /// The next chunk, waiting for one without holding up other tasks; empty
    /// at the end.
    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 {
    /// [`Request::send`] without blocking: other tasks keep running while the
    /// request connects. Requires the `async` feature; see [`crate::task`].
    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;
        }
    }
}

/// `internet::get(url)` without blocking; see [`Request::send_async`].
#[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 {
    /// Reads some of the body, like `Read::read`, without holding up other
    /// tasks while waiting for data. `Ok(0)` at the end.
    pub async fn read_async(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        read_buffered_async(&mut self.conn, &mut self.pending, buf).await
    }

    /// Reads the rest of the body into `out`; returns how many bytes that was.
    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 {
    /// [`TcpStream::connect`] without blocking.
    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() })
    }

    /// Reads what arrives, waiting for something without holding up other
    /// tasks. `Ok(0)` once the other side has closed.
    pub async fn read_async(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        read_buffered_async(&mut self.conn, &mut self.pending, buf).await
    }

    /// Writes some of `buf`; returns how much.
    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()));
                }
            }
        }
    }

    /// Writes all of `buf`.
    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(())
    }
}