Add object primitives, official ext/llm, and HTTPS/dotenv platform.
Introduce # objects with ## methods (handles + ` x.method `), ship OpenAI-compatible ext/llm, and upgrade net/sys for HTTPS headers and dotenv loading. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b974f10c6e
commit
b00b018056
55 files changed
+1741
-291
No files matched your search
+127
-87
@@ -1,7 +1,5 @@
|
||||
//! Minimal HTTP host primitives (HTTP cleartext in v1; HTTPS deferred).
|
||||
//! HTTP host primitives (HTTP and HTTPS via ureq).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::host::HostContext;
|
||||
@@ -14,104 +12,96 @@ fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
|
||||
}
|
||||
}
|
||||
|
||||
struct UrlParts {
|
||||
host: String,
|
||||
port: u16,
|
||||
path: String,
|
||||
}
|
||||
|
||||
fn parse_http_url(url: &str) -> Result<UrlParts, String> {
|
||||
let rest = url
|
||||
.strip_prefix("http://")
|
||||
.ok_or_else(|| {
|
||||
if url.starts_with("https://") {
|
||||
"https is not supported yet (use http:// or wait for TLS)".to_string()
|
||||
} else {
|
||||
"url must start with http://".into()
|
||||
}
|
||||
})?;
|
||||
let (hostport, path) = match rest.split_once('/') {
|
||||
Some((h, p)) => (h, format!("/{p}")),
|
||||
None => (rest, "/".into()),
|
||||
fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>, String> {
|
||||
let Some(h) = headers else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let (host, port) = if let Some((h, p)) = hostport.split_once(':') {
|
||||
let port: u16 = p
|
||||
.parse()
|
||||
.map_err(|_| format!("invalid port in url: {p}"))?;
|
||||
(h.to_string(), port)
|
||||
} else {
|
||||
(hostport.to_string(), 80)
|
||||
};
|
||||
if host.is_empty() {
|
||||
return Err("url missing host".into());
|
||||
match h {
|
||||
Value::None => Ok(Vec::new()),
|
||||
Value::Map(entries) => Ok(entries
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), v.as_display()))
|
||||
.collect()),
|
||||
_ => Err("headers must be a map (e.g. from json parse)".into()),
|
||||
}
|
||||
Ok(UrlParts { host, port, path })
|
||||
}
|
||||
|
||||
fn http_exchange(
|
||||
method: &str,
|
||||
url: &str,
|
||||
body: Option<&str>,
|
||||
content_type: &str,
|
||||
content_type: Option<&str>,
|
||||
extra_headers: &[(String, String)],
|
||||
) -> Result<(u16, String), String> {
|
||||
let parts = parse_http_url(url)?;
|
||||
let addr = format!("{}:{}", parts.host, parts.port);
|
||||
let mut stream = TcpStream::connect(&addr).map_err(|e| format!("http connect {addr}: {e}"))?;
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(10)))
|
||||
.ok();
|
||||
stream
|
||||
.set_write_timeout(Some(Duration::from_secs(10)))
|
||||
.ok();
|
||||
if !(url.starts_with("http://") || url.starts_with("https://")) {
|
||||
return Err("url must start with http:// or https://".into());
|
||||
}
|
||||
let agent = ureq::AgentBuilder::new()
|
||||
.timeout_connect(Duration::from_secs(15))
|
||||
.timeout_read(Duration::from_secs(120))
|
||||
.build();
|
||||
|
||||
let body = body.unwrap_or("");
|
||||
let mut req = format!(
|
||||
"{method} {path} HTTP/1.0\r\nHost: {host}\r\nConnection: close\r\nUser-Agent: marqdo\r\n",
|
||||
path = parts.path,
|
||||
host = parts.host,
|
||||
);
|
||||
if method == "POST" {
|
||||
req.push_str(&format!(
|
||||
"Content-Type: {content_type}\r\nContent-Length: {}\r\n",
|
||||
body.len()
|
||||
));
|
||||
let mut req = match method {
|
||||
"GET" => agent.get(url),
|
||||
"POST" => agent.post(url),
|
||||
"PUT" => agent.put(url),
|
||||
"DELETE" => agent.request("DELETE", url),
|
||||
other => return Err(format!("unsupported http method: {other}")),
|
||||
};
|
||||
req = req.set("User-Agent", "marqdo");
|
||||
if let Some(ct) = content_type {
|
||||
if !ct.is_empty() {
|
||||
req = req.set("Content-Type", ct);
|
||||
}
|
||||
}
|
||||
req.push_str("\r\n");
|
||||
if method == "POST" {
|
||||
req.push_str(body);
|
||||
for (k, v) in extra_headers {
|
||||
req = req.set(k, v);
|
||||
}
|
||||
stream
|
||||
.write_all(req.as_bytes())
|
||||
.map_err(|e| format!("http write: {e}"))?;
|
||||
|
||||
let mut buf = Vec::new();
|
||||
stream
|
||||
.read_to_end(&mut buf)
|
||||
.map_err(|e| format!("http read: {e}"))?;
|
||||
if buf.len() > 2 * 1024 * 1024 {
|
||||
return Err("http response exceeds 2MiB limit".into());
|
||||
let resp = if let Some(b) = body {
|
||||
req.send_string(b)
|
||||
} else {
|
||||
req.call()
|
||||
};
|
||||
|
||||
match resp {
|
||||
Ok(r) => {
|
||||
let status = r.status();
|
||||
let text = r
|
||||
.into_string()
|
||||
.map_err(|e| format!("http read body: {e}"))?;
|
||||
if text.len() > 8 * 1024 * 1024 {
|
||||
return Err("http response exceeds 8MiB limit".into());
|
||||
}
|
||||
Ok((status, text))
|
||||
}
|
||||
Err(ureq::Error::Status(code, r)) => {
|
||||
let text = r.into_string().unwrap_or_default();
|
||||
Ok((code, text))
|
||||
}
|
||||
Err(e) => Err(format!("http {method} {url}: {e}")),
|
||||
}
|
||||
let text = String::from_utf8_lossy(&buf);
|
||||
let (header, body) = text.split_once("\r\n\r\n").unwrap_or((text.as_ref(), ""));
|
||||
let status = header
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|line| line.split_whitespace().nth(1))
|
||||
.and_then(|s| s.parse::<u16>().ok())
|
||||
.unwrap_or(0);
|
||||
Ok((status, body.to_string()))
|
||||
}
|
||||
|
||||
pub fn http_get(ctx: &HostContext, url: &Value) -> Result<Value, String> {
|
||||
fn response_map(status: u16, body: String) -> Value {
|
||||
Value::Map(vec![
|
||||
("status".into(), Value::Int(status as i64)),
|
||||
("body".into(), Value::Text(body)),
|
||||
])
|
||||
}
|
||||
|
||||
pub fn http_get(
|
||||
ctx: &HostContext,
|
||||
url: &Value,
|
||||
headers: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
if !ctx.allow_net() {
|
||||
return Err("http_get denied by host policy".into());
|
||||
}
|
||||
let url = as_text(url, "url")?;
|
||||
let (status, body) = http_exchange("GET", url, None, "")?;
|
||||
Ok(Value::Map(vec![
|
||||
("status".into(), Value::Int(status as i64)),
|
||||
("body".into(), Value::Text(body)),
|
||||
]))
|
||||
let hdrs = headers_from_value(headers)?;
|
||||
let (status, body) = http_exchange("GET", url, None, None, &hdrs)?;
|
||||
Ok(response_map(status, body))
|
||||
}
|
||||
|
||||
pub fn http_post(
|
||||
@@ -119,6 +109,7 @@ pub fn http_post(
|
||||
url: &Value,
|
||||
body: &Value,
|
||||
content_type: Option<&Value>,
|
||||
headers: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
if !ctx.allow_net() {
|
||||
return Err("http_post denied by host policy".into());
|
||||
@@ -127,13 +118,44 @@ pub fn http_post(
|
||||
let body = as_text(body, "body")?;
|
||||
let ct = match content_type {
|
||||
Some(v) => as_text(v, "content_type")?,
|
||||
None => "text/plain; charset=utf-8",
|
||||
None => "application/json; charset=utf-8",
|
||||
};
|
||||
let (status, resp) = http_exchange("POST", url, Some(body), ct)?;
|
||||
Ok(Value::Map(vec![
|
||||
("status".into(), Value::Int(status as i64)),
|
||||
("body".into(), Value::Text(resp)),
|
||||
]))
|
||||
let hdrs = headers_from_value(headers)?;
|
||||
let (status, resp) = http_exchange("POST", url, Some(body), Some(ct), &hdrs)?;
|
||||
Ok(response_map(status, resp))
|
||||
}
|
||||
|
||||
/// Generic request: method + url + optional body / content_type / headers.
|
||||
pub fn http_request(
|
||||
ctx: &HostContext,
|
||||
method: &Value,
|
||||
url: &Value,
|
||||
body: Option<&Value>,
|
||||
content_type: Option<&Value>,
|
||||
headers: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
if !ctx.allow_net() {
|
||||
return Err("http_request denied by host policy".into());
|
||||
}
|
||||
let method = as_text(method, "method")?.to_uppercase();
|
||||
let url = as_text(url, "url")?;
|
||||
let body_s = match body {
|
||||
None | Some(Value::None) => None,
|
||||
Some(v) => Some(as_text(v, "body")?),
|
||||
};
|
||||
let ct = match content_type {
|
||||
None | Some(Value::None) => {
|
||||
if body_s.is_some() && method == "POST" {
|
||||
Some("application/json; charset=utf-8")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
Some(v) => Some(as_text(v, "content_type")?),
|
||||
};
|
||||
let hdrs = headers_from_value(headers)?;
|
||||
let (status, resp) = http_exchange(&method, url, body_s, ct, &hdrs)?;
|
||||
Ok(response_map(status, resp))
|
||||
}
|
||||
|
||||
pub fn url_encode(text: &Value) -> Result<Value, String> {
|
||||
@@ -150,3 +172,21 @@ pub fn url_encode(text: &Value) -> Result<Value, String> {
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn headers_from_map() {
|
||||
let m = Value::Map(vec![
|
||||
("Authorization".into(), Value::Text("Bearer x".into())),
|
||||
("X-Test".into(), Value::Int(1)),
|
||||
]);
|
||||
let h = headers_from_value(Some(&m)).unwrap();
|
||||
assert_eq!(h.len(), 2);
|
||||
assert!(h
|
||||
.iter()
|
||||
.any(|(k, v)| k == "Authorization" && v == "Bearer x"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user