Skip to main content

sandogasa_kojihub/
xmlrpc.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3//! Minimal XML-RPC client using reqwest + quick-xml.
4
5use std::collections::HashMap;
6use std::fmt;
7
8use quick_xml::Reader;
9use quick_xml::events::{BytesText, Event};
10
11/// An XML-RPC value.
12#[derive(Debug, Clone)]
13pub enum Value {
14    Int(i64),
15    String(String),
16    Boolean(bool),
17    Double(f64),
18    Array(Vec<Value>),
19    Struct(HashMap<String, Value>),
20    Nil,
21}
22
23impl Value {
24    pub fn as_int(&self) -> Option<i64> {
25        match self {
26            Value::Int(i) => Some(*i),
27            _ => None,
28        }
29    }
30
31    pub fn as_str(&self) -> Option<&str> {
32        match self {
33            Value::String(s) => Some(s),
34            _ => None,
35        }
36    }
37
38    pub fn as_array(&self) -> Option<&[Value]> {
39        match self {
40            Value::Array(a) => Some(a),
41            _ => None,
42        }
43    }
44
45    pub fn as_struct(&self) -> Option<&HashMap<String, Value>> {
46        match self {
47            Value::Struct(s) => Some(s),
48            _ => None,
49        }
50    }
51
52    /// Look up a field in a struct value.
53    pub fn get(&self, key: &str) -> Option<&Value> {
54        self.as_struct()?.get(key)
55    }
56}
57
58#[derive(Debug)]
59pub enum Error {
60    Http(reqwest::Error),
61    Xml(String),
62    Fault { code: i64, message: String },
63    Parse(String),
64}
65
66impl fmt::Display for Error {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self {
69            Error::Http(e) => {
70                // reqwest's Display hides the cause ("error
71                // sending request"); walk the chain so transport
72                // failures are actually diagnosable.
73                write!(f, "HTTP error: {e}")?;
74                let mut source = std::error::Error::source(e);
75                while let Some(cause) = source {
76                    write!(f, ": {cause}")?;
77                    source = cause.source();
78                }
79                Ok(())
80            }
81            Error::Xml(e) => write!(f, "XML error: {e}"),
82            Error::Fault { code, message } => {
83                write!(f, "XML-RPC fault {code}: {message}")
84            }
85            Error::Parse(e) => write!(f, "parse error: {e}"),
86        }
87    }
88}
89
90impl std::error::Error for Error {}
91
92impl Error {
93    /// Return `true` if this error is likely transient and the
94    /// operation should be retried (e.g. HTTP 502/503/504).
95    pub fn is_retriable(&self) -> bool {
96        match self {
97            // Connection or transport failures are often transient.
98            Error::Http(_) => true,
99            // XML parse failures after a successful HTTP request
100            // usually mean we got an HTML error page instead of XML
101            // (e.g. a 502 gateway error page).
102            Error::Xml(_) => true,
103            // Koji CLI errors mentioning server errors.
104            Error::Parse(msg) => {
105                msg.contains("502")
106                    || msg.contains("503")
107                    || msg.contains("504")
108                    || msg.contains("Bad Gateway")
109                    || msg.contains("Service Unavailable")
110                    || msg.contains("Gateway Timeout")
111            }
112            // XML-RPC faults are legitimate API errors.
113            Error::Fault { .. } => false,
114        }
115    }
116}
117
118impl From<reqwest::Error> for Error {
119    fn from(e: reqwest::Error) -> Self {
120        Error::Http(e)
121    }
122}
123
124impl From<quick_xml::Error> for Error {
125    fn from(e: quick_xml::Error) -> Self {
126        Error::Xml(e.to_string())
127    }
128}
129
130/// XML-RPC client that communicates with a hub endpoint.
131pub struct Client {
132    http: reqwest::blocking::Client,
133    hub_url: String,
134}
135
136impl Client {
137    pub fn new(hub_url: &str) -> Self {
138        sandogasa_cli::install_crypto_provider();
139        Self {
140            http: reqwest::blocking::Client::builder()
141                // Fedora's infrastructure TARPITS requests without
142                // a User-Agent: the same heavy listTasks query
143                // completes with one and times out without one
144                // (measured live, 2026-07). reqwest sends none by
145                // default — always identify ourselves.
146                .user_agent(concat!("sandogasa-kojihub/", env!("CARGO_PKG_VERSION")))
147                // Match the koji CLI's HTTP/1.1; h2 to the hub
148                // showed additional hangs during the same testing.
149                .http1_only()
150                // Fedora's proxy stack also stalls heavy queries
151                // sent over a REUSED keep-alive connection
152                // (reproduced with curl --next: fresh connection
153                // ~3-90s, reused connection times out), so don't
154                // pool connections at all — the handshake cost is
155                // noise next to the queries and the polite pacing.
156                .pool_max_idle_per_host(0)
157                // Heavy queries (multi-MB decoded task pages) have
158                // been observed taking 90+ seconds on a loaded hub.
159                .timeout(std::time::Duration::from_secs(180))
160                .build()
161                .expect("build reqwest client"),
162            hub_url: hub_url.to_string(),
163        }
164    }
165
166    /// Call an XML-RPC method with the given parameters.
167    pub fn call(&self, method: &str, params: &[Value]) -> Result<Value, Error> {
168        let body = build_request(method, params);
169        let resp = self
170            .http
171            .post(&self.hub_url)
172            .header("Content-Type", "text/xml")
173            .body(body)
174            .send()?
175            // Surface HTTP-level failures (proxy 502s and friends)
176            // as retriable Http errors instead of depending on
177            // whatever body shape the error page happens to have.
178            .error_for_status()?
179            .text()?;
180        parse_response(&resp)
181    }
182}
183
184// --- Request building ---
185
186fn build_request(method: &str, params: &[Value]) -> String {
187    let mut xml = format!(
188        "<?xml version=\"1.0\"?>\n\
189         <methodCall>\n\
190         <methodName>{method}</methodName>\n\
191         <params>\n"
192    );
193    for param in params {
194        xml.push_str("<param>");
195        write_value(&mut xml, param);
196        xml.push_str("</param>\n");
197    }
198    xml.push_str("</params>\n</methodCall>");
199    xml
200}
201
202fn write_value(xml: &mut String, value: &Value) {
203    xml.push_str("<value>");
204    match value {
205        Value::Int(i) => {
206            xml.push_str(&format!("<int>{i}</int>"));
207        }
208        Value::String(s) => {
209            xml.push_str("<string>");
210            xml.push_str(&quick_xml::escape::escape(s));
211            xml.push_str("</string>");
212        }
213        Value::Boolean(b) => {
214            xml.push_str(&format!("<boolean>{}</boolean>", if *b { 1 } else { 0 }));
215        }
216        Value::Double(d) => {
217            xml.push_str(&format!("<double>{d}</double>"));
218        }
219        Value::Array(items) => {
220            xml.push_str("<array><data>");
221            for item in items {
222                write_value(xml, item);
223            }
224            xml.push_str("</data></array>");
225        }
226        Value::Struct(map) => {
227            xml.push_str("<struct>");
228            for (key, val) in map {
229                xml.push_str(&format!("<member><name>{key}</name>"));
230                write_value(xml, val);
231                xml.push_str("</member>");
232            }
233            xml.push_str("</struct>");
234        }
235        Value::Nil => {
236            xml.push_str("<nil/>");
237        }
238    }
239    xml.push_str("</value>");
240}
241
242// --- Response parsing ---
243
244pub fn parse_response(xml: &str) -> Result<Value, Error> {
245    let mut reader = Reader::from_str(xml);
246    reader.config_mut().trim_text(true);
247
248    loop {
249        match reader.read_event() {
250            Ok(Event::Start(e)) => match e.name().as_ref() {
251                b"params" => return parse_params(&mut reader),
252                b"fault" => return parse_fault(&mut reader),
253                _ => {}
254            },
255            Ok(Event::Eof) => {
256                return Err(Error::Parse("unexpected EOF before params or fault".into()));
257            }
258            Err(e) => return Err(Error::Xml(e.to_string())),
259            _ => {}
260        }
261    }
262}
263
264fn parse_params(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
265    loop {
266        match reader.read_event() {
267            Ok(Event::Start(e)) if e.name().as_ref() == b"value" => {
268                return parse_value_content(reader);
269            }
270            Ok(Event::End(e)) if e.name().as_ref() == b"params" => {
271                return Ok(Value::Nil);
272            }
273            Ok(Event::Eof) => {
274                return Err(Error::Parse("unexpected EOF in params".into()));
275            }
276            Err(e) => return Err(e.into()),
277            _ => {}
278        }
279    }
280}
281
282fn parse_fault(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
283    loop {
284        match reader.read_event() {
285            Ok(Event::Start(e)) if e.name().as_ref() == b"value" => {
286                let value = parse_value_content(reader)?;
287                let code = value
288                    .get("faultCode")
289                    .and_then(|v| v.as_int())
290                    .unwrap_or(-1);
291                let message = value
292                    .get("faultString")
293                    .and_then(|v| v.as_str())
294                    .unwrap_or("unknown fault")
295                    .to_string();
296                return Err(Error::Fault { code, message });
297            }
298            Ok(Event::Eof) => {
299                return Err(Error::Parse("unexpected EOF in fault".into()));
300            }
301            Err(e) => return Err(e.into()),
302            _ => {}
303        }
304    }
305}
306
307/// Parse the content inside a `<value>` tag (opening `<value>` already consumed).
308fn parse_value_content(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
309    loop {
310        match reader.read_event() {
311            Ok(Event::Start(e)) => {
312                let tag = e.name().as_ref().to_vec();
313                match tag.as_slice() {
314                    b"int" | b"i4" | b"i8" => {
315                        let text = read_text_content(reader)?;
316                        skip_to_end(reader, b"value")?;
317                        return Ok(Value::Int(text.parse::<i64>().map_err(|e| {
318                            Error::Parse(format!("invalid int '{text}': {e}"))
319                        })?));
320                    }
321                    b"string" => {
322                        let text = read_text_content(reader)?;
323                        skip_to_end(reader, b"value")?;
324                        return Ok(Value::String(text));
325                    }
326                    b"boolean" => {
327                        let text = read_text_content(reader)?;
328                        skip_to_end(reader, b"value")?;
329                        return Ok(Value::Boolean(text == "1" || text == "true"));
330                    }
331                    b"double" => {
332                        let text = read_text_content(reader)?;
333                        skip_to_end(reader, b"value")?;
334                        return Ok(Value::Double(text.parse::<f64>().map_err(|e| {
335                            Error::Parse(format!("invalid double '{text}': {e}"))
336                        })?));
337                    }
338                    b"struct" => {
339                        let s = parse_struct_content(reader)?;
340                        skip_to_end(reader, b"value")?;
341                        return Ok(s);
342                    }
343                    b"array" => {
344                        let a = parse_array_content(reader)?;
345                        skip_to_end(reader, b"value")?;
346                        return Ok(a);
347                    }
348                    _ => {
349                        // Unknown type tag — treat content as string.
350                        let text = read_text_content(reader)?;
351                        skip_to_end(reader, b"value")?;
352                        return Ok(Value::String(text));
353                    }
354                }
355            }
356            Ok(Event::Empty(e)) if e.name().as_ref() == b"nil" => {
357                skip_to_end(reader, b"value")?;
358                return Ok(Value::Nil);
359            }
360            Ok(Event::Text(t)) => {
361                let text = decode_text(&t)?;
362                if !text.trim().is_empty() {
363                    // Bare text in <value> is implicitly a string.
364                    skip_to_end(reader, b"value")?;
365                    return Ok(Value::String(text));
366                }
367            }
368            Ok(Event::End(e)) if e.name().as_ref() == b"value" => {
369                return Ok(Value::String(String::new()));
370            }
371            Ok(Event::Eof) => {
372                return Err(Error::Parse("unexpected EOF in value".into()));
373            }
374            Err(e) => return Err(e.into()),
375            _ => {}
376        }
377    }
378}
379
380fn parse_struct_content(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
381    let mut map = HashMap::new();
382    loop {
383        match reader.read_event() {
384            Ok(Event::Start(e)) if e.name().as_ref() == b"member" => {
385                let (name, value) = parse_member(reader)?;
386                map.insert(name, value);
387            }
388            Ok(Event::End(e)) if e.name().as_ref() == b"struct" => {
389                return Ok(Value::Struct(map));
390            }
391            Ok(Event::Eof) => {
392                return Err(Error::Parse("unexpected EOF in struct".into()));
393            }
394            Err(e) => return Err(e.into()),
395            _ => {}
396        }
397    }
398}
399
400fn parse_member(reader: &mut Reader<&[u8]>) -> Result<(String, Value), Error> {
401    let mut name = String::new();
402    let mut value = Value::Nil;
403    loop {
404        match reader.read_event() {
405            Ok(Event::Start(e)) => match e.name().as_ref() {
406                b"name" => {
407                    name = read_text_content(reader)?;
408                }
409                b"value" => {
410                    value = parse_value_content(reader)?;
411                }
412                _ => {}
413            },
414            Ok(Event::End(e)) if e.name().as_ref() == b"member" => {
415                return Ok((name, value));
416            }
417            Ok(Event::Eof) => {
418                return Err(Error::Parse("unexpected EOF in member".into()));
419            }
420            Err(e) => return Err(e.into()),
421            _ => {}
422        }
423    }
424}
425
426fn parse_array_content(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
427    let mut items = Vec::new();
428    loop {
429        match reader.read_event() {
430            Ok(Event::Start(e)) => {
431                if e.name().as_ref() == b"data" {
432                    loop {
433                        match reader.read_event() {
434                            Ok(Event::Start(e2)) if e2.name().as_ref() == b"value" => {
435                                items.push(parse_value_content(reader)?);
436                            }
437                            Ok(Event::End(e2)) if e2.name().as_ref() == b"data" => break,
438                            Ok(Event::Eof) => {
439                                return Err(Error::Parse("unexpected EOF in array data".into()));
440                            }
441                            Err(e) => return Err(e.into()),
442                            _ => {}
443                        }
444                    }
445                }
446            }
447            Ok(Event::End(e)) if e.name().as_ref() == b"array" => {
448                return Ok(Value::Array(items));
449            }
450            Ok(Event::Eof) => {
451                return Err(Error::Parse("unexpected EOF in array".into()));
452            }
453            Err(e) => return Err(e.into()),
454            _ => {}
455        }
456    }
457}
458
459/// Read text content until the matching end tag.
460/// Decode and unescape a quick-xml text node to an owned String.
461///
462/// quick-xml 0.40 dropped `BytesText::unescape`; decoding and
463/// entity-unescaping are now separate explicit steps.
464fn decode_text(t: &BytesText) -> Result<String, Error> {
465    let decoded = t.decode().map_err(|e| Error::Xml(e.to_string()))?;
466    Ok(quick_xml::escape::unescape(&decoded)
467        .map_err(|e| Error::Xml(e.to_string()))?
468        .into_owned())
469}
470
471fn read_text_content(reader: &mut Reader<&[u8]>) -> Result<String, Error> {
472    let mut text = String::new();
473    loop {
474        match reader.read_event() {
475            Ok(Event::Text(t)) => {
476                text.push_str(&decode_text(&t)?);
477            }
478            Ok(Event::End(_)) => return Ok(text),
479            Ok(Event::Eof) => {
480                return Err(Error::Parse("unexpected EOF reading text".into()));
481            }
482            Err(e) => return Err(e.into()),
483            _ => {}
484        }
485    }
486}
487
488/// Skip events until we find an end tag matching the given name at depth 0.
489fn skip_to_end(reader: &mut Reader<&[u8]>, end_tag: &[u8]) -> Result<(), Error> {
490    let mut depth: u32 = 0;
491    loop {
492        match reader.read_event() {
493            Ok(Event::Start(_)) => depth += 1,
494            Ok(Event::End(e)) => {
495                if depth == 0 && e.name().as_ref() == end_tag {
496                    return Ok(());
497                }
498                depth = depth.saturating_sub(1);
499            }
500            Ok(Event::Eof) => return Ok(()),
501            Err(e) => return Err(e.into()),
502            _ => {}
503        }
504    }
505}
506
507#[cfg(test)]
508mod tests {
509    use super::*;
510
511    #[test]
512    fn test_build_request_int() {
513        let xml = build_request("getBuild", &[Value::Int(42)]);
514        assert!(xml.contains("<methodName>getBuild</methodName>"));
515        assert!(xml.contains("<int>42</int>"));
516    }
517
518    #[test]
519    fn test_build_request_string_escaping() {
520        let xml = build_request("test", &[Value::String("a<b&c".into())]);
521        assert!(xml.contains("a&lt;b&amp;c"));
522    }
523
524    #[test]
525    fn test_parse_int_response() {
526        let xml = r#"<?xml version="1.0"?>
527            <methodResponse><params><param>
528            <value><int>42</int></value>
529            </param></params></methodResponse>"#;
530        let v = parse_response(xml).unwrap();
531        assert_eq!(v.as_int(), Some(42));
532    }
533
534    #[test]
535    fn test_parse_string_response() {
536        let xml = r#"<?xml version="1.0"?>
537            <methodResponse><params><param>
538            <value><string>hello world</string></value>
539            </param></params></methodResponse>"#;
540        let v = parse_response(xml).unwrap();
541        assert_eq!(v.as_str(), Some("hello world"));
542    }
543
544    #[test]
545    fn test_parse_struct_response() {
546        let xml = r#"<?xml version="1.0"?>
547            <methodResponse><params><param>
548            <value><struct>
549                <member><name>task_id</name><value><int>12345</int></value></member>
550                <member><name>nvr</name><value><string>foo-1.0-1.fc42</string></value></member>
551            </struct></value>
552            </param></params></methodResponse>"#;
553        let v = parse_response(xml).unwrap();
554        assert_eq!(v.get("task_id").unwrap().as_int(), Some(12345));
555        assert_eq!(v.get("nvr").unwrap().as_str(), Some("foo-1.0-1.fc42"));
556    }
557
558    #[test]
559    fn test_parse_array_response() {
560        let xml = r#"<?xml version="1.0"?>
561            <methodResponse><params><param>
562            <value><array><data>
563                <value><int>1</int></value>
564                <value><int>2</int></value>
565                <value><int>3</int></value>
566            </data></array></value>
567            </param></params></methodResponse>"#;
568        let v = parse_response(xml).unwrap();
569        let arr = v.as_array().unwrap();
570        assert_eq!(arr.len(), 3);
571        assert_eq!(arr[0].as_int(), Some(1));
572        assert_eq!(arr[2].as_int(), Some(3));
573    }
574
575    #[test]
576    fn test_parse_nested_struct_array() {
577        let xml = r#"<?xml version="1.0"?>
578            <methodResponse><params><param>
579            <value><array><data>
580                <value><struct>
581                    <member><name>id</name><value><int>100</int></value></member>
582                    <member><name>method</name><value><string>buildArch</string></value></member>
583                    <member><name>arch</name><value><string>x86_64</string></value></member>
584                </struct></value>
585                <value><struct>
586                    <member><name>id</name><value><int>101</int></value></member>
587                    <member><name>method</name><value><string>buildArch</string></value></member>
588                    <member><name>arch</name><value><string>aarch64</string></value></member>
589                </struct></value>
590            </data></array></value>
591            </param></params></methodResponse>"#;
592        let v = parse_response(xml).unwrap();
593        let arr = v.as_array().unwrap();
594        assert_eq!(arr.len(), 2);
595        assert_eq!(arr[0].get("id").unwrap().as_int(), Some(100));
596        assert_eq!(arr[0].get("arch").unwrap().as_str(), Some("x86_64"));
597        assert_eq!(arr[1].get("id").unwrap().as_int(), Some(101));
598    }
599
600    #[test]
601    fn test_parse_boolean_response() {
602        let xml = r#"<?xml version="1.0"?>
603            <methodResponse><params><param>
604            <value><boolean>1</boolean></value>
605            </param></params></methodResponse>"#;
606        let v = parse_response(xml).unwrap();
607        assert_eq!(v.as_int(), None);
608        match v {
609            Value::Boolean(b) => assert!(b),
610            _ => panic!("expected boolean"),
611        }
612    }
613
614    #[test]
615    fn test_parse_nil_response() {
616        let xml = r#"<?xml version="1.0"?>
617            <methodResponse><params><param>
618            <value><nil/></value>
619            </param></params></methodResponse>"#;
620        let v = parse_response(xml).unwrap();
621        assert!(matches!(v, Value::Nil));
622    }
623
624    #[test]
625    fn test_parse_fault_response() {
626        let xml = r#"<?xml version="1.0"?>
627            <methodResponse><fault><value><struct>
628                <member><name>faultCode</name><value><int>1000</int></value></member>
629                <member><name>faultString</name><value><string>No such build</string></value></member>
630            </struct></value></fault></methodResponse>"#;
631        let err = parse_response(xml).unwrap_err();
632        match err {
633            Error::Fault { code, message } => {
634                assert_eq!(code, 1000);
635                assert_eq!(message, "No such build");
636            }
637            _ => panic!("expected Fault error, got: {err}"),
638        }
639    }
640
641    #[test]
642    fn test_parse_bare_text_as_string() {
643        let xml = r#"<?xml version="1.0"?>
644            <methodResponse><params><param>
645            <value>bare text</value>
646            </param></params></methodResponse>"#;
647        let v = parse_response(xml).unwrap();
648        assert_eq!(v.as_str(), Some("bare text"));
649    }
650
651    #[test]
652    fn test_is_retriable_http_error() {
653        // reqwest errors are retriable (connection failures, etc.)
654        let err = Error::Xml("unexpected token".into());
655        assert!(err.is_retriable());
656    }
657
658    #[test]
659    fn test_is_retriable_parse_502() {
660        let err = Error::Parse("koji download-logs failed: 502 Bad Gateway".into());
661        assert!(err.is_retriable());
662    }
663
664    #[test]
665    fn test_is_retriable_parse_503() {
666        let err = Error::Parse("503 Service Unavailable".into());
667        assert!(err.is_retriable());
668    }
669
670    #[test]
671    fn test_is_not_retriable_fault() {
672        let err = Error::Fault {
673            code: 1000,
674            message: "No such build".into(),
675        };
676        assert!(!err.is_retriable());
677    }
678
679    #[test]
680    fn test_is_not_retriable_parse_not_found() {
681        let err = Error::Parse("root.log not found for task 123".into());
682        assert!(!err.is_retriable());
683    }
684}