bun_runtime 0.1.2

Bao runtime integration — JS engine + Bun API + event loop
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
// @trace REQ-ENG-007 [entity:HttpClientBridge]
// @trace REQ-PERF-001 [entity:HttpResponse] @trace REQ-PERF-003 [entity:BufferManager]
//! Synchronous HTTP client bridge using bun_http::AsyncHTTP::init_sync + send_sync().
//!
//! Provides a simple synchronous HTTP request function that can be called
//! from anywhere in bao_runtime without needing SpiderMonkey context.

use bun_core::MutableString;
use bun_http::header_builder::HeaderBuilder;
use bun_http::{AsyncHTTP, FetchRedirect, Method};
use bun_url::URL;
use bytes::Bytes;
use compact_str::CompactString;
use smallvec::SmallVec;

/// Simplified HTTP response type extracted from picohttp::Response.
/// Owns all data (no borrowed lifetime) so it can be stored and used freely.
///
/// Zero-copy / zero-alloc optimizations:
/// - `status_text`: CompactString inlines short strings like "OK" (no heap alloc)
/// - `headers`: SmallVec stacks ≤8 header pairs (typical case), spills to heap only for many headers
/// - `body`: Bytes enables zero-copy slicing and avoids clone() on large responses
pub struct HttpResponse {
    /// HTTP status code (e.g. 200, 404, 500).
    pub status_code: u32,
    /// Status text (e.g. "OK", "Not Found"). CompactString: inline for ≤24 bytes.
    pub status_text: CompactString,
    /// Response headers as (name, value) pairs. SmallVec: stack for ≤8 pairs.
    pub headers: SmallVec<[(CompactString, CompactString); 8]>,
    /// Response body. Bytes: zero-copy slicing, cheap clone (Arc ref count).
    pub body: Bytes,
}

/// Perform a synchronous HTTP request via bun_http::AsyncHTTP::send_sync().
///
/// This function:
/// 1. Parses the URL via bun_url::URL::parse
/// 2. Builds request headers via HeaderBuilder
/// 3. Initializes AsyncHTTP via init_sync()
/// 4. Executes the request via send_sync() (blocking)
/// 5. Extracts the response into an owned HttpResponse
pub fn http_request(
    method: Method,
    url: &str,
    headers: &[(String, String)],
    body: Option<&[u8]>,
) -> ::std::result::Result<HttpResponse, String> {
    // Parse URL from bytes
    let url_bytes = url.as_bytes();
    let parsed_url = URL::parse(url_bytes);

    // Build header entries via HeaderBuilder: count -> allocate -> append
    let mut hb = HeaderBuilder::default();
    for (name, value) in headers {
        hb.count(name.as_bytes(), value.as_bytes());
    }
    if let ::std::result::Result::Err(e) = hb.allocate() {
        return ::std::result::Result::Err(format!("Header allocation failed: {:?}", e));
    }
    for (name, value) in headers {
        hb.append(name.as_bytes(), value.as_bytes());
    }

    let entry_list = hb.entries;
    let headers_buf: &[u8] = unsafe {
        if let Some(ptr) = hb.content.ptr {
            ::std::slice::from_raw_parts(ptr.as_ptr(), hb.content.len)
        } else {
            &[]
        }
    };

    // Allocate response buffer — send_sync writes the response body here
    let response_buffer = Box::into_raw(Box::new(MutableString::default()));

    let body_slice: &[u8] = body.unwrap_or_default();

    let mut async_http = AsyncHTTP::init_sync(
        method,
        parsed_url,
        entry_list,
        headers_buf,
        response_buffer,
        body_slice,
        None, // http_proxy
        None, // hostname
        FetchRedirect::Follow,
    );

    let result = async_http.send_sync().map_err(|e| format!("{:?}", e))?;

    // Read body from response_buffer via zero-copy take (avoids clone of potentially MB-sized buffer)
    let body_vec = unsafe { std::mem::take(&mut (*response_buffer).list) };

    // Reclaim response buffer
    unsafe {
        drop(Box::from_raw(response_buffer));
    }

    // Extract fields from picohttp::Response into owned HttpResponse
    let status_code = result.status_code;
    let status_text = CompactString::new(::std::str::from_utf8(result.status).unwrap_or(""));

    let headers: SmallVec<[(CompactString, CompactString); 8]> = result
        .headers
        .list
        .iter()
        .map(|h| {
            let name = CompactString::new(::std::str::from_utf8(h.name()).unwrap_or(""));
            let value = CompactString::new(::std::str::from_utf8(h.value()).unwrap_or(""));
            (name, value)
        })
        .collect();

    ::std::result::Result::Ok(HttpResponse {
        status_code,
        status_text,
        headers,
        body: Bytes::from(bun_core::vec::chan_vec_to_std(body_vec)),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_method_roundtrip() {
        assert_eq!(Method::GET.as_str(), "GET");
        assert_eq!(Method::POST.as_str(), "POST");
        assert_eq!(Method::PUT.as_str(), "PUT");
        assert_eq!(Method::DELETE.as_str(), "DELETE");
        assert_eq!(Method::PATCH.as_str(), "PATCH");
        assert_eq!(Method::HEAD.as_str(), "HEAD");
    }

    #[test]
    fn test_http_response_construction() {
        let resp = HttpResponse {
            status_code: 200,
            status_text: CompactString::new("OK"),
            headers: smallvec::smallvec![("Content-Type".into(), "text/html".into())],
            body: Bytes::from_static(b"hello"),
        };
        assert_eq!(resp.status_code, 200);
        assert_eq!(resp.status_text, "OK");
        assert_eq!(resp.headers.len(), 1);
        assert_eq!(&resp.body[..], b"hello");
    }

    // ─── HttpResponse extended tests ──────────────────────────────
    // @trace REQ-ENG-007 [req:REQ-ENG-007] [level:unit]

    #[test]
    fn test_http_response_empty_body() {
        let resp = HttpResponse {
            status_code: 204,
            status_text: CompactString::new("No Content"),
            headers: SmallVec::new(),
            body: Bytes::new(),
        };
        assert_eq!(resp.status_code, 204);
        assert!(resp.body.is_empty());
        assert!(resp.headers.is_empty());
    }

    #[test]
    fn test_http_response_multiple_headers() {
        let resp = HttpResponse {
            status_code: 200,
            status_text: CompactString::new("OK"),
            headers: smallvec::smallvec![
                ("content-type".into(), "application/json".into()),
                ("x-request-id".into(), "abc-123".into()),
                ("cache-control".into(), "no-cache".into()),
            ],
            body: Bytes::from_static(b"{}"),
        };
        assert_eq!(resp.headers.len(), 3);
        assert_eq!(resp.headers[0].0, "content-type");
        assert_eq!(resp.headers[1].1, "abc-123");
    }

    #[test]
    fn test_http_response_error_status() {
        let resp = HttpResponse {
            status_code: 500,
            status_text: CompactString::new("Internal Server Error"),
            headers: SmallVec::new(),
            body: Bytes::from_static(b"error"),
        };
        assert_eq!(resp.status_code, 500);
        assert_eq!(resp.status_text, "Internal Server Error");
    }

    #[test]
    fn test_http_response_redirect_status() {
        let resp = HttpResponse {
            status_code: 301,
            status_text: CompactString::new("Moved Permanently"),
            headers: smallvec::smallvec![("location".into(), "https://example.com".into())],
            body: Bytes::new(),
        };
        assert_eq!(resp.status_code, 301);
        assert_eq!(resp.headers[0].0, "location");
    }

    #[test]
    fn test_method_all_variants() {
        assert_eq!(Method::GET.as_str(), "GET");
        assert_eq!(Method::POST.as_str(), "POST");
        assert_eq!(Method::PUT.as_str(), "PUT");
        assert_eq!(Method::DELETE.as_str(), "DELETE");
        assert_eq!(Method::PATCH.as_str(), "PATCH");
        assert_eq!(Method::HEAD.as_str(), "HEAD");
        assert_eq!(Method::OPTIONS.as_str(), "OPTIONS");
    }

    #[test]
    fn test_method_connect_trace() {
        assert_eq!(Method::CONNECT.as_str(), "CONNECT");
        assert_eq!(Method::TRACE.as_str(), "TRACE");
    }

    // ─── http_client extended edge case tests ────────────────
    // @trace REQ-ENG-007 [req:REQ-ENG-007] [level:unit]

    #[test]
    fn test_http_response_status_codes_range() {
        for code in [
            200, 201, 204, 301, 302, 304, 400, 401, 403, 404, 500, 502, 503,
        ] {
            let resp = HttpResponse {
                status_code: code,
                status_text: CompactString::new(""),
                headers: SmallVec::new(),
                body: Bytes::new(),
            };
            assert_eq!(resp.status_code, code);
        }
    }

    #[test]
    fn test_http_response_body_binary() {
        let resp = HttpResponse {
            status_code: 200,
            status_text: CompactString::new("OK"),
            headers: SmallVec::new(),
            body: Bytes::from(vec![0x89, 0x50, 0x4E, 0x47]),
        };
        assert_eq!(&resp.body[..4], &[0x89, 0x50, 0x4E, 0x47]);
    }

    #[test]
    fn test_http_response_header_value_with_semicolon() {
        let resp = HttpResponse {
            status_code: 200,
            status_text: CompactString::new("OK"),
            headers: smallvec::smallvec![(
                "content-type".into(),
                "text/html; charset=utf-8".into()
            )],
            body: Bytes::new(),
        };
        assert!(resp.headers[0].1.contains("charset=utf-8"));
    }

    #[test]
    fn test_http_response_large_body() {
        let large_body: Vec<u8> = (0..10_000).map(|i| (i % 256) as u8).collect();
        let resp = HttpResponse {
            status_code: 200,
            status_text: CompactString::new("OK"),
            headers: SmallVec::new(),
            body: Bytes::from(large_body.clone()),
        };
        assert_eq!(resp.body.len(), 10_000);
        assert_eq!(resp.body[0], 0);
        assert_eq!(resp.body[255], 255);
    }

    #[test]
    fn test_http_response_header_order_preserved() {
        let resp = HttpResponse {
            status_code: 200,
            status_text: CompactString::new("OK"),
            headers: smallvec::smallvec![
                ("x-first".into(), "1".into()),
                ("x-second".into(), "2".into()),
                ("x-third".into(), "3".into()),
            ],
            body: Bytes::new(),
        };
        assert_eq!(resp.headers[0].0, "x-first");
        assert_eq!(resp.headers[1].0, "x-second");
        assert_eq!(resp.headers[2].0, "x-third");
    }

    #[test]
    fn test_http_response_status_4xx() {
        for code in [400, 401, 403, 404, 405, 408, 429] {
            let resp = HttpResponse {
                status_code: code,
                status_text: CompactString::new(""),
                headers: SmallVec::new(),
                body: Bytes::new(),
            };
            assert!(resp.status_code >= 400 && resp.status_code < 500);
        }
    }

    #[test]
    fn test_http_response_status_5xx() {
        for code in [500, 502, 503, 504] {
            let resp = HttpResponse {
                status_code: code,
                status_text: CompactString::new(""),
                headers: SmallVec::new(),
                body: Bytes::new(),
            };
            assert!(resp.status_code >= 500 && resp.status_code < 600);
        }
    }

    #[test]
    fn test_method_debug_format() {
        let _ = format!("{:?}", Method::GET);
        let _ = format!("{:?}", Method::POST);
    }

    #[test]
    fn test_http_response_unicode_body() {
        let unicode_body = "你好世界".as_bytes().to_vec();
        let resp = HttpResponse {
            status_code: 200,
            status_text: CompactString::new("OK"),
            headers: smallvec::smallvec![(
                "content-type".into(),
                "text/plain; charset=utf-8".into()
            )],
            body: Bytes::from(unicode_body.clone()),
        };
        assert_eq!(&resp.body[..], &unicode_body[..]);
    }

    #[test]
    fn test_http_response_empty_status_text() {
        let resp = HttpResponse {
            status_code: 200,
            status_text: CompactString::new(""),
            headers: SmallVec::new(),
            body: Bytes::new(),
        };
        assert!(resp.status_text.is_empty());
    }

    #[test]
    fn test_http_response_header_duplicate_names() {
        let resp = HttpResponse {
            status_code: 200,
            status_text: CompactString::new("OK"),
            headers: smallvec::smallvec![
                ("set-cookie".into(), "a=1".into()),
                ("set-cookie".into(), "b=2".into()),
            ],
            body: Bytes::new(),
        };
        assert_eq!(resp.headers.len(), 2);
        assert_eq!(resp.headers[0].0, "set-cookie");
        assert_eq!(resp.headers[1].0, "set-cookie");
        assert_ne!(resp.headers[0].1, resp.headers[1].1);
    }

    // ── Zero-copy / zero-alloc optimization tests ──────────────────
    // @trace REQ-PURE-002 [req:REQ-PURE-002] [level:unit]

    /// CompactString inlines short status texts like "OK" — no heap allocation.
    #[test]
    fn test_short_status_text_no_heap_alloc() {
        let short = CompactString::new("OK");
        assert_eq!(short.len(), 2);
        assert_eq!(&*short, "OK");
        // CompactString inlines strings up to 24 bytes on 64-bit platforms
        let longer = CompactString::new("Internal Server Error");
        assert_eq!(&*longer, "Internal Server Error");
    }

    /// SmallVec stacks ≤8 header pairs — no heap allocation for typical responses.
    #[test]
    fn test_small_headers_stack_allocated() {
        let headers: SmallVec<[(CompactString, CompactString); 8]> = smallvec::smallvec![
            ("content-type".into(), "text/html".into()),
            ("content-length".into(), "42".into()),
            ("server".into(), "bao".into()),
        ];
        assert_eq!(headers.len(), 3);
        // ≤8 items: stored on the stack (no heap allocation)
        assert!(headers.len() <= 8);
    }

    /// Bytes::from(Vec) is zero-copy — the Vec's buffer is moved into Bytes without cloning.
    #[test]
    fn test_body_take_no_clone() {
        let original = vec![0xDE, 0xAD, 0xBE, 0xEF];
        let ptr = original.as_ptr();
        let b = Bytes::from(original);
        // Bytes::from(Vec) reuses the same allocation — pointer is identical
        assert_eq!(
            b.as_ptr(),
            ptr,
            "Bytes::from(Vec) must reuse the same allocation (zero-copy)"
        );
        assert_eq!(&b[..], &[0xDE, 0xAD, 0xBE, 0xEF]);
    }
}