Skip to main content

agentmux_srv/drone/executor/blocks/
api_poll.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The question a `poll` trigger asks when its `query` is `api` (docs/specs/SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md
5//! §3.2): one GET of a site's list, with an optional Vault credential, answered as the items in it.
6//!
7//! The call is the API block's own ([`super::api::run`]), not a second HTTP client, so a poll has the same site binding,
8//! the same refusal of a `Host` header, the same header handling, the same size cap and timeout, and a credentialed call
9//! follows no redirect (a 3xx is an error here, said so). What differs is one thing: a poll has nobody at the desk, so it
10//! never asks the person. With a credential it uses only an "Always" the person already gave this drone for this site
11//! (`ExecutionScope::never_ask`); without one it fails at once, with no card.
12//!
13//! The filter keys: `url` (https, written out), `auth` (as the API block's), `headers`, `items` (the dotted path to the
14//! list in the answer, empty when the answer is the list), `id` (the dotted path of an item's id, `id` when left out),
15//! `limit` (at most that many items kept, 100 when left out). What comes back is outside text: each item is the answer's
16//! own, and goes to the run as `{{trigger.item}}` like the API block's output, with the same handling.
17
18use 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
25/// The value at the dotted `path` of `v`; the value itself for an empty path. Array positions are numbers (`a.0.b`).
26fn 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
38/// An item's id as text: a non-empty string or a number.
39fn 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
47/// The items in a successful answer's body, each with its id: `{ "items": [ { "id": "…", "item": <the item> } ] }`.
48/// An item with no id is not one. Pure, so it is testable without a server.
49pub(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
67/// Asks the site `filter["url"]` for its list. `filter["drone_id"]` is the drone whose job polls, set by the poller: it is
68/// who a Vault credential is granted to.
69pub(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
98/// The items in the API block's output: an error for any answer but a 2xx with a list in it.
99pub(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;