sim-table-http 0.1.0

Capability-gated HTTP table directory backend for SIM.
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
//! The [`HttpDir`] object: a capability-gated HTTP-backed table directory.

use std::{sync::Arc, time::Duration};

use sim_citizen::CitizenField;
use sim_codec::{Input, Output, decode_with_codec, encode_with_codec};
use sim_kernel::{
    Cx, EncodeOptions, Error, Expr, Object, ObjectEncode, ObjectEncoding, ReadPolicy, Result,
    Symbol, Value,
    id::CORE_TABLE_CLASS_ID,
    object::ClassRef,
    table::{Dir, Table},
};

use crate::{
    capabilities::require_table_http,
    citizen::http_dir_class_symbol,
    transport::{HttpRequest, send},
};

/// The HTTP method used for table `set`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HttpWriteMethod {
    /// Write with `PUT`.
    #[default]
    Put,
    /// Write with `POST`.
    Post,
}

impl HttpWriteMethod {
    /// Returns the wire method token.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Put => "PUT",
            Self::Post => "POST",
        }
    }

    fn from_str(value: &str) -> Result<Self> {
        match value {
            "PUT" => Ok(Self::Put),
            "POST" => Ok(Self::Post),
            other => Err(Error::Eval(format!(
                "table/http: unsupported write method {other}"
            ))),
        }
    }
}

/// Configuration for an [`HttpDir`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HttpDirOptions {
    /// Base URL whose children are addressed by table keys.
    pub base_url: String,
    /// Codec used to decode response bodies and encode request bodies.
    pub codec: Symbol,
    /// Write method used by [`Table::set`].
    pub write_method: HttpWriteMethod,
    /// Socket read/write timeout in milliseconds.
    pub timeout_ms: u64,
    /// Maximum response body size in bytes.
    pub max_body_bytes: usize,
}

impl HttpDirOptions {
    /// Builds options for `base_url` with the Lisp codec, `PUT`, a five-second
    /// timeout, and a 1 MiB response body cap.
    pub fn new(base_url: impl Into<String>) -> Self {
        Self {
            base_url: base_url.into(),
            codec: Symbol::qualified("codec", "lisp"),
            write_method: HttpWriteMethod::Put,
            timeout_ms: 5_000,
            max_body_bytes: 1024 * 1024,
        }
    }

    /// Returns options using `codec`.
    pub fn with_codec(mut self, codec: Symbol) -> Self {
        self.codec = codec;
        self
    }

    /// Returns options using `write_method` for `set`.
    pub fn with_write_method(mut self, write_method: HttpWriteMethod) -> Self {
        self.write_method = write_method;
        self
    }

    /// Returns options using `timeout_ms`.
    pub fn with_timeout_ms(mut self, timeout_ms: u64) -> Self {
        self.timeout_ms = timeout_ms;
        self
    }

    /// Returns options using `max_body_bytes`.
    pub fn with_max_body_bytes(mut self, max_body_bytes: usize) -> Self {
        self.max_body_bytes = max_body_bytes;
        self
    }
}

/// A table directory backed by direct HTTP resources.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HttpDir {
    options: HttpDirOptions,
}

impl HttpDir {
    /// Builds an HTTP directory from `options`.
    pub fn new(options: HttpDirOptions) -> Result<Self> {
        validate_options(&options)?;
        Ok(Self {
            options: normalize_options(options),
        })
    }

    /// Returns this directory's options.
    pub fn options(&self) -> &HttpDirOptions {
        &self.options
    }

    fn child(&self, key: &Symbol) -> Result<Self> {
        Self::new(HttpDirOptions {
            base_url: self.url_for_key(key)?,
            codec: self.options.codec.clone(),
            write_method: self.options.write_method,
            timeout_ms: self.options.timeout_ms,
            max_body_bytes: self.options.max_body_bytes,
        })
    }

    fn request(&self, method: &'static str, url: String, body: Vec<u8>) -> HttpRequest {
        HttpRequest {
            method,
            url,
            headers: Vec::new(),
            body,
            timeout: Duration::from_millis(self.options.timeout_ms),
            max_body_bytes: self.options.max_body_bytes,
        }
    }

    fn url_for_key(&self, key: &Symbol) -> Result<String> {
        let segment = key.name.as_ref();
        if !sim_table_core::is_legal_table_segment(segment) {
            return Err(Error::Eval(format!("table/http: illegal name {segment:?}")));
        }
        Ok(format!("{}/{segment}", self.options.base_url))
    }

    fn decode_body(&self, cx: &mut Cx, body: Vec<u8>) -> Result<Value> {
        let expr = decode_with_codec(
            cx,
            &self.options.codec,
            Input::Bytes(body),
            ReadPolicy::default(),
        )?;
        cx.factory().expr(expr)
    }

    fn encode_value(&self, cx: &mut Cx, value: Value) -> Result<Vec<u8>> {
        let expr = value.object().as_expr(cx)?;
        match encode_with_codec(cx, &self.options.codec, &expr, EncodeOptions::default())? {
            Output::Text(text) => Ok(text.into_bytes()),
            Output::Bytes(bytes) => Ok(bytes),
        }
    }
}

impl Object for HttpDir {
    fn display(&self, _cx: &mut Cx) -> Result<String> {
        Ok(format!("table/http[{}]", self.options.base_url))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl sim_kernel::ObjectCompat for HttpDir {
    fn class(&self, cx: &mut Cx) -> Result<ClassRef> {
        let symbol = http_dir_class_symbol();
        if let Some(value) = cx.registry().class_by_symbol(&symbol) {
            return Ok(value.clone());
        }
        let symbol = Symbol::qualified("core", "Table");
        if let Some(value) = cx.registry().class_by_symbol(&symbol) {
            return Ok(value.clone());
        }
        cx.factory().class_stub(CORE_TABLE_CLASS_ID, symbol)
    }

    fn as_expr(&self, cx: &mut Cx) -> Result<Expr> {
        self.as_table_expr(cx)
    }

    fn truth(&self, _cx: &mut Cx) -> Result<bool> {
        Ok(true)
    }

    fn as_table_impl(&self) -> Option<&dyn Table> {
        Some(self)
    }

    fn as_dir(&self) -> Option<&dyn Dir> {
        Some(self)
    }

    fn as_object_encoder(&self) -> Option<&dyn ObjectEncode> {
        Some(self)
    }
}

impl ObjectEncode for HttpDir {
    fn object_encoding(&self, _cx: &mut Cx) -> Result<ObjectEncoding> {
        Ok(ObjectEncoding::Constructor {
            class: http_dir_class_symbol(),
            args: vec![
                Expr::Symbol(Symbol::new("v0")),
                self.options.base_url.encode_field(),
                self.options.codec.encode_field(),
                self.options.write_method.as_str().to_owned().encode_field(),
                self.options.timeout_ms.encode_field(),
                self.options.max_body_bytes.encode_field(),
            ],
        })
    }
}

impl sim_citizen::Citizen for HttpDir {
    fn citizen_symbol() -> Symbol {
        http_dir_class_symbol()
    }

    fn citizen_version() -> u32 {
        0
    }

    fn citizen_arity() -> usize {
        5
    }

    fn citizen_fields() -> &'static [&'static str] {
        &[
            "base_url",
            "codec",
            "write_method",
            "timeout_ms",
            "max_body_bytes",
        ]
    }
}

impl Table for HttpDir {
    fn backend_symbol(&self) -> Symbol {
        Symbol::qualified("table", "http")
    }

    fn get(&self, cx: &mut Cx, key: Symbol) -> Result<Value> {
        require_table_http(cx)?;
        let response = send(self.request("GET", self.url_for_key(&key)?, Vec::new()))?;
        ensure_success(response.status, response.reason.as_deref(), &response.body)?;
        self.decode_body(cx, response.body)
    }

    fn set(&self, cx: &mut Cx, key: Symbol, value: Value) -> Result<()> {
        require_table_http(cx)?;
        let body = self.encode_value(cx, value)?;
        let response = send(self.request(
            self.options.write_method.as_str(),
            self.url_for_key(&key)?,
            body,
        ))?;
        ensure_success(response.status, response.reason.as_deref(), &response.body)?;
        Ok(())
    }

    fn has(&self, cx: &mut Cx, key: Symbol) -> Result<bool> {
        require_table_http(cx)?;
        let response = send(self.request("HEAD", self.url_for_key(&key)?, Vec::new()))?;
        match response.status {
            status if (200..300).contains(&status) => Ok(true),
            404 => Ok(false),
            status => Err(status_error(
                status,
                response.reason.as_deref(),
                &response.body,
            )),
        }
    }

    fn del(&self, cx: &mut Cx, key: Symbol) -> Result<Value> {
        require_table_http(cx)?;
        let response = send(self.request("DELETE", self.url_for_key(&key)?, Vec::new()))?;
        match response.status {
            status if (200..300).contains(&status) || status == 404 => cx.factory().nil(),
            status => Err(status_error(
                status,
                response.reason.as_deref(),
                &response.body,
            )),
        }
    }

    fn keys(&self, _cx: &mut Cx) -> Result<Vec<Symbol>> {
        Err(Error::Eval(
            "table/http: keys are not available without an index resource".to_owned(),
        ))
    }

    fn entries(&self, _cx: &mut Cx) -> Result<Vec<(Symbol, Value)>> {
        Err(Error::Eval(
            "table/http: entries are not available without an index resource".to_owned(),
        ))
    }

    fn len(&self, _cx: &mut Cx) -> Result<usize> {
        Err(Error::Eval(
            "table/http: len is not available without an index resource".to_owned(),
        ))
    }

    fn clear(&self, _cx: &mut Cx) -> Result<()> {
        Err(Error::Eval(
            "table/http: clear is not available without an index resource".to_owned(),
        ))
    }
}

impl Dir for HttpDir {
    fn mkdir(&self, cx: &mut Cx, name: Symbol) -> Result<Value> {
        require_table_http(cx)?;
        cx.factory().opaque(Arc::new(self.child(&name)?))
    }

    fn opendir(&self, cx: &mut Cx, name: Symbol) -> Result<Option<Value>> {
        require_table_http(cx)?;
        Ok(Some(cx.factory().opaque(Arc::new(self.child(&name)?))?))
    }

    fn rmdir(&self, cx: &mut Cx, name: Symbol) -> Result<Value> {
        self.del(cx, name)
    }

    fn is_dir(&self, cx: &mut Cx, name: Symbol) -> Result<bool> {
        require_table_http(cx)?;
        let _ = self.url_for_key(&name)?;
        Ok(true)
    }
}

/// Creates an HTTP directory value from `options`.
pub fn install_http_dir_lib(cx: &mut Cx, options: HttpDirOptions) -> Result<Value> {
    cx.factory().opaque(Arc::new(HttpDir::new(options)?))
}

fn validate_options(options: &HttpDirOptions) -> Result<()> {
    if options.timeout_ms == 0 {
        return Err(Error::Eval(
            "table/http: timeout_ms must be non-zero".to_owned(),
        ));
    }
    if options.base_url.trim().is_empty() {
        return Err(Error::Eval("table/http: base_url is empty".to_owned()));
    }
    let _ = sim_lib_net_core::parse_url(options.base_url.trim())
        .map_err(|err| Error::Eval(format!("table/http: {err}")))?;
    Ok(())
}

fn normalize_options(mut options: HttpDirOptions) -> HttpDirOptions {
    options.base_url = options.base_url.trim().trim_end_matches('/').to_owned();
    options
}

fn ensure_success(status: u16, reason: Option<&str>, body: &[u8]) -> Result<()> {
    if (200..300).contains(&status) {
        Ok(())
    } else {
        Err(status_error(status, reason, body))
    }
}

fn status_error(status: u16, reason: Option<&str>, body: &[u8]) -> Error {
    let reason = reason.unwrap_or_default();
    let body = String::from_utf8_lossy(body);
    let detail = if body.is_empty() {
        reason.to_owned()
    } else if reason.is_empty() {
        body.into_owned()
    } else {
        format!("{reason}: {body}")
    };
    Error::HostError(format!("table/http: http {status}: {detail}"))
}

impl TryFrom<crate::HttpDirDescriptor> for HttpDirOptions {
    type Error = Error;

    fn try_from(value: crate::HttpDirDescriptor) -> Result<Self> {
        Ok(Self {
            base_url: value.base_url,
            codec: value.codec,
            write_method: HttpWriteMethod::from_str(&value.write_method)?,
            timeout_ms: value.timeout_ms,
            max_body_bytes: value.max_body_bytes,
        })
    }
}