|
| 1 | +//! Native HTTP builtins: `http_get`, `http_post`, `http_post_json`, `http_put`, `http_delete`. |
| 2 | +//! |
| 3 | +//! These builtins give OMC programs direct access to HTTP without needing LLM |
| 4 | +//! credentials. They are built on the same `ureq` crate already used by |
| 5 | +//! `llm_builtins` and are gated behind the same `native-llm` Cargo feature |
| 6 | +//! (which controls `dep:ureq`). |
| 7 | +//! |
| 8 | +//! ## Return value |
| 9 | +//! |
| 10 | +//! Every function returns a dict with at least: |
| 11 | +//! - `status` — HTTP status code as int |
| 12 | +//! - `body` — response body as string |
| 13 | +//! - `ok` — bool, true when 200 <= status < 300 |
| 14 | +//! |
| 15 | +//! `http_post_json` additionally includes: |
| 16 | +//! - `json` — parsed JSON body as OMC value, or null on parse failure |
| 17 | +
|
| 18 | +use crate::value::Value; |
| 19 | +use std::collections::BTreeMap; |
| 20 | + |
| 21 | +// --------------------------------------------------------------------------- |
| 22 | +// Public entry points (called from interpreter.rs dispatch) |
| 23 | +// --------------------------------------------------------------------------- |
| 24 | + |
| 25 | +/// `http_get(url: string, headers?: dict) -> dict` |
| 26 | +#[cfg(feature = "native-llm")] |
| 27 | +pub fn http_get(args: &[Value]) -> Result<Value, String> { |
| 28 | + if args.is_empty() { |
| 29 | + return Err("http_get requires (url: string, headers?: dict)".to_string()); |
| 30 | + } |
| 31 | + let url = args[0].to_display_string(); |
| 32 | + let headers = extract_headers(args.get(1))?; |
| 33 | + |
| 34 | + let mut req = ureq::get(&url); |
| 35 | + for (k, v) in &headers { |
| 36 | + req = req.set(k, v); |
| 37 | + } |
| 38 | + |
| 39 | + let (status, body) = send_request(req)?; |
| 40 | + Ok(make_response_dict(status, body)) |
| 41 | +} |
| 42 | + |
| 43 | +/// `http_post(url: string, body: string, headers?: dict) -> dict` |
| 44 | +#[cfg(feature = "native-llm")] |
| 45 | +pub fn http_post(args: &[Value]) -> Result<Value, String> { |
| 46 | + if args.len() < 2 { |
| 47 | + return Err("http_post requires (url: string, body: string, headers?: dict)".to_string()); |
| 48 | + } |
| 49 | + let url = args[0].to_display_string(); |
| 50 | + let body_str = args[1].to_display_string(); |
| 51 | + let headers = extract_headers(args.get(2))?; |
| 52 | + |
| 53 | + let mut req = ureq::post(&url); |
| 54 | + for (k, v) in &headers { |
| 55 | + req = req.set(k, v); |
| 56 | + } |
| 57 | + |
| 58 | + let resp = req |
| 59 | + .send_string(&body_str) |
| 60 | + .map_err(|e| format!("http_post failed: {e}"))?; |
| 61 | + let status = resp.status(); |
| 62 | + let body = resp |
| 63 | + .into_string() |
| 64 | + .map_err(|e| format!("http_post: read body failed: {e}"))?; |
| 65 | + Ok(make_response_dict(status, body)) |
| 66 | +} |
| 67 | + |
| 68 | +/// `http_post_json(url: string, data: dict|array, headers?: dict) -> dict` |
| 69 | +/// |
| 70 | +/// Serialises `data` to JSON, sends with `Content-Type: application/json`, |
| 71 | +/// and additionally attempts to parse the response body as JSON, returning it |
| 72 | +/// under the `json` key (null on parse failure). |
| 73 | +#[cfg(feature = "native-llm")] |
| 74 | +pub fn http_post_json(args: &[Value]) -> Result<Value, String> { |
| 75 | + if args.len() < 2 { |
| 76 | + return Err( |
| 77 | + "http_post_json requires (url: string, data: dict|array, headers?: dict)".to_string(), |
| 78 | + ); |
| 79 | + } |
| 80 | + let url = args[0].to_display_string(); |
| 81 | + let json_body = crate::interpreter::value_to_json(&args[1]); |
| 82 | + let json_str = serde_json::to_string(&json_body) |
| 83 | + .map_err(|e| format!("http_post_json: JSON serialisation failed: {e}"))?; |
| 84 | + let headers = extract_headers(args.get(2))?; |
| 85 | + |
| 86 | + let mut req = ureq::post(&url).set("Content-Type", "application/json"); |
| 87 | + for (k, v) in &headers { |
| 88 | + req = req.set(k, v); |
| 89 | + } |
| 90 | + |
| 91 | + let resp = req |
| 92 | + .send_string(&json_str) |
| 93 | + .map_err(|e| format!("http_post_json failed: {e}"))?; |
| 94 | + let status = resp.status(); |
| 95 | + let body = resp |
| 96 | + .into_string() |
| 97 | + .map_err(|e| format!("http_post_json: read body failed: {e}"))?; |
| 98 | + |
| 99 | + Ok(make_json_response_dict(status, body)) |
| 100 | +} |
| 101 | + |
| 102 | +/// `http_put(url: string, body: string, headers?: dict) -> dict` |
| 103 | +#[cfg(feature = "native-llm")] |
| 104 | +pub fn http_put(args: &[Value]) -> Result<Value, String> { |
| 105 | + if args.len() < 2 { |
| 106 | + return Err("http_put requires (url: string, body: string, headers?: dict)".to_string()); |
| 107 | + } |
| 108 | + let url = args[0].to_display_string(); |
| 109 | + let body_str = args[1].to_display_string(); |
| 110 | + let headers = extract_headers(args.get(2))?; |
| 111 | + |
| 112 | + let mut req = ureq::put(&url); |
| 113 | + for (k, v) in &headers { |
| 114 | + req = req.set(k, v); |
| 115 | + } |
| 116 | + |
| 117 | + let resp = req |
| 118 | + .send_string(&body_str) |
| 119 | + .map_err(|e| format!("http_put failed: {e}"))?; |
| 120 | + let status = resp.status(); |
| 121 | + let body = resp |
| 122 | + .into_string() |
| 123 | + .map_err(|e| format!("http_put: read body failed: {e}"))?; |
| 124 | + Ok(make_response_dict(status, body)) |
| 125 | +} |
| 126 | + |
| 127 | +/// `http_delete(url: string, headers?: dict) -> dict` |
| 128 | +#[cfg(feature = "native-llm")] |
| 129 | +pub fn http_delete(args: &[Value]) -> Result<Value, String> { |
| 130 | + if args.is_empty() { |
| 131 | + return Err("http_delete requires (url: string, headers?: dict)".to_string()); |
| 132 | + } |
| 133 | + let url = args[0].to_display_string(); |
| 134 | + let headers = extract_headers(args.get(1))?; |
| 135 | + |
| 136 | + let mut req = ureq::delete(&url); |
| 137 | + for (k, v) in &headers { |
| 138 | + req = req.set(k, v); |
| 139 | + } |
| 140 | + |
| 141 | + let (status, body) = send_request(req)?; |
| 142 | + Ok(make_response_dict(status, body)) |
| 143 | +} |
| 144 | + |
| 145 | +// --------------------------------------------------------------------------- |
| 146 | +// Stubs for non-native builds |
| 147 | +// --------------------------------------------------------------------------- |
| 148 | + |
| 149 | +#[cfg(not(feature = "native-llm"))] |
| 150 | +pub fn http_get(_args: &[Value]) -> Result<Value, String> { |
| 151 | + Err("http_get: recompile with --features native-llm".to_string()) |
| 152 | +} |
| 153 | + |
| 154 | +#[cfg(not(feature = "native-llm"))] |
| 155 | +pub fn http_post(_args: &[Value]) -> Result<Value, String> { |
| 156 | + Err("http_post: recompile with --features native-llm".to_string()) |
| 157 | +} |
| 158 | + |
| 159 | +#[cfg(not(feature = "native-llm"))] |
| 160 | +pub fn http_post_json(_args: &[Value]) -> Result<Value, String> { |
| 161 | + Err("http_post_json: recompile with --features native-llm".to_string()) |
| 162 | +} |
| 163 | + |
| 164 | +#[cfg(not(feature = "native-llm"))] |
| 165 | +pub fn http_put(_args: &[Value]) -> Result<Value, String> { |
| 166 | + Err("http_put: recompile with --features native-llm".to_string()) |
| 167 | +} |
| 168 | + |
| 169 | +#[cfg(not(feature = "native-llm"))] |
| 170 | +pub fn http_delete(_args: &[Value]) -> Result<Value, String> { |
| 171 | + Err("http_delete: recompile with --features native-llm".to_string()) |
| 172 | +} |
| 173 | + |
| 174 | +// --------------------------------------------------------------------------- |
| 175 | +// Helpers |
| 176 | +// --------------------------------------------------------------------------- |
| 177 | + |
| 178 | +/// Extract optional header dict (Value::Dict) into a Vec<(String, String)>. |
| 179 | +/// Accepts null / missing arg gracefully. |
| 180 | +fn extract_headers(v: Option<&Value>) -> Result<Vec<(String, String)>, String> { |
| 181 | + match v { |
| 182 | + None | Some(Value::Null) => Ok(vec![]), |
| 183 | + Some(Value::Dict(d)) => { |
| 184 | + let map = d.borrow(); |
| 185 | + let mut out = Vec::with_capacity(map.len()); |
| 186 | + for (k, val) in map.iter() { |
| 187 | + out.push((k.clone(), val.to_display_string())); |
| 188 | + } |
| 189 | + Ok(out) |
| 190 | + } |
| 191 | + Some(other) => Err(format!( |
| 192 | + "http headers must be a dict or null, got {}", |
| 193 | + other.to_display_string() |
| 194 | + )), |
| 195 | + } |
| 196 | +} |
| 197 | + |
| 198 | +/// Fire a GET/DELETE-style request and return (status, body). |
| 199 | +#[cfg(feature = "native-llm")] |
| 200 | +fn send_request(req: ureq::Request) -> Result<(u16, String), String> { |
| 201 | + let resp = req.call().map_err(|e| format!("HTTP request failed: {e}"))?; |
| 202 | + let status = resp.status(); |
| 203 | + let body = resp |
| 204 | + .into_string() |
| 205 | + .map_err(|e| format!("read body failed: {e}"))?; |
| 206 | + Ok((status, body)) |
| 207 | +} |
| 208 | + |
| 209 | +/// Build the standard {status, body, ok} response dict. |
| 210 | +fn make_response_dict(status: u16, body: String) -> Value { |
| 211 | + let mut map = BTreeMap::new(); |
| 212 | + map.insert("status".to_string(), Value::HInt(crate::value::HInt::new(status as i64))); |
| 213 | + map.insert("body".to_string(), Value::String(body)); |
| 214 | + map.insert("ok".to_string(), Value::Bool(status >= 200 && status < 300)); |
| 215 | + Value::dict_from(map) |
| 216 | +} |
| 217 | + |
| 218 | +/// Build the {status, body, ok, json} response dict used by http_post_json. |
| 219 | +fn make_json_response_dict(status: u16, body: String) -> Value { |
| 220 | + let parsed_json = serde_json::from_str::<serde_json::Value>(&body) |
| 221 | + .ok() |
| 222 | + .map(crate::interpreter::json_to_value) |
| 223 | + .unwrap_or(Value::Null); |
| 224 | + |
| 225 | + let mut map = BTreeMap::new(); |
| 226 | + map.insert("status".to_string(), Value::HInt(crate::value::HInt::new(status as i64))); |
| 227 | + map.insert("body".to_string(), Value::String(body)); |
| 228 | + map.insert("ok".to_string(), Value::Bool(status >= 200 && status < 300)); |
| 229 | + map.insert("json".to_string(), parsed_json); |
| 230 | + Value::dict_from(map) |
| 231 | +} |
0 commit comments