use gadk_agent::ToolError;
use serde_json::{Map, Value};
use url::Url;
use crate::operation::{Location, Operation};
#[derive(Debug, PartialEq)]
pub(crate) struct Parts {
pub(crate) url: Url,
pub(crate) headers: Vec<(String, String)>,
pub(crate) body: Option<Value>,
}
pub(crate) fn build(
op: &Operation,
base: &str,
query_api_key: Option<&(String, String)>,
args: &Value,
) -> Result<Parts, ToolError> {
let Value::Object(args) = args else {
return Err(invalid("the arguments must be a JSON object".to_string()));
};
for param in op.params.iter().filter(|p| p.required) {
if arg(args, ¶m.property).is_none() {
return Err(invalid(format!(
"missing required argument {}",
param.property
)));
}
}
if op.body.as_ref().is_some_and(|body| body.required) && arg(args, "body").is_none() {
return Err(invalid("missing required argument body".to_string()));
}
let mut path_values = Vec::new();
let mut query = Vec::new();
let mut headers = Vec::new();
for param in &op.params {
let Some(value) = arg(args, ¶m.property) else {
continue;
};
match param.location {
Location::Path => {
let text = scalar(value).ok_or_else(|| not_scalar(¶m.property))?;
if text.is_empty() {
return Err(invalid(format!(
"argument {} must not be empty",
param.property
)));
}
path_values.push((
format!("{{{}}}", param.name),
param.property.as_str(),
encode_segment(&text),
));
}
Location::Header => {
let text = scalar(value).ok_or_else(|| not_scalar(¶m.property))?;
headers.push((param.name.clone(), text));
}
Location::Query => match value {
Value::Array(items) => {
for item in items.iter().filter(|item| !item.is_null()) {
let text = scalar(item).ok_or_else(|| not_query(¶m.property))?;
query.push((param.name.clone(), text));
}
}
_ => {
let text = scalar(value).ok_or_else(|| not_query(¶m.property))?;
query.push((param.name.clone(), text));
}
},
}
}
let path = substitute_path(&op.path, &path_values)?;
if let Some((name, value)) = query_api_key {
query.push((name.clone(), value.clone()));
}
let mut url = Url::parse(&format!("{base}{path}"))
.map_err(|err| invalid(format!("cannot build the request URL {base}{path}: {err}")))?;
if !query.is_empty() {
let mut pairs = url.query_pairs_mut();
for (name, value) in &query {
pairs.append_pair(name, value);
}
}
let body = match &op.body {
Some(_) => arg(args, "body").cloned(),
None => None,
};
Ok(Parts { url, headers, body })
}
fn substitute_path(template: &str, values: &[(String, &str, String)]) -> Result<String, ToolError> {
let mut segments = Vec::new();
for segment in template.split('/') {
let mut out = segment.to_string();
let mut used = Vec::new();
for (placeholder, property, encoded) in values {
if out.contains(placeholder.as_str()) {
out = out.replace(placeholder.as_str(), encoded);
used.push((placeholder.as_str(), *property));
}
}
if !used.is_empty() && (out == "." || out == "..") {
if let [(placeholder, property)] = used[..]
&& placeholder == segment
{
return Err(invalid(format!(
"argument {property} must not be \".\" or \"..\""
)));
}
let names = used
.iter()
.map(|(_, property)| *property)
.collect::<Vec<_>>()
.join(", ");
let noun = if used.len() == 1 {
"argument"
} else {
"arguments"
};
return Err(invalid(format!(
"{noun} {names} must not form the path segment \"{out}\""
)));
}
segments.push(out);
}
Ok(segments.join("/"))
}
fn arg<'a>(args: &'a Map<String, Value>, property: &str) -> Option<&'a Value> {
args.get(property).filter(|value| !value.is_null())
}
fn scalar(value: &Value) -> Option<String> {
match value {
Value::String(text) => Some(text.clone()),
Value::Number(_) | Value::Bool(_) => Some(value.to_string()),
_ => None,
}
}
fn encode_segment(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for byte in text.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
out.push(char::from(byte));
} else {
out.push_str(&format!("%{byte:02X}"));
}
}
out
}
fn invalid(message: String) -> ToolError {
ToolError::InvalidArgument(message)
}
fn not_scalar(property: &str) -> ToolError {
invalid(format!(
"argument {property} must be a string, number or boolean"
))
}
fn not_query(property: &str) -> ToolError {
invalid(format!(
"argument {property} must be a string, number, boolean or an array of them"
))
}
#[cfg(test)]
#[path = "request_tests.rs"]
mod tests;