xur-std 0.1.7

The standard library of the Xur language
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
use std::io::Read as _;
use std::sync::Arc;

use facet::Facet;
use ureq::ResponseExt;
use xur_runtime::convert::into_value;
use xur_runtime::{
    Context, NativeObject, OneOf, Registry, RunResult, RuntimeError, Value, XurBytes, XurStr, lock,
    one_of,
};

use crate::{error_text, result};

one_of! {
    /// A request body: a string or raw bytes.
    enum Body {
        Text(XurStr),
        Bytes(XurBytes),
    }
}

/// Builder-method helper: clone the builder, apply `change`, return the new one.
fn configured_rb(rb: &RequestBuilder, change: impl FnOnce(&mut RequestBuilder)) -> RequestBuilder {
    let mut rb = rb.clone();
    change(&mut rb);
    rb
}

pub(crate) fn register(registry: &Registry) {
    registry.lazy_module("std::http", |module| {
        module
            .raw_function_returns::<Response>("get", http_get)
            .raw_function_returns::<Response>("post", http_post)
            .raw_function_returns::<Response>("put", http_put)
            .raw_function_returns::<Response>("patch", http_patch)
            .raw_function_returns::<Response>("delete", http_delete)
            .raw_function_returns::<Response>("head", http_head)
            .raw_function_returns::<RequestBuilder>("request", http_request);

        module
            .ty::<RequestBuilder>("RequestBuilder")
            .named_method(
                "header",
                &["name", "value"],
                |rb: &RequestBuilder, name: XurStr, value: XurStr| {
                    configured_rb(rb, |rb| {
                        rb.headers.push((name.to_string(), value.to_string()))
                    })
                },
            )
            .named_method(
                "bearer_auth",
                &["token"],
                |rb: &RequestBuilder, token: XurStr| {
                    configured_rb(rb, |rb| {
                        rb.headers
                            .push(("authorization".into(), format!("Bearer {}", &*token)))
                    })
                },
            )
            .named_method(
                "basic_auth",
                &["user", "pass"],
                |rb: &RequestBuilder, user: XurStr, pass: XurStr| {
                    configured_rb(rb, |rb| {
                        let encoded = base64_encode(format!("{}:{}", &*user, &*pass).as_bytes());
                        rb.headers
                            .push(("authorization".into(), format!("Basic {encoded}")));
                    })
                },
            )
            .named_method(
                "body",
                &["body"],
                |rb: &RequestBuilder, body: OneOf<Body>| {
                    let bytes = match body.0 {
                        Body::Text(s) => s.as_bytes().to_vec(),
                        Body::Bytes(b) => lock(&b.0).clone(),
                    };
                    configured_rb(rb, |rb| rb.body = Some(bytes))
                },
            )
            .raw_function_returns::<RequestBuilder>("json_body", rb_json_body)
            .named_method("timeout", &["secs"], |rb: &RequestBuilder, secs: u64| {
                configured_rb(rb, |rb| rb.timeout_secs = Some(secs))
            })
            .named_method(
                "query",
                &["key", "value"],
                |rb: &RequestBuilder, key: XurStr, value: XurStr| {
                    configured_rb(rb, |rb| {
                        rb.query_params.push((key.to_string(), value.to_string()))
                    })
                },
            )
            .raw_function_returns::<Response>("send", rb_send);

        module
            .ty::<Response>("Response")
            .method("status", |r: &Response| r.status as i64)
            .method("status_text", |r: &Response| r.status_text.clone())
            .method("url", |r: &Response| r.url.clone())
            .method("text", |r: &Response| {
                String::from_utf8_lossy(&r.body).into_owned()
            })
            .raw_function_returns::<Vec<u8>>("bytes", resp_bytes)
            .raw_function("json", resp_json)
            .named_method(
                "header",
                &["name"],
                |r: &Response, name: XurStr| -> Option<String> {
                    let lower = name.to_lowercase();
                    r.headers
                        .iter()
                        .find(|(k, _)| k.to_lowercase() == lower)
                        .map(|(_, v)| v.clone())
                },
            )
            .method("headers", |r: &Response| -> Value {
                let fields: Vec<(xur_span::Symbol, Value)> = r
                    .headers
                    .iter()
                    .map(|(k, v)| (xur_span::Symbol::intern(k), Value::str(v)))
                    .collect();
                Value::Record(xur_runtime::Record::new(fields).into())
            });
    });
}

// ── Response ───────────────────────────────────────────────────────

#[derive(Clone, Facet)]
#[facet(opaque)]
struct Response {
    status: u16,
    status_text: String,
    headers: Vec<(String, String)>,
    body: Arc<Vec<u8>>,
    url: String,
}

impl std::fmt::Display for Response {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Response {{ {} {} }}", self.status, self.status_text)
    }
}

fn read_response(resp: ureq::http::Response<ureq::Body>) -> RunResult<Response> {
    let status = resp.status().as_u16();
    let status_text = resp.status().canonical_reason().unwrap_or("").to_string();
    let url = resp.get_uri().to_string();

    let mut headers = Vec::new();
    for (name, value) in resp.headers() {
        headers.push((name.to_string(), value.to_str().unwrap_or("").to_string()));
    }

    let mut body_bytes = Vec::new();
    resp.into_body()
        .as_reader()
        .read_to_end(&mut body_bytes)
        .map_err(|e| RuntimeError::new(format!("failed to read response body: {e}")))?;

    Ok(Response {
        status,
        status_text,
        headers,
        body: Arc::new(body_bytes),
        url,
    })
}

fn with_response<R>(value: &Value, f: impl FnOnce(&Response) -> R) -> RunResult<R> {
    match value {
        Value::Native(obj) => obj
            .with(f)
            .ok_or_else(|| RuntimeError::new("expected an HTTP Response")),
        _ => Err(RuntimeError::new("expected an HTTP Response")),
    }
}

fn resp_bytes(_cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
    let [this] = args else {
        return Err(RuntimeError::new("`bytes` takes no arguments"));
    };
    let bytes = with_response(this, |r| r.body.as_ref().clone())?;
    Ok(Value::bytes(bytes))
}

fn resp_json(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
    let [this] = args else {
        return Err(RuntimeError::new("`json` takes no arguments"));
    };
    let text = with_response(this, |r| String::from_utf8_lossy(&r.body).into_owned())?;
    match crate::json::parse_str(cx, &text) {
        Ok(value) => Ok(result(cx, Ok(value))),
        Err(e) => Ok(result(cx, Err(e.message))),
    }
}

// ── RequestBuilder ─────────────────────────────────────────────────

#[derive(Clone, Facet)]
#[facet(opaque)]
struct RequestBuilder {
    method: String,
    url: String,
    headers: Vec<(String, String)>,
    body: Option<Vec<u8>>,
    content_type: Option<String>,
    timeout_secs: Option<u64>,
    query_params: Vec<(String, String)>,
}

impl std::fmt::Display for RequestBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "RequestBuilder {{ {} {} }}", self.method, self.url)
    }
}

fn with_rb(value: &Value, f: impl FnOnce(&RequestBuilder) -> RequestBuilder) -> RunResult<Value> {
    match value {
        Value::Native(obj) => {
            let new = obj
                .with(f)
                .ok_or_else(|| RuntimeError::new("expected a RequestBuilder"))?;
            let new_obj = NativeObject::new(obj.ty, Box::new(new));
            Ok(Value::Native(new_obj.into()))
        }
        _ => Err(RuntimeError::new("expected a RequestBuilder")),
    }
}

fn rb_json_body(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
    let [this, value] = args else {
        return Err(RuntimeError::new("`json_body` takes a value to serialize"));
    };
    let json_str = crate::json::stringify_value(cx, value)?;
    with_rb(this, |rb| {
        let mut rb = rb.clone();
        rb.body = Some(json_str.clone().into_bytes());
        rb.content_type = Some("application/json".into());
        rb
    })
}

fn rb_send(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
    let [this] = args else {
        return Err(RuntimeError::new("`send` takes no arguments"));
    };
    let rb = match this {
        Value::Native(obj) => obj
            .with(|rb: &RequestBuilder| rb.clone())
            .ok_or_else(|| RuntimeError::new("expected a RequestBuilder"))?,
        _ => return Err(RuntimeError::new("expected a RequestBuilder")),
    };
    match execute_request(&rb) {
        Ok(resp) => {
            let value = into_value(cx, resp)?;
            Ok(result(cx, Ok(value)))
        }
        Err(e) => Ok(result(cx, Err(e.message))),
    }
}

fn execute_request(rb: &RequestBuilder) -> RunResult<Response> {
    let config = ureq::Agent::config_builder()
        .timeout_global(Some(std::time::Duration::from_secs(
            rb.timeout_secs.unwrap_or(30),
        )))
        .build();
    let agent = ureq::Agent::new_with_config(config);

    let uses_body = rb.body.is_some() || matches!(rb.method.as_str(), "POST" | "PUT" | "PATCH");

    let resp = if uses_body {
        let mut req = match rb.method.as_str() {
            "PUT" => agent.put(&rb.url),
            "PATCH" => agent.patch(&rb.url),
            _ => agent.post(&rb.url),
        };
        for (k, v) in &rb.headers {
            req = req.header(k.as_str(), v.as_str());
        }
        for (k, v) in &rb.query_params {
            req = req.query(k.as_str(), v.as_str());
        }
        if let Some(ct) = &rb.content_type {
            req = req.header("content-type", ct.as_str());
        }
        let body_data = rb.body.clone().unwrap_or_default();
        req.send(body_data)
    } else {
        let mut req = match rb.method.as_str() {
            "DELETE" => agent.delete(&rb.url),
            "HEAD" => agent.head(&rb.url),
            "OPTIONS" => agent.options(&rb.url),
            _ => agent.get(&rb.url),
        };
        for (k, v) in &rb.headers {
            req = req.header(k.as_str(), v.as_str());
        }
        for (k, v) in &rb.query_params {
            req = req.query(k.as_str(), v.as_str());
        }
        req.call()
    };

    match resp {
        Ok(resp) => read_response(resp),
        Err(ureq::Error::StatusCode(code)) => {
            Err(RuntimeError::new(format!("HTTP error: status {code}")))
        }
        Err(e) => Err(RuntimeError::new(error_text(e))),
    }
}

// ── Shorthand functions ────────────────────────────────────────────

fn http_get(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
    let [Value::Str(url)] = args else {
        return Err(RuntimeError::new("`get` takes a URL string"));
    };
    simple_request(cx, "GET", url, None)
}

fn http_post(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
    let (url, body) = match args {
        [Value::Str(url)] => (url, None),
        [Value::Str(url), Value::Str(body)] => (url, Some(body.as_bytes().to_vec())),
        [Value::Str(url), Value::Bytes(body)] => (url, Some(lock(body).clone())),
        _ => return Err(RuntimeError::new("`post` takes (url) or (url, body)")),
    };
    simple_request(cx, "POST", url, body)
}

fn http_put(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
    let (url, body) = match args {
        [Value::Str(url)] => (url, None),
        [Value::Str(url), Value::Str(body)] => (url, Some(body.as_bytes().to_vec())),
        [Value::Str(url), Value::Bytes(body)] => (url, Some(lock(body).clone())),
        _ => return Err(RuntimeError::new("`put` takes (url) or (url, body)")),
    };
    simple_request(cx, "PUT", url, body)
}

fn http_patch(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
    let (url, body) = match args {
        [Value::Str(url)] => (url, None),
        [Value::Str(url), Value::Str(body)] => (url, Some(body.as_bytes().to_vec())),
        [Value::Str(url), Value::Bytes(body)] => (url, Some(lock(body).clone())),
        _ => return Err(RuntimeError::new("`patch` takes (url) or (url, body)")),
    };
    simple_request(cx, "PATCH", url, body)
}

fn http_delete(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
    let [Value::Str(url)] = args else {
        return Err(RuntimeError::new("`delete` takes a URL string"));
    };
    simple_request(cx, "DELETE", url, None)
}

fn http_head(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
    let [Value::Str(url)] = args else {
        return Err(RuntimeError::new("`head` takes a URL string"));
    };
    simple_request(cx, "HEAD", url, None)
}

fn http_request(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
    let [Value::Str(method), Value::Str(url)] = args else {
        return Err(RuntimeError::new("`request` takes (method, url) strings"));
    };
    let rb = RequestBuilder {
        method: method.to_uppercase(),
        url: url.to_string(),
        headers: Vec::new(),
        body: None,
        content_type: None,
        timeout_secs: None,
        query_params: Vec::new(),
    };
    into_value(cx, rb)
}

fn simple_request(
    cx: &mut dyn Context,
    method: &str,
    url: &str,
    body: Option<Vec<u8>>,
) -> RunResult<Value> {
    let rb = RequestBuilder {
        method: method.into(),
        url: url.into(),
        headers: Vec::new(),
        body,
        content_type: None,
        timeout_secs: None,
        query_params: Vec::new(),
    };
    match execute_request(&rb) {
        Ok(resp) => {
            let value = into_value(cx, resp)?;
            Ok(result(cx, Ok(value)))
        }
        Err(e) => Ok(result(cx, Err(e.message))),
    }
}

// ── Base64 (minimal, for Basic auth) ───────────────────────────────

fn base64_encode(data: &[u8]) -> String {
    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
    for chunk in data.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
        let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
        let n = (b0 << 16) | (b1 << 8) | b2;
        out.push(CHARS[(n >> 18 & 63) as usize] as char);
        out.push(CHARS[(n >> 12 & 63) as usize] as char);
        if chunk.len() > 1 {
            out.push(CHARS[(n >> 6 & 63) as usize] as char);
        } else {
            out.push('=');
        }
        if chunk.len() > 2 {
            out.push(CHARS[(n & 63) as usize] as char);
        } else {
            out.push('=');
        }
    }
    out
}