Skip to main content

harn_vm/stdlib/
http_response.rs

1//! HTTP response codec primitives for `.harn` HTTP handlers.
2//!
3//! Handlers hosted on `harn-serve` build their replies with these
4//! builtins instead of bare JSON dicts. The codec on the server side
5//! (`harn_serve::http_codec`) recognises the tagged record, lifts
6//! status/headers/body out of it, and renders it as a proper HTTP
7//! response — JSON, no-content, error envelope, buffered stream, or
8//! Server-Sent Events.
9//!
10//! The tag is the literal string `"v1"` under the
11//! `__http_response__` key. Plain dicts that happen to define
12//! `status`/`headers`/`body` are not picked up by the codec; only the
13//! tagged record is.
14//!
15//! Channel-bearing bodies (`http_stream(channel)`, `http_sse(channel)`)
16//! are drained inside the builtin before the handler returns. This
17//! keeps the v1 codec wire-format JSON-only — the channel is
18//! materialised into a list of chunks/events. Authors write the same
19//! code that true streaming will accept; only the on-the-wire timing
20//! differs.
21
22use std::collections::BTreeMap;
23use std::rc::Rc;
24
25use sha2::{Digest, Sha256};
26
27use crate::stdlib::macros::{harn_builtin, VmBuiltinDef};
28use crate::value::{VmError, VmValue};
29use crate::vm::Vm;
30
31/// Tag key + version that the harn-serve codec keys off of.
32pub const HTTP_RESPONSE_TAG_KEY: &str = "__http_response__";
33pub const HTTP_RESPONSE_TAG_VERSION: &str = "v1";
34
35const BODY_KIND_JSON: &str = "json";
36const BODY_KIND_NONE: &str = "none";
37const BODY_KIND_STREAM: &str = "stream";
38const BODY_KIND_SSE: &str = "sse";
39
40pub(crate) fn register_http_response_builtins(vm: &mut Vm) {
41    for def in MODULE_BUILTINS {
42        vm.register_builtin_def(def);
43    }
44}
45
46#[harn_builtin(sig = "http_ok(body: any?) -> dict", category = "http_response")]
47fn http_ok_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
48    let body = args.first().cloned().unwrap_or(VmValue::Nil);
49    Ok(envelope(200, body, BODY_KIND_JSON, BTreeMap::new()))
50}
51
52#[harn_builtin(
53    sig = "http_created(body: any?, location?: string?) -> dict",
54    category = "http_response"
55)]
56fn http_created_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
57    let body = args.first().cloned().unwrap_or(VmValue::Nil);
58    let mut headers = BTreeMap::new();
59    if let Some(location) = args.get(1).and_then(string_or_nil) {
60        headers.insert("Location".to_string(), VmValue::String(Rc::from(location)));
61    }
62    Ok(envelope(201, body, BODY_KIND_JSON, headers))
63}
64
65#[harn_builtin(sig = "http_no_content() -> dict", category = "http_response")]
66fn http_no_content_impl(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
67    Ok(envelope(204, VmValue::Nil, BODY_KIND_NONE, BTreeMap::new()))
68}
69
70#[harn_builtin(
71    sig = "http_error(status: int, code: string, message: string, details?: any) -> dict",
72    category = "http_response"
73)]
74fn http_error_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
75    let status = require_status(args.first(), "http_error")?;
76    if !(400..=599).contains(&status) {
77        return Err(thrown_err(format!(
78            "http_error: status must be 4xx or 5xx (got {status})"
79        )));
80    }
81    let code = require_nonempty_string(args.get(1), "http_error", "code")?;
82    let message = require_nonempty_string(args.get(2), "http_error", "message")?;
83    let details = args.get(3).cloned().unwrap_or(VmValue::Nil);
84
85    let mut body = BTreeMap::new();
86    body.insert("code".to_string(), VmValue::String(Rc::from(code)));
87    body.insert("message".to_string(), VmValue::String(Rc::from(message)));
88    if !matches!(details, VmValue::Nil) {
89        body.insert("details".to_string(), details);
90    }
91    let mut env = envelope_map(
92        status,
93        VmValue::Dict(Rc::new(body)),
94        BODY_KIND_JSON,
95        BTreeMap::new(),
96    );
97    env.insert("is_error".to_string(), VmValue::Bool(true));
98    Ok(VmValue::Dict(Rc::new(env)))
99}
100
101#[harn_builtin(
102    sig = "http_reply(status: int, body?: any, headers?: dict) -> dict",
103    category = "http_response"
104)]
105fn http_reply_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
106    let status = require_status(args.first(), "http_reply")?;
107    let body = args.get(1).cloned().unwrap_or(VmValue::Nil);
108    let headers = parse_headers(args.get(2), "http_reply")?;
109    let body_kind = if status == 204 || status == 304 || matches!(body, VmValue::Nil) {
110        BODY_KIND_NONE
111    } else {
112        BODY_KIND_JSON
113    };
114    let body_for_envelope = if body_kind == BODY_KIND_NONE {
115        VmValue::Nil
116    } else {
117        body
118    };
119    Ok(envelope(status, body_for_envelope, body_kind, headers))
120}
121
122#[harn_builtin(
123    sig = "http_stream(source: any, content_type?: string?) -> dict",
124    kind = "async",
125    category = "http_response"
126)]
127async fn http_stream_impl(args: Vec<VmValue>) -> Result<VmValue, VmError> {
128    let source = args
129        .first()
130        .cloned()
131        .ok_or_else(|| thrown_err("http_stream: source is required"))?;
132    let content_type = args
133        .get(1)
134        .and_then(string_or_nil)
135        .unwrap_or_else(|| "application/octet-stream".to_string());
136
137    let chunks = drain_to_list(source, "http_stream").await?;
138    let mut headers = BTreeMap::new();
139    headers.insert(
140        "Content-Type".to_string(),
141        VmValue::String(Rc::from(content_type)),
142    );
143    Ok(envelope(
144        200,
145        VmValue::List(Rc::new(chunks)),
146        BODY_KIND_STREAM,
147        headers,
148    ))
149}
150
151#[harn_builtin(
152    sig = "http_sse(source: any, retry_ms?: int?) -> dict",
153    kind = "async",
154    category = "http_response"
155)]
156async fn http_sse_impl(args: Vec<VmValue>) -> Result<VmValue, VmError> {
157    let source = args
158        .first()
159        .cloned()
160        .ok_or_else(|| thrown_err("http_sse: source is required"))?;
161    let retry_ms = match args.get(1) {
162        None | Some(VmValue::Nil) => None,
163        Some(VmValue::Int(value)) => {
164            if *value < 0 {
165                return Err(thrown_err(format!(
166                    "http_sse: retry_ms must be non-negative (got {value})"
167                )));
168            }
169            Some(*value)
170        }
171        Some(other) => {
172            return Err(thrown_err(format!(
173                "http_sse: retry_ms must be an integer (got {})",
174                other.type_name()
175            )));
176        }
177    };
178
179    let events = drain_to_list(source, "http_sse").await?;
180    let mut headers = BTreeMap::new();
181    headers.insert(
182        "Content-Type".to_string(),
183        VmValue::String(Rc::from("text/event-stream")),
184    );
185    headers.insert(
186        "Cache-Control".to_string(),
187        VmValue::String(Rc::from("no-cache")),
188    );
189    let mut env = envelope_map(200, VmValue::List(Rc::new(events)), BODY_KIND_SSE, headers);
190    if let Some(retry_ms) = retry_ms {
191        env.insert("retry_ms".to_string(), VmValue::Int(retry_ms));
192    }
193    Ok(VmValue::Dict(Rc::new(env)))
194}
195
196fn envelope(
197    status: i64,
198    body: VmValue,
199    body_kind: &str,
200    headers: BTreeMap<String, VmValue>,
201) -> VmValue {
202    VmValue::Dict(Rc::new(envelope_map(status, body, body_kind, headers)))
203}
204
205fn envelope_map(
206    status: i64,
207    body: VmValue,
208    body_kind: &str,
209    headers: BTreeMap<String, VmValue>,
210) -> BTreeMap<String, VmValue> {
211    let mut map = BTreeMap::new();
212    map.insert(
213        HTTP_RESPONSE_TAG_KEY.to_string(),
214        VmValue::String(Rc::from(HTTP_RESPONSE_TAG_VERSION)),
215    );
216    map.insert("status".to_string(), VmValue::Int(status));
217    map.insert(
218        "body_kind".to_string(),
219        VmValue::String(Rc::from(body_kind)),
220    );
221    map.insert("headers".to_string(), VmValue::Dict(Rc::new(headers)));
222    if !matches!(body, VmValue::Nil) {
223        map.insert("body".to_string(), body);
224    }
225    map
226}
227
228fn require_status(value: Option<&VmValue>, fn_name: &str) -> Result<i64, VmError> {
229    let status = match value {
230        Some(VmValue::Int(value)) => *value,
231        Some(other) => {
232            return Err(thrown_err(format!(
233                "{fn_name}: status must be an integer (got {})",
234                other.type_name()
235            )));
236        }
237        None => {
238            return Err(thrown_err(format!("{fn_name}: status is required")));
239        }
240    };
241    if !(100..=599).contains(&status) {
242        return Err(thrown_err(format!(
243            "{fn_name}: status {status} is out of range (100-599)"
244        )));
245    }
246    Ok(status)
247}
248
249fn require_nonempty_string(
250    value: Option<&VmValue>,
251    fn_name: &str,
252    arg_name: &str,
253) -> Result<String, VmError> {
254    let text = match value {
255        Some(VmValue::String(text)) => text.to_string(),
256        Some(other) => {
257            return Err(thrown_err(format!(
258                "{fn_name}: {arg_name} must be a string (got {})",
259                other.type_name()
260            )));
261        }
262        None => {
263            return Err(thrown_err(format!("{fn_name}: {arg_name} is required")));
264        }
265    };
266    if text.is_empty() {
267        return Err(thrown_err(format!(
268            "{fn_name}: {arg_name} must be non-empty"
269        )));
270    }
271    Ok(text)
272}
273
274fn string_or_nil(value: &VmValue) -> Option<String> {
275    match value {
276        VmValue::String(text) if !text.is_empty() => Some(text.to_string()),
277        _ => None,
278    }
279}
280
281fn parse_headers(
282    value: Option<&VmValue>,
283    fn_name: &str,
284) -> Result<BTreeMap<String, VmValue>, VmError> {
285    match value {
286        None | Some(VmValue::Nil) => Ok(BTreeMap::new()),
287        Some(VmValue::Dict(dict)) => Ok((**dict).clone()),
288        Some(other) => Err(thrown_err(format!(
289            "{fn_name}: headers must be a dict (got {})",
290            other.type_name()
291        ))),
292    }
293}
294
295/// Drain a channel into a `Vec<VmValue>`, or pass a list through verbatim.
296///
297/// The drain stops when the channel is closed and all queued values have
298/// been consumed. Note: `close_channel(chan)` sets a flag — it does
299/// **not** drop the channel's `Sender`, so a naive `rx.recv().await`
300/// would block forever for channel-typed sources. We instead poll with
301/// `try_recv` and observe the `closed` flag; when both report empty,
302/// the drain terminates.
303async fn drain_to_list(value: VmValue, fn_name: &str) -> Result<Vec<VmValue>, VmError> {
304    use std::sync::atomic::Ordering;
305    use tokio::sync::mpsc::error::TryRecvError;
306
307    match value {
308        VmValue::List(items) => Ok(items.iter().cloned().collect()),
309        VmValue::Channel(handle) => {
310            let mut items = Vec::new();
311            let mut rx = handle.receiver.lock().await;
312            loop {
313                match rx.try_recv() {
314                    Ok(value) => items.push(value),
315                    Err(TryRecvError::Empty) => {
316                        if handle.closed.load(Ordering::SeqCst) {
317                            break;
318                        }
319                        // Yield so the producer can deliver the next
320                        // value; if the channel is still empty after
321                        // the producer has done its work, the next
322                        // pass will see it closed.
323                        tokio::task::yield_now().await;
324                    }
325                    Err(TryRecvError::Disconnected) => break,
326                }
327            }
328            Ok(items)
329        }
330        other => Err(thrown_err(format!(
331            "{fn_name}: source must be a list or channel (got {})",
332            other.type_name()
333        ))),
334    }
335}
336
337fn thrown_err(message: impl Into<String>) -> VmError {
338    VmError::Thrown(VmValue::String(Rc::from(message.into())))
339}
340
341/// Return `Some(envelope)` if the JSON value is a tagged HTTP response.
342///
343/// Used by the harn-serve HTTP codec to detect that a `.harn` handler
344/// opted into structured HTTP semantics rather than the default `200
345/// {result}` shape.
346pub fn parse_envelope(value: &serde_json::Value) -> Option<HttpEnvelope> {
347    let obj = value.as_object()?;
348    let tag = obj.get(HTTP_RESPONSE_TAG_KEY)?.as_str()?;
349    if tag != HTTP_RESPONSE_TAG_VERSION {
350        return None;
351    }
352    let status = obj.get("status")?.as_u64()? as u16;
353    let body_kind = obj
354        .get("body_kind")
355        .and_then(|v| v.as_str())
356        .unwrap_or(BODY_KIND_JSON)
357        .to_string();
358    let headers = obj
359        .get("headers")
360        .and_then(|v| v.as_object())
361        .map(|map| {
362            map.iter()
363                .map(|(key, value)| {
364                    let header = match value {
365                        serde_json::Value::String(s) => HttpHeaderValue::Single(s.clone()),
366                        serde_json::Value::Array(values) => HttpHeaderValue::Multi(
367                            values
368                                .iter()
369                                .filter_map(|v| v.as_str().map(str::to_string))
370                                .collect(),
371                        ),
372                        other => HttpHeaderValue::Single(other.to_string()),
373                    };
374                    (key.clone(), header)
375                })
376                .collect::<BTreeMap<_, _>>()
377        })
378        .unwrap_or_default();
379    let body = obj.get("body").cloned();
380    let retry_ms = obj.get("retry_ms").and_then(|v| v.as_u64());
381    let is_error = obj
382        .get("is_error")
383        .and_then(|v| v.as_bool())
384        .unwrap_or(false);
385    let ws_upgrade = obj
386        .get("ws_upgrade")
387        .and_then(|v| v.as_object())
388        .map(|map| {
389            let subprotocol = map
390                .get("subprotocol")
391                .and_then(|v| v.as_str())
392                .map(str::to_string);
393            let offered = map
394                .get("offered")
395                .and_then(|v| v.as_array())
396                .map(|values| {
397                    values
398                        .iter()
399                        .filter_map(|v| v.as_str().map(str::to_string))
400                        .collect()
401                })
402                .unwrap_or_default();
403            let idle_ping_ms = map.get("idle_ping_ms").and_then(|v| v.as_u64());
404            let max_message_bytes = map.get("max_message_bytes").and_then(|v| v.as_u64());
405            WsUpgradeSpec {
406                subprotocol,
407                offered,
408                idle_ping_ms,
409                max_message_bytes,
410            }
411        });
412    Some(HttpEnvelope {
413        status,
414        body_kind,
415        headers,
416        body,
417        retry_ms,
418        is_error,
419        ws_upgrade,
420    })
421}
422
423#[derive(Debug, Clone)]
424pub struct HttpEnvelope {
425    pub status: u16,
426    pub body_kind: String,
427    pub headers: BTreeMap<String, HttpHeaderValue>,
428    pub body: Option<serde_json::Value>,
429    pub retry_ms: Option<u64>,
430    pub is_error: bool,
431    /// Populated when the handler returned an `http_upgrade_ws(...)`
432    /// envelope. The hosting adapter detects this and routes the
433    /// upgrade through `harn_serve::ws_route` instead of rendering the
434    /// 101 response as plain HTTP.
435    pub ws_upgrade: Option<WsUpgradeSpec>,
436}
437
438#[derive(Debug, Clone, Default)]
439pub struct WsUpgradeSpec {
440    pub subprotocol: Option<String>,
441    pub offered: Vec<String>,
442    pub idle_ping_ms: Option<u64>,
443    pub max_message_bytes: Option<u64>,
444}
445
446#[derive(Debug, Clone)]
447pub enum HttpHeaderValue {
448    Single(String),
449    Multi(Vec<String>),
450}
451
452impl HttpHeaderValue {
453    pub fn values(&self) -> Box<dyn Iterator<Item = &str> + '_> {
454        match self {
455            Self::Single(value) => Box::new(std::iter::once(value.as_str())),
456            Self::Multi(values) => Box::new(values.iter().map(String::as_str)),
457        }
458    }
459}
460
461#[harn_builtin(sig = "http_etag(body: any) -> string", category = "http_response")]
462fn http_etag_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
463    let body = args
464        .first()
465        .ok_or_else(|| thrown_err("http_etag: body is required"))?;
466    let bytes = value_as_bytes(body);
467    let mut hasher = Sha256::new();
468    hasher.update(&bytes);
469    let digest = hasher.finalize();
470    Ok(VmValue::String(Rc::from(format!(
471        "\"{}\"",
472        hex::encode(digest)
473    ))))
474}
475
476#[harn_builtin(
477    sig = "http_choose(accept: string?, offers: list, default?: string?) -> string",
478    category = "http_response"
479)]
480fn http_choose_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
481    let accept = optional_string_arg(args.first(), "http_choose", "accept")?;
482    let offers_value = args
483        .get(1)
484        .ok_or_else(|| thrown_err("http_choose: offers is required"))?;
485    let offers = expect_string_list(offers_value, "http_choose", "offers")?;
486    if offers.is_empty() {
487        return Err(thrown_err("http_choose: offers must be non-empty"));
488    }
489    let default = optional_string_arg(args.get(2), "http_choose", "default")?
490        .unwrap_or_else(|| offers[0].clone());
491
492    let chosen = match accept.as_deref() {
493        None | Some("") | Some("*/*") => default,
494        Some(header) => negotiate_accept(header, &offers).unwrap_or(default),
495    };
496    Ok(VmValue::String(Rc::from(chosen)))
497}
498
499fn optional_string_arg(
500    value: Option<&VmValue>,
501    builtin: &str,
502    arg_name: &str,
503) -> Result<Option<String>, VmError> {
504    match value {
505        None | Some(VmValue::Nil) => Ok(None),
506        Some(VmValue::String(text)) => Ok(Some(text.to_string())),
507        Some(other) => Err(thrown_err(format!(
508            "{builtin}: {arg_name} must be a string or nil (got {})",
509            other.type_name()
510        ))),
511    }
512}
513
514fn expect_string_list(
515    value: &VmValue,
516    builtin: &str,
517    arg_name: &str,
518) -> Result<Vec<String>, VmError> {
519    let items = match value {
520        VmValue::List(items) => items,
521        other => {
522            return Err(thrown_err(format!(
523                "{builtin}: {arg_name} must be a list (got {})",
524                other.type_name()
525            )));
526        }
527    };
528    items
529        .iter()
530        .map(|value| match value {
531            VmValue::String(text) => Ok(text.to_string()),
532            other => Err(thrown_err(format!(
533                "{builtin}: {arg_name} must contain strings (got {})",
534                other.type_name()
535            ))),
536        })
537        .collect()
538}
539
540#[harn_builtin(
541    sig = "http_not_modified(etag?: string?, headers?: dict) -> dict",
542    category = "http_response"
543)]
544fn http_not_modified_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
545    let mut headers = parse_headers(args.get(1), "http_not_modified")?;
546    if let Some(etag) = args.first().and_then(string_or_nil) {
547        headers.insert("ETag".to_string(), VmValue::String(Rc::from(etag)));
548    }
549    Ok(envelope(304, VmValue::Nil, BODY_KIND_NONE, headers))
550}
551
552#[harn_builtin(
553    sig = "http_push_hints(envelope: dict, paths: list) -> dict",
554    category = "http_response"
555)]
556fn http_push_hints_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
557    // Pull the inbound envelope. We require it to be a tagged
558    // `http_response` envelope so the codec on the other side actually
559    // applies the Link headers — wrapping a plain dict would silently
560    // no-op once it reached the wire.
561    let envelope = args
562        .first()
563        .and_then(VmValue::as_dict)
564        .ok_or_else(|| thrown_err("http_push_hints: envelope must be a dict"))?;
565    if !is_http_response_envelope(envelope) {
566        return Err(thrown_err(
567            "http_push_hints: envelope must be an http_response envelope \
568             (use http_ok, http_reply, etc. before calling this)",
569        ));
570    }
571
572    let paths = match args.get(1) {
573        Some(VmValue::List(items)) => items.clone(),
574        Some(other) => {
575            return Err(thrown_err(format!(
576                "http_push_hints: paths must be a list (got {})",
577                other.type_name()
578            )));
579        }
580        None => {
581            return Err(thrown_err("http_push_hints: paths is required"));
582        }
583    };
584
585    let mut new_links: Vec<String> = Vec::with_capacity(paths.len());
586    for item in paths.iter() {
587        match item {
588            VmValue::String(text) => {
589                let path = text.as_ref();
590                if path.is_empty() {
591                    return Err(thrown_err(
592                        "http_push_hints: paths must not contain empty strings",
593                    ));
594                }
595                new_links.push(format_link_header(path));
596            }
597            other => {
598                return Err(thrown_err(format!(
599                    "http_push_hints: paths must contain strings (got {})",
600                    other.type_name()
601                )));
602            }
603        }
604    }
605
606    if new_links.is_empty() {
607        return Ok(VmValue::Dict(envelope.clone().into()));
608    }
609
610    let mut envelope_map = (*envelope).clone();
611    let mut headers = envelope_map
612        .get("headers")
613        .and_then(VmValue::as_dict)
614        .cloned()
615        .unwrap_or_default();
616
617    // Preserve any pre-existing Link header(s) the handler already set.
618    let mut combined: Vec<VmValue> = match headers.get("Link") {
619        Some(VmValue::String(existing)) => vec![VmValue::String(existing.clone())],
620        Some(VmValue::List(items)) => items.iter().cloned().collect(),
621        _ => Vec::new(),
622    };
623    combined.extend(
624        new_links
625            .into_iter()
626            .map(|link| VmValue::String(Rc::from(link))),
627    );
628
629    headers.insert("Link".to_string(), VmValue::List(Rc::new(combined)));
630    envelope_map.insert("headers".to_string(), VmValue::Dict(Rc::new(headers)));
631    Ok(VmValue::Dict(Rc::new(envelope_map)))
632}
633
634fn is_http_response_envelope(map: &BTreeMap<String, VmValue>) -> bool {
635    matches!(
636        map.get(HTTP_RESPONSE_TAG_KEY),
637        Some(VmValue::String(tag)) if tag.as_ref() == HTTP_RESPONSE_TAG_VERSION,
638    )
639}
640
641fn format_link_header(path: &str) -> String {
642    match infer_preload_as(path) {
643        Some(kind) => format!("<{path}>; rel=preload; as={kind}"),
644        None => format!("<{path}>; rel=preload"),
645    }
646}
647
648/// Map the asset extension to its `as=` attribute per the HTML living
649/// standard's [destination table]. Unknown extensions emit a bare
650/// `rel=preload` and let the browser decline the hint rather than
651/// guessing — `as=` mismatch silently invalidates the preload.
652///
653/// [destination table]: https://html.spec.whatwg.org/multipage/links.html#link-type-preload
654fn infer_preload_as(path: &str) -> Option<&'static str> {
655    // Strip any query string / fragment before extension lookup. Paths
656    // like `/main.js?v=42` should still infer `script`.
657    let pre_query = path.split(['?', '#']).next().unwrap_or(path);
658    let dot = pre_query.rfind('.')?;
659    let ext = &pre_query[dot + 1..];
660    Some(match ext.to_ascii_lowercase().as_str() {
661        "css" => "style",
662        "js" | "mjs" => "script",
663        "json" => "fetch",
664        "png" | "jpg" | "jpeg" | "gif" | "webp" | "svg" | "avif" | "ico" => "image",
665        "woff" | "woff2" | "ttf" | "otf" => "font",
666        _ => return None,
667    })
668}
669
670#[harn_builtin(
671    sig = "http_upgrade_ws(req: dict, options?: dict) -> dict",
672    category = "http_response"
673)]
674fn http_upgrade_ws_impl(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
675    let req = args
676        .first()
677        .and_then(VmValue::as_dict)
678        .ok_or_else(|| thrown_err("http_upgrade_ws: req must be a dict"))?;
679    let options = args.get(1).and_then(VmValue::as_dict);
680
681    let request_subprotocols = req
682        .get("headers")
683        .and_then(VmValue::as_dict)
684        .and_then(|headers| header_lookup(headers, "sec-websocket-protocol"))
685        .map(|raw| {
686            raw.split(',')
687                .map(|s| s.trim().to_string())
688                .filter(|s| !s.is_empty())
689                .collect::<Vec<_>>()
690        })
691        .unwrap_or_default();
692    let offered_subprotocols = options
693        .and_then(|opts| opts.get("subprotocols"))
694        .and_then(|value| match value {
695            VmValue::List(items) => Some(
696                items
697                    .iter()
698                    .filter_map(|v| match v {
699                        VmValue::String(s) => Some(s.to_string()),
700                        _ => None,
701                    })
702                    .collect::<Vec<_>>(),
703            ),
704            _ => None,
705        })
706        .unwrap_or_default();
707
708    // Pick the first *client-preferred* subprotocol the server can
709    // serve. This must match the convention in
710    // `harn_serve::ws::negotiate_subprotocol` — if the two
711    // disagreed, the builtin's envelope would carry one subprotocol
712    // while the actual upgrade handshake echoed back another.
713    let negotiated = request_subprotocols
714        .iter()
715        .find(|client| offered_subprotocols.iter().any(|name| name == *client))
716        .cloned();
717
718    let mut headers = BTreeMap::new();
719    headers.insert(
720        "Upgrade".to_string(),
721        VmValue::String(Rc::from("websocket")),
722    );
723    headers.insert(
724        "Connection".to_string(),
725        VmValue::String(Rc::from("Upgrade")),
726    );
727    if let Some(name) = &negotiated {
728        headers.insert(
729            "Sec-WebSocket-Protocol".to_string(),
730            VmValue::String(Rc::from(name.clone())),
731        );
732    }
733
734    let idle_ping_ms = options
735        .and_then(|opts| opts.get("idle_ping_ms"))
736        .and_then(|v| v.as_int());
737    let max_message_bytes = options
738        .and_then(|opts| opts.get("max_message_bytes"))
739        .and_then(|v| v.as_int());
740
741    let mut env_map = envelope_map(101, VmValue::Nil, BODY_KIND_NONE, headers);
742    env_map.insert(
743        "ws_upgrade".to_string(),
744        VmValue::Dict(Rc::new({
745            let mut map = BTreeMap::new();
746            map.insert(
747                "subprotocol".to_string(),
748                match &negotiated {
749                    Some(name) => VmValue::String(Rc::from(name.clone())),
750                    None => VmValue::Nil,
751                },
752            );
753            map.insert(
754                "offered".to_string(),
755                VmValue::List(Rc::new(
756                    offered_subprotocols
757                        .iter()
758                        .map(|s| VmValue::String(Rc::from(s.clone())))
759                        .collect(),
760                )),
761            );
762            if let Some(ms) = idle_ping_ms {
763                map.insert("idle_ping_ms".to_string(), VmValue::Int(ms));
764            }
765            if let Some(bytes) = max_message_bytes {
766                map.insert("max_message_bytes".to_string(), VmValue::Int(bytes));
767            }
768            map
769        })),
770    );
771    Ok(VmValue::Dict(Rc::new(env_map)))
772}
773
774fn header_lookup(headers: &BTreeMap<String, VmValue>, name: &str) -> Option<String> {
775    let needle = name.to_ascii_lowercase();
776    headers
777        .iter()
778        .find(|(key, _)| key.to_ascii_lowercase() == needle)
779        .and_then(|(_, value)| match value {
780            VmValue::String(text) => Some(text.to_string()),
781            _ => None,
782        })
783}
784
785fn value_as_bytes(value: &VmValue) -> Vec<u8> {
786    match value {
787        VmValue::Bytes(bytes) => bytes.as_ref().clone(),
788        VmValue::String(text) => text.as_bytes().to_vec(),
789        VmValue::Nil => Vec::new(),
790        // For dicts / lists / structs, fall through to the stdlib JSON
791        // encoder so the ETag derives from a stable canonical form
792        // (dict keys sorted, bytes base64-tagged) rather than the
793        // less-stable `display()` representation. We reuse
794        // `stdlib::json` directly instead of reaching for the
795        // llm-helpers encoder so the abstraction boundary stays
796        // sibling-module, not cross-subsystem.
797        other => crate::stdlib::json::vm_value_to_json(other).into_bytes(),
798    }
799}
800
801/// Parse an HTTP `Accept` header and return the best matching offer.
802///
803/// Standard Q-value scoring per RFC 9110 §12.5.1: each media-range
804/// gets a `q` (1.0 by default); each offer is scored by its
805/// best-matching range, with ties broken by offer order. Wildcard
806/// matches (`type/*`, `*/*`) score below exact-type matches.
807fn negotiate_accept(header: &str, offers: &[String]) -> Option<String> {
808    let ranges: Vec<MediaRange> = header
809        .split(',')
810        .filter_map(MediaRange::parse)
811        .filter(|range| range.q > 0.0)
812        .collect();
813    if ranges.is_empty() {
814        return None;
815    }
816
817    let mut best: Option<(usize, f32, u8)> = None;
818    for (index, offer) in offers.iter().enumerate() {
819        let (offer_type, offer_subtype) = split_media(offer)?;
820        for range in &ranges {
821            let score = range.match_score(offer_type, offer_subtype);
822            let Some(score) = score else { continue };
823            let q = range.q;
824            let candidate = (index, q, score);
825            best = Some(match best {
826                None => candidate,
827                Some(current) => {
828                    // Prefer higher q first; if equal, higher specificity;
829                    // if equal, earlier offer wins.
830                    if q > current.1
831                        || (q == current.1 && score > current.2)
832                        || (q == current.1 && score == current.2 && index < current.0)
833                    {
834                        candidate
835                    } else {
836                        current
837                    }
838                }
839            });
840        }
841    }
842    best.map(|(index, _, _)| offers[index].clone())
843}
844
845struct MediaRange<'a> {
846    type_: &'a str,
847    subtype: &'a str,
848    q: f32,
849}
850
851impl<'a> MediaRange<'a> {
852    fn parse(raw: &'a str) -> Option<Self> {
853        let trimmed = raw.trim();
854        let mut parts = trimmed.split(';');
855        let media = parts.next()?.trim();
856        let (type_, subtype) = split_media(media)?;
857        let mut q = 1.0;
858        for param in parts {
859            let param = param.trim();
860            if let Some(value) = param
861                .strip_prefix("q=")
862                .or_else(|| param.strip_prefix("Q="))
863            {
864                if let Ok(parsed) = value.trim().parse::<f32>() {
865                    if (0.0..=1.0).contains(&parsed) {
866                        q = parsed;
867                    }
868                }
869            }
870        }
871        Some(Self { type_, subtype, q })
872    }
873
874    fn match_score(&self, offer_type: &str, offer_subtype: &str) -> Option<u8> {
875        let type_match = self.type_ == "*" || self.type_.eq_ignore_ascii_case(offer_type);
876        let subtype_match = self.subtype == "*" || self.subtype.eq_ignore_ascii_case(offer_subtype);
877        if !type_match || !subtype_match {
878            return None;
879        }
880        Some(match (self.type_, self.subtype) {
881            ("*", _) => 1,
882            (_, "*") => 2,
883            _ => 3,
884        })
885    }
886}
887
888fn split_media(value: &str) -> Option<(&str, &str)> {
889    let mut iter = value.splitn(2, '/');
890    let type_ = iter.next()?.trim();
891    let subtype = iter.next()?.trim();
892    if type_.is_empty() || subtype.is_empty() {
893        return None;
894    }
895    Some((type_, subtype))
896}
897
898pub(crate) const MODULE_BUILTINS: &[&VmBuiltinDef] = &[
899    &HTTP_OK_IMPL_DEF,
900    &HTTP_CREATED_IMPL_DEF,
901    &HTTP_NO_CONTENT_IMPL_DEF,
902    &HTTP_ERROR_IMPL_DEF,
903    &HTTP_REPLY_IMPL_DEF,
904    &HTTP_STREAM_IMPL_DEF,
905    &HTTP_SSE_IMPL_DEF,
906    &HTTP_ETAG_IMPL_DEF,
907    &HTTP_CHOOSE_IMPL_DEF,
908    &HTTP_NOT_MODIFIED_IMPL_DEF,
909    &HTTP_PUSH_HINTS_IMPL_DEF,
910    &HTTP_UPGRADE_WS_IMPL_DEF,
911];
912
913#[cfg(test)]
914mod tests {
915    use super::*;
916    use crate::llm::helpers::vm_value_to_json;
917
918    fn dict(value: &VmValue) -> &BTreeMap<String, VmValue> {
919        value.as_dict().expect("envelope is a dict")
920    }
921
922    fn run_sync<F, Fut>(future: F) -> Fut::Output
923    where
924        F: FnOnce() -> Fut,
925        Fut: std::future::Future,
926    {
927        tokio::runtime::Builder::new_current_thread()
928            .enable_all()
929            .build()
930            .expect("rt")
931            .block_on(future())
932    }
933
934    #[test]
935    fn http_ok_produces_tagged_envelope() {
936        let body = VmValue::String(Rc::from("hello"));
937        let response = http_ok_impl(&[body], &mut String::new()).expect("ok");
938        let map = dict(&response);
939        assert_eq!(
940            map.get(HTTP_RESPONSE_TAG_KEY).and_then(|v| match v {
941                VmValue::String(s) => Some(s.as_ref()),
942                _ => None,
943            }),
944            Some(HTTP_RESPONSE_TAG_VERSION)
945        );
946        assert!(matches!(map.get("status"), Some(VmValue::Int(200))));
947        assert_eq!(
948            map.get("body").map(|v| v.display()).as_deref(),
949            Some("hello")
950        );
951    }
952
953    #[test]
954    fn http_created_sets_location_header() {
955        let body = VmValue::Dict(Rc::new(BTreeMap::from([(
956            "id".to_string(),
957            VmValue::String(Rc::from("sess_1")),
958        )])));
959        let location = VmValue::String(Rc::from("/v1/sessions/sess_1"));
960        let response = http_created_impl(&[body, location], &mut String::new()).expect("created");
961        let map = dict(&response);
962        assert!(matches!(map.get("status"), Some(VmValue::Int(201))));
963        let headers = map
964            .get("headers")
965            .and_then(VmValue::as_dict)
966            .expect("headers");
967        assert_eq!(
968            headers.get("Location").map(|v| v.display()).as_deref(),
969            Some("/v1/sessions/sess_1")
970        );
971    }
972
973    #[test]
974    fn http_no_content_omits_body_marker() {
975        let response = http_no_content_impl(&[], &mut String::new()).expect("no_content");
976        let map = dict(&response);
977        assert!(matches!(map.get("status"), Some(VmValue::Int(204))));
978        assert!(map.get("body").is_none());
979        assert_eq!(
980            map.get("body_kind").and_then(|v| match v {
981                VmValue::String(s) => Some(s.as_ref()),
982                _ => None,
983            }),
984            Some(BODY_KIND_NONE)
985        );
986    }
987
988    #[test]
989    fn http_error_carries_code_message_and_marker() {
990        let response = http_error_impl(
991            &[
992                VmValue::Int(422),
993                VmValue::String(Rc::from("invalid_input")),
994                VmValue::String(Rc::from("bad payload")),
995                VmValue::Nil,
996            ],
997            &mut String::new(),
998        )
999        .expect("error");
1000        let map = dict(&response);
1001        assert!(matches!(map.get("status"), Some(VmValue::Int(422))));
1002        assert!(matches!(map.get("is_error"), Some(VmValue::Bool(true))));
1003        let body = map
1004            .get("body")
1005            .and_then(VmValue::as_dict)
1006            .expect("body dict");
1007        assert_eq!(
1008            body.get("code").map(|v| v.display()).as_deref(),
1009            Some("invalid_input")
1010        );
1011        assert_eq!(
1012            body.get("message").map(|v| v.display()).as_deref(),
1013            Some("bad payload")
1014        );
1015    }
1016
1017    #[test]
1018    fn http_error_rejects_2xx_status() {
1019        let err = http_error_impl(
1020            &[
1021                VmValue::Int(200),
1022                VmValue::String(Rc::from("x")),
1023                VmValue::String(Rc::from("y")),
1024            ],
1025            &mut String::new(),
1026        )
1027        .expect_err("expected reject");
1028        match err {
1029            VmError::Thrown(VmValue::String(text)) => {
1030                assert!(text.contains("4xx or 5xx"), "got: {text}");
1031            }
1032            other => panic!("unexpected error: {other:?}"),
1033        }
1034    }
1035
1036    #[test]
1037    fn http_reply_rejects_out_of_range_status() {
1038        let err =
1039            http_reply_impl(&[VmValue::Int(999)], &mut String::new()).expect_err("out of range");
1040        match err {
1041            VmError::Thrown(VmValue::String(text)) => {
1042                assert!(text.contains("100-599"), "got: {text}");
1043            }
1044            other => panic!("unexpected error: {other:?}"),
1045        }
1046    }
1047
1048    #[test]
1049    fn http_stream_buffers_list_source() {
1050        let items = vec![
1051            VmValue::String(Rc::from("a")),
1052            VmValue::String(Rc::from("b")),
1053        ];
1054        let response = run_sync(|| {
1055            http_stream_impl(vec![
1056                VmValue::List(Rc::new(items.clone())),
1057                VmValue::String(Rc::from("text/plain")),
1058            ])
1059        })
1060        .expect("stream");
1061        let map = dict(&response);
1062        assert_eq!(
1063            map.get("body_kind").and_then(|v| match v {
1064                VmValue::String(s) => Some(s.as_ref()),
1065                _ => None,
1066            }),
1067            Some(BODY_KIND_STREAM)
1068        );
1069        let body = map.get("body").expect("body");
1070        match body {
1071            VmValue::List(values) => {
1072                assert_eq!(values.len(), 2);
1073            }
1074            other => panic!("expected list body, got {other:?}"),
1075        }
1076        let headers = map
1077            .get("headers")
1078            .and_then(VmValue::as_dict)
1079            .expect("headers");
1080        assert_eq!(
1081            headers.get("Content-Type").map(|v| v.display()).as_deref(),
1082            Some("text/plain")
1083        );
1084    }
1085
1086    #[test]
1087    fn http_sse_sets_event_stream_headers_and_optional_retry() {
1088        let events = vec![VmValue::Dict(Rc::new(BTreeMap::from([(
1089            "data".to_string(),
1090            VmValue::String(Rc::from("ping")),
1091        )])))];
1092        let response = run_sync(|| {
1093            http_sse_impl(vec![
1094                VmValue::List(Rc::new(events.clone())),
1095                VmValue::Int(2500),
1096            ])
1097        })
1098        .expect("sse");
1099        let map = dict(&response);
1100        let headers = map
1101            .get("headers")
1102            .and_then(VmValue::as_dict)
1103            .expect("headers");
1104        assert_eq!(
1105            headers.get("Content-Type").map(|v| v.display()).as_deref(),
1106            Some("text/event-stream")
1107        );
1108        assert_eq!(
1109            headers.get("Cache-Control").map(|v| v.display()).as_deref(),
1110            Some("no-cache")
1111        );
1112        assert!(matches!(map.get("retry_ms"), Some(VmValue::Int(2500))));
1113    }
1114
1115    #[test]
1116    fn parse_envelope_round_trip_through_json() {
1117        let response = http_error_impl(
1118            &[
1119                VmValue::Int(404),
1120                VmValue::String(Rc::from("not_found")),
1121                VmValue::String(Rc::from("missing")),
1122                VmValue::Dict(Rc::new(BTreeMap::from([(
1123                    "id".to_string(),
1124                    VmValue::String(Rc::from("sess_404")),
1125                )]))),
1126            ],
1127            &mut String::new(),
1128        )
1129        .expect("error");
1130        let json = vm_value_to_json(&response);
1131        let envelope = parse_envelope(&json).expect("envelope parses");
1132        assert_eq!(envelope.status, 404);
1133        assert!(envelope.is_error);
1134        let body = envelope.body.expect("body");
1135        assert_eq!(body["code"], "not_found");
1136        assert_eq!(body["details"]["id"], "sess_404");
1137    }
1138
1139    #[test]
1140    fn parse_envelope_ignores_untagged_dicts() {
1141        let plain = serde_json::json!({"status": 200, "body": {}});
1142        assert!(parse_envelope(&plain).is_none());
1143    }
1144
1145    #[test]
1146    fn http_etag_is_quoted_hex_sha256_of_payload() {
1147        let value = VmValue::String(Rc::from("hello"));
1148        let etag = http_etag_impl(&[value], &mut String::new()).expect("etag");
1149        match etag {
1150            VmValue::String(text) => {
1151                assert_eq!(
1152                    text.as_ref(),
1153                    "\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\""
1154                );
1155            }
1156            other => panic!("expected string, got {other:?}"),
1157        }
1158    }
1159
1160    #[test]
1161    fn http_etag_stable_across_string_and_bytes_for_same_payload() {
1162        let from_string =
1163            http_etag_impl(&[VmValue::String(Rc::from("hello"))], &mut String::new()).unwrap();
1164        let from_bytes = http_etag_impl(
1165            &[VmValue::Bytes(Rc::new(b"hello".to_vec()))],
1166            &mut String::new(),
1167        )
1168        .unwrap();
1169        assert_eq!(from_string.display(), from_bytes.display());
1170    }
1171
1172    #[test]
1173    fn http_choose_returns_best_q_match() {
1174        let accept = VmValue::String(Rc::from("application/xml;q=0.5, application/json;q=0.9"));
1175        let offers = VmValue::List(Rc::new(vec![
1176            VmValue::String(Rc::from("application/xml")),
1177            VmValue::String(Rc::from("application/json")),
1178        ]));
1179        let chosen = http_choose_impl(&[accept, offers], &mut String::new()).unwrap();
1180        assert_eq!(chosen.display(), "application/json");
1181    }
1182
1183    #[test]
1184    fn http_choose_prefers_specific_over_wildcard() {
1185        let accept = VmValue::String(Rc::from("text/*;q=0.5, application/json"));
1186        let offers = VmValue::List(Rc::new(vec![
1187            VmValue::String(Rc::from("text/plain")),
1188            VmValue::String(Rc::from("application/json")),
1189        ]));
1190        let chosen = http_choose_impl(&[accept, offers], &mut String::new()).unwrap();
1191        assert_eq!(chosen.display(), "application/json");
1192    }
1193
1194    #[test]
1195    fn http_choose_returns_default_for_no_accept() {
1196        let offers = VmValue::List(Rc::new(vec![
1197            VmValue::String(Rc::from("text/plain")),
1198            VmValue::String(Rc::from("application/json")),
1199        ]));
1200        let chosen = http_choose_impl(&[VmValue::Nil, offers], &mut String::new()).unwrap();
1201        assert_eq!(chosen.display(), "text/plain");
1202    }
1203
1204    #[test]
1205    fn http_choose_overrides_default_with_explicit() {
1206        let offers = VmValue::List(Rc::new(vec![
1207            VmValue::String(Rc::from("text/plain")),
1208            VmValue::String(Rc::from("application/json")),
1209        ]));
1210        let chosen = http_choose_impl(
1211            &[
1212                VmValue::Nil,
1213                offers,
1214                VmValue::String(Rc::from("application/json")),
1215            ],
1216            &mut String::new(),
1217        )
1218        .unwrap();
1219        assert_eq!(chosen.display(), "application/json");
1220    }
1221
1222    #[test]
1223    fn http_choose_wildcard_accept_yields_default() {
1224        let offers = VmValue::List(Rc::new(vec![VmValue::String(Rc::from("application/json"))]));
1225        let chosen = http_choose_impl(
1226            &[VmValue::String(Rc::from("*/*")), offers],
1227            &mut String::new(),
1228        )
1229        .unwrap();
1230        assert_eq!(chosen.display(), "application/json");
1231    }
1232
1233    #[test]
1234    fn http_not_modified_envelope_carries_etag() {
1235        let etag = VmValue::String(Rc::from("\"abc\""));
1236        let response = http_not_modified_impl(&[etag, VmValue::Nil], &mut String::new()).unwrap();
1237        let map = dict(&response);
1238        assert!(matches!(map.get("status"), Some(VmValue::Int(304))));
1239        let headers = map
1240            .get("headers")
1241            .and_then(VmValue::as_dict)
1242            .expect("headers");
1243        assert_eq!(
1244            headers.get("ETag").map(|v| v.display()).as_deref(),
1245            Some("\"abc\"")
1246        );
1247    }
1248
1249    #[test]
1250    fn http_push_hints_appends_link_headers_with_inferred_as() {
1251        let envelope = http_ok_impl(
1252            &[VmValue::Dict(Rc::new(BTreeMap::new()))],
1253            &mut String::new(),
1254        )
1255        .unwrap();
1256        let paths = VmValue::List(Rc::new(vec![
1257            VmValue::String(Rc::from("/main.css")),
1258            VmValue::String(Rc::from("/app.js")),
1259            VmValue::String(Rc::from("/hero.webp")),
1260            VmValue::String(Rc::from("/inter.woff2")),
1261            VmValue::String(Rc::from("/manifest.json")),
1262            VmValue::String(Rc::from("/unknown.xyz")),
1263        ]));
1264        let response =
1265            http_push_hints_impl(&[envelope, paths], &mut String::new()).expect("push_hints");
1266        let map = dict(&response);
1267        let headers = map
1268            .get("headers")
1269            .and_then(VmValue::as_dict)
1270            .expect("headers");
1271        let links = match headers.get("Link") {
1272            Some(VmValue::List(items)) => items.clone(),
1273            other => panic!("Link should be a list, got {other:?}"),
1274        };
1275        let rendered: Vec<String> = links
1276            .iter()
1277            .map(|v| match v {
1278                VmValue::String(s) => s.to_string(),
1279                other => panic!("Link entry is not a string: {other:?}"),
1280            })
1281            .collect();
1282        assert_eq!(
1283            rendered,
1284            vec![
1285                "</main.css>; rel=preload; as=style",
1286                "</app.js>; rel=preload; as=script",
1287                "</hero.webp>; rel=preload; as=image",
1288                "</inter.woff2>; rel=preload; as=font",
1289                "</manifest.json>; rel=preload; as=fetch",
1290                "</unknown.xyz>; rel=preload",
1291            ]
1292        );
1293    }
1294
1295    #[test]
1296    fn http_push_hints_handles_querystring_in_path() {
1297        let envelope = http_ok_impl(&[VmValue::Nil], &mut String::new()).unwrap();
1298        let paths = VmValue::List(Rc::new(vec![VmValue::String(Rc::from(
1299            "/static/app.js?v=42",
1300        ))]));
1301        let response =
1302            http_push_hints_impl(&[envelope, paths], &mut String::new()).expect("push_hints");
1303        let map = dict(&response);
1304        let headers = map
1305            .get("headers")
1306            .and_then(VmValue::as_dict)
1307            .expect("headers");
1308        let links = match headers.get("Link") {
1309            Some(VmValue::List(items)) => items.clone(),
1310            other => panic!("Link should be a list, got {other:?}"),
1311        };
1312        assert_eq!(
1313            links[0].display(),
1314            "</static/app.js?v=42>; rel=preload; as=script"
1315        );
1316    }
1317
1318    #[test]
1319    fn http_push_hints_rejects_untagged_envelope() {
1320        let plain = VmValue::Dict(Rc::new(BTreeMap::from([(
1321            "status".to_string(),
1322            VmValue::Int(200),
1323        )])));
1324        let paths = VmValue::List(Rc::new(vec![VmValue::String(Rc::from("/main.css"))]));
1325        let result = http_push_hints_impl(&[plain, paths], &mut String::new());
1326        assert!(
1327            matches!(result, Err(VmError::Thrown(_))),
1328            "untagged dict should be rejected, got {result:?}"
1329        );
1330    }
1331
1332    #[test]
1333    fn http_push_hints_preserves_existing_link_header() {
1334        let envelope = http_reply_impl(
1335            &[
1336                VmValue::Int(200),
1337                VmValue::Dict(Rc::new(BTreeMap::new())),
1338                VmValue::Dict(Rc::new(BTreeMap::from([(
1339                    "Link".to_string(),
1340                    VmValue::String(Rc::from("</legacy.css>; rel=preload; as=style")),
1341                )]))),
1342            ],
1343            &mut String::new(),
1344        )
1345        .unwrap();
1346        let paths = VmValue::List(Rc::new(vec![VmValue::String(Rc::from("/app.js"))]));
1347        let response = http_push_hints_impl(&[envelope, paths], &mut String::new()).unwrap();
1348        let map = dict(&response);
1349        let headers = map
1350            .get("headers")
1351            .and_then(VmValue::as_dict)
1352            .expect("headers");
1353        let links = match headers.get("Link") {
1354            Some(VmValue::List(items)) => items.clone(),
1355            other => panic!("Link should be a list once preloads are added, got {other:?}"),
1356        };
1357        assert_eq!(links.len(), 2);
1358        assert_eq!(links[0].display(), "</legacy.css>; rel=preload; as=style");
1359        assert_eq!(links[1].display(), "</app.js>; rel=preload; as=script");
1360    }
1361
1362    #[test]
1363    fn http_upgrade_ws_envelope_negotiates_subprotocol() {
1364        let req = VmValue::Dict(Rc::new(BTreeMap::from([(
1365            "headers".to_string(),
1366            VmValue::Dict(Rc::new(BTreeMap::from([(
1367                "Sec-WebSocket-Protocol".to_string(),
1368                VmValue::String(Rc::from("v0.harn, v1.harn")),
1369            )]))),
1370        )])));
1371        let options = VmValue::Dict(Rc::new(BTreeMap::from([(
1372            "subprotocols".to_string(),
1373            VmValue::List(Rc::new(vec![
1374                VmValue::String(Rc::from("v1.harn")),
1375                VmValue::String(Rc::from("v2.harn")),
1376            ])),
1377        )])));
1378        let response = http_upgrade_ws_impl(&[req, options], &mut String::new()).unwrap();
1379        let map = dict(&response);
1380        assert!(matches!(map.get("status"), Some(VmValue::Int(101))));
1381        let upgrade = map
1382            .get("ws_upgrade")
1383            .and_then(VmValue::as_dict)
1384            .expect("ws_upgrade");
1385        assert_eq!(
1386            upgrade.get("subprotocol").map(|v| v.display()).as_deref(),
1387            Some("v1.harn")
1388        );
1389        let headers = map
1390            .get("headers")
1391            .and_then(VmValue::as_dict)
1392            .expect("headers");
1393        assert_eq!(
1394            headers.get("Upgrade").map(|v| v.display()).as_deref(),
1395            Some("websocket")
1396        );
1397        assert_eq!(
1398            headers
1399                .get("Sec-WebSocket-Protocol")
1400                .map(|v| v.display())
1401                .as_deref(),
1402            Some("v1.harn")
1403        );
1404    }
1405
1406    #[test]
1407    fn http_upgrade_ws_picks_client_preferred_when_both_overlap() {
1408        // Regression for the divergence between
1409        // `http_upgrade_ws_impl`'s envelope-side negotiation and
1410        // `harn_serve::ws::negotiate_subprotocol`'s wire-side
1411        // negotiation. With client "v2.harn, v1.harn" and server
1412        // ["v1.harn", "v2.harn"] the two implementations used to
1413        // disagree (server-order picked v1; client-order picks v2).
1414        // The envelope MUST match what the upgrade handshake echoes
1415        // back, so we honour client preference everywhere.
1416        let req = VmValue::Dict(Rc::new(BTreeMap::from([(
1417            "headers".to_string(),
1418            VmValue::Dict(Rc::new(BTreeMap::from([(
1419                "Sec-WebSocket-Protocol".to_string(),
1420                VmValue::String(Rc::from("v2.harn, v1.harn")),
1421            )]))),
1422        )])));
1423        let options = VmValue::Dict(Rc::new(BTreeMap::from([(
1424            "subprotocols".to_string(),
1425            VmValue::List(Rc::new(vec![
1426                VmValue::String(Rc::from("v1.harn")),
1427                VmValue::String(Rc::from("v2.harn")),
1428            ])),
1429        )])));
1430        let response = http_upgrade_ws_impl(&[req, options], &mut String::new()).unwrap();
1431        let upgrade = dict(&response)
1432            .get("ws_upgrade")
1433            .and_then(VmValue::as_dict)
1434            .expect("ws_upgrade");
1435        assert_eq!(
1436            upgrade.get("subprotocol").map(|v| v.display()).as_deref(),
1437            Some("v2.harn")
1438        );
1439    }
1440
1441    #[test]
1442    fn parse_envelope_round_trips_ws_upgrade_marker() {
1443        let req = VmValue::Dict(Rc::new(BTreeMap::from([(
1444            "headers".to_string(),
1445            VmValue::Dict(Rc::new(BTreeMap::from([(
1446                "Sec-WebSocket-Protocol".to_string(),
1447                VmValue::String(Rc::from("v1.harn")),
1448            )]))),
1449        )])));
1450        let options = VmValue::Dict(Rc::new(BTreeMap::from([
1451            (
1452                "subprotocols".to_string(),
1453                VmValue::List(Rc::new(vec![VmValue::String(Rc::from("v1.harn"))])),
1454            ),
1455            ("idle_ping_ms".to_string(), VmValue::Int(15_000)),
1456        ])));
1457        let response = http_upgrade_ws_impl(&[req, options], &mut String::new()).unwrap();
1458        let json = vm_value_to_json(&response);
1459        let envelope = parse_envelope(&json).expect("envelope parses");
1460        let ws = envelope.ws_upgrade.expect("ws_upgrade present");
1461        assert_eq!(ws.subprotocol.as_deref(), Some("v1.harn"));
1462        assert_eq!(ws.offered, vec!["v1.harn"]);
1463        assert_eq!(ws.idle_ping_ms, Some(15_000));
1464        assert_eq!(envelope.status, 101);
1465    }
1466
1467    #[test]
1468    fn http_upgrade_ws_falls_through_when_no_subprotocols_offered() {
1469        let req = VmValue::Dict(Rc::new(BTreeMap::new()));
1470        let response = http_upgrade_ws_impl(&[req], &mut String::new()).unwrap();
1471        let map = dict(&response);
1472        let upgrade = map
1473            .get("ws_upgrade")
1474            .and_then(VmValue::as_dict)
1475            .expect("ws_upgrade");
1476        assert!(matches!(upgrade.get("subprotocol"), Some(VmValue::Nil)));
1477    }
1478}