agentmux_srv/drone/executor/blocks/
api_poll.rs1use serde_json::{json, Map, Value};
19
20use crate::drone::data_flow::ExecutionScope;
21use crate::drone::types::FlowNode;
22
23use crate::backend::jobs::poll::{API_DEFAULT_ITEMS as DEFAULT_ITEMS, API_MAX_ITEMS as MAX_ITEMS};
24
25fn at<'a>(v: &'a Value, path: &str) -> Option<&'a Value> {
27 let mut cur = v;
28 for key in path.split('.').map(str::trim).filter(|k| !k.is_empty()) {
29 cur = match cur {
30 Value::Object(m) => m.get(key)?,
31 Value::Array(a) => a.get(key.parse::<usize>().ok()?)?,
32 _ => return None,
33 };
34 }
35 Some(cur)
36}
37
38fn id_text(v: &Value) -> Option<String> {
40 match v {
41 Value::String(s) if !s.is_empty() => Some(s.clone()),
42 Value::Number(n) => Some(n.to_string()),
43 _ => None,
44 }
45}
46
47pub(crate) fn items_in(body: &Value, items_path: &str, id_path: &str, limit: usize) -> Result<Value, String> {
50 let list = at(body, items_path).and_then(Value::as_array).ok_or_else(|| {
51 if items_path.trim().is_empty() {
52 "the answer is not a list: give `items`, the path to the list in it".to_string()
53 } else {
54 format!("the answer has no list at `{items_path}`")
55 }
56 })?;
57 let id_path = if id_path.trim().is_empty() { "id" } else { id_path };
58 let limit = limit.clamp(1, MAX_ITEMS);
59 let items: Vec<Value> = list
60 .iter()
61 .filter_map(|item| at(item, id_path).and_then(id_text).map(|id| json!({ "id": id, "item": item })))
62 .take(limit)
63 .collect();
64 Ok(json!({ "items": items }))
65}
66
67pub(crate) async fn ask(filter: Map<String, Value>) -> Result<Value, String> {
70 let text = |k: &str| filter.get(k).and_then(Value::as_str).unwrap_or("").trim().to_string();
71 let url = text("url");
72 if url.is_empty() {
73 return Err("a poll of api has a url".to_string());
74 }
75 let mut data = Map::new();
76 data.insert("method".into(), json!("GET"));
77 data.insert("url".into(), json!(url));
78 if let Some(h) = filter.get("headers") {
79 data.insert("headers".into(), h.clone());
80 }
81 let has_auth = filter.get("auth").is_some_and(|a| !a.is_null());
82 if has_auth {
83 data.insert("auth".into(), filter["auth"].clone());
84 }
85 let drone_id = text("drone_id");
86 if has_auth && drone_id.is_empty() {
87 return Err("a poll with a Vault credential belongs to a drone job: the credential is the drone's".to_string());
88 }
89 let mut scope = ExecutionScope::new();
90 scope.drone_id = drone_id;
91 scope.never_ask = true;
92 let node = FlowNode { id: "poll".to_string(), position: Default::default(), data: Value::Object(data), node_type: None };
93 let out = super::api::run(&node, &scope).await?;
94 let limit = filter.get("limit").and_then(Value::as_u64).map_or(DEFAULT_ITEMS, |n| n as usize);
95 items_of_output(&out, &text("items"), &text("id"), limit)
96}
97
98pub(crate) fn items_of_output(out: &Value, items_path: &str, id_path: &str, limit: usize) -> Result<Value, String> {
100 let status = out.get("status").and_then(Value::as_u64).unwrap_or(0);
101 if !(200..300).contains(&status) {
102 let note = if (300..400).contains(&status) {
103 " (a call with a credential follows no redirect, so a redirect is an error: poll the address it moves to)"
104 } else {
105 ""
106 };
107 return Err(format!("the site answered {status}{note}"));
108 }
109 let body = match out.get("body") {
110 Some(Value::String(s)) => serde_json::from_str::<Value>(s).map_err(|_| "the answer is not JSON".to_string())?,
111 Some(other) => other.clone(),
112 None => Value::Null,
113 };
114 items_in(&body, items_path, id_path, limit)
115}
116
117#[cfg(test)]
118#[path = "api_poll_tests.rs"]
119mod tests;