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::{BytesRef, 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/// Default bound on a single hub request.
131///
132/// **Sized for the first page into a cold region, not for the steady
133/// state.** Those differ by most of an order of magnitude and the steady
134/// state is what a casual measurement finds: listing January 2025 at
135/// twenty months' depth settled at 27-34s a 4000-row page across nine
136/// consecutive pages, while the first page into that stretch exceeded
137/// 180s and was abandoned there.
138///
139/// The two failure modes are not symmetric, which is why this errs high.
140/// Too low discards work that was nearly done and charges the hub for it
141/// again — three times, with retries — and a deep sweep can stop making
142/// progress rather than merely slow down. Too high only delays noticing a
143/// genuine hang, which the duty-cycle pacing and the retry budget already
144/// tolerate.
145pub const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
146
147/// Environment variable overriding [`DEFAULT_TIMEOUT`], in seconds.
148///
149/// The same variable `sandogasa-koji` uses for the `koji` CLI,
150/// deliberately: it is one knob for "how long may a Koji request take",
151/// and whoever has had to raise it for one path usually means both. A
152/// value of `0` waits forever, for a caller willing to block.
153///
154/// A setting and its override belong together — a crate that takes the
155/// first without the second leaves the caller with a wall and no door.
156pub const TIMEOUT_ENV: &str = "SANDOGASA_KOJI_TIMEOUT";
157
158/// The configured request bound: the environment if it says so, else
159/// [`DEFAULT_TIMEOUT`]. `None` means no bound at all.
160pub fn configured_timeout() -> Option<std::time::Duration> {
161    match std::env::var(TIMEOUT_ENV)
162        .ok()
163        .and_then(|v| v.trim().parse::<u64>().ok())
164    {
165        Some(0) => None,
166        Some(secs) => Some(std::time::Duration::from_secs(secs)),
167        None => Some(DEFAULT_TIMEOUT),
168    }
169}
170
171/// XML-RPC client that communicates with a hub endpoint.
172pub struct Client {
173    http: reqwest::blocking::Client,
174    hub_url: String,
175}
176
177impl Client {
178    /// A client bound by [`configured_timeout`].
179    pub fn new(hub_url: &str) -> Self {
180        Self::with_timeout(hub_url, configured_timeout())
181    }
182
183    /// A client bound by `timeout`, or unbounded when it is `None`.
184    ///
185    /// For a caller that knows better than the environment does — a deep
186    /// sweep that has measured what its own pages cost, say.
187    pub fn with_timeout(hub_url: &str, timeout: Option<std::time::Duration>) -> Self {
188        sandogasa_cli::install_crypto_provider();
189        let builder = reqwest::blocking::Client::builder()
190            // Fedora's infrastructure TARPITS requests without
191            // a User-Agent: the same heavy listTasks query
192            // completes with one and times out without one
193            // (measured live, 2026-07). reqwest sends none by
194            // default — always identify ourselves.
195            .user_agent(concat!("sandogasa-kojihub/", env!("CARGO_PKG_VERSION")))
196            // Match the koji CLI's HTTP/1.1; h2 to the hub
197            // showed additional hangs during the same testing.
198            .http1_only()
199            // Fedora's proxy stack also stalls heavy queries
200            // sent over a REUSED keep-alive connection
201            // (reproduced with curl --next: fresh connection
202            // ~3-90s, reused connection times out), so don't
203            // pool connections at all — the handshake cost is
204            // noise next to the queries and the polite pacing.
205            .pool_max_idle_per_host(0);
206        // Heavy queries (multi-MB decoded task pages) have been observed
207        // taking 90+ seconds on a loaded hub and about 300s at twenty
208        // months' depth. Past the bound the request is abandoned and the
209        // retry pays the hub cost again, so too low a value stops a deep
210        // sweep progressing rather than merely slowing it.
211        //
212        // Unbounded is the *absence* of a bound, not a very large one:
213        // reqwest adds the duration to an `Instant`, and a sentinel near
214        // `u64::MAX` overflows when it does.
215        let builder = match timeout {
216            Some(bound) => builder.timeout(bound),
217            None => builder,
218        };
219        Self {
220            http: builder.build().expect("build reqwest client"),
221            // Normalised, so a hub given as ".../kojihub/" is the same
222            // client as one given as ".../kojihu" — the difference is a
223            // typo, not a different hub.
224            hub_url: hub_url.trim_end_matches('/').to_string(),
225        }
226    }
227
228    /// Call an XML-RPC method with the given parameters.
229    /// The hub this client talks to, for callers that report it. Any
230    /// trailing slash has been trimmed.
231    pub fn hub_url(&self) -> &str {
232        &self.hub_url
233    }
234
235    /// Several calls in one request, through the hub's `multiCall`:
236    /// one round trip instead of one each. The outer `Err` is the
237    /// request failing; each inner result is one call's answer, or its
238    /// fault, in the order the calls were given.
239    pub fn multicall(
240        &self,
241        calls: &[(&str, Vec<Value>)],
242    ) -> Result<Vec<Result<Value, Error>>, Error> {
243        if calls.is_empty() {
244            return Ok(Vec::new());
245        }
246        let list = calls
247            .iter()
248            .map(|(method, params)| {
249                Value::Struct(HashMap::from([
250                    ("methodName".to_string(), Value::String(method.to_string())),
251                    ("params".to_string(), Value::Array(params.clone())),
252                ]))
253            })
254            .collect();
255        let answer = self.call("multiCall", &[Value::Array(list)])?;
256        let items = answer
257            .as_array()
258            .ok_or_else(|| Error::Parse("multiCall did not answer a list".into()))?;
259        if items.len() != calls.len() {
260            return Err(Error::Parse(format!(
261                "multiCall answered {} results for {} calls",
262                items.len(),
263                calls.len()
264            )));
265        }
266        Ok(items.iter().map(multicall_result).collect())
267    }
268
269    pub fn call(&self, method: &str, params: &[Value]) -> Result<Value, Error> {
270        let body = build_request(method, params);
271        let resp = self
272            .http
273            .post(&self.hub_url)
274            .header("Content-Type", "text/xml")
275            .body(body)
276            .send()?
277            // Surface HTTP-level failures (proxy 502s and friends)
278            // as retriable Http errors instead of depending on
279            // whatever body shape the error page happens to have.
280            .error_for_status()?
281            .text()?;
282        parse_response(&resp)
283    }
284}
285
286/// One entry of a `multiCall` answer: the result wrapped in a
287/// one-element list, or a fault struct.
288fn multicall_result(item: &Value) -> Result<Value, Error> {
289    if let Some(code) = item.get("faultCode").and_then(Value::as_int) {
290        let message = item
291            .get("faultString")
292            .and_then(Value::as_str)
293            .unwrap_or("")
294            .to_string();
295        return Err(Error::Fault { code, message });
296    }
297    match item.as_array() {
298        Some([result]) => Ok(result.clone()),
299        _ => Err(Error::Parse(
300            "multiCall entry is neither a result nor a fault".into(),
301        )),
302    }
303}
304
305// --- Request building ---
306
307fn build_request(method: &str, params: &[Value]) -> String {
308    let mut xml = format!(
309        "<?xml version=\"1.0\"?>\n\
310         <methodCall>\n\
311         <methodName>{method}</methodName>\n\
312         <params>\n"
313    );
314    for param in params {
315        xml.push_str("<param>");
316        write_value(&mut xml, param);
317        xml.push_str("</param>\n");
318    }
319    xml.push_str("</params>\n</methodCall>");
320    xml
321}
322
323fn write_value(xml: &mut String, value: &Value) {
324    xml.push_str("<value>");
325    match value {
326        Value::Int(i) => {
327            xml.push_str(&format!("<int>{i}</int>"));
328        }
329        Value::String(s) => {
330            xml.push_str("<string>");
331            xml.push_str(&quick_xml::escape::escape(s));
332            xml.push_str("</string>");
333        }
334        Value::Boolean(b) => {
335            xml.push_str(&format!("<boolean>{}</boolean>", if *b { 1 } else { 0 }));
336        }
337        Value::Double(d) => {
338            xml.push_str(&format!("<double>{d}</double>"));
339        }
340        Value::Array(items) => {
341            xml.push_str("<array><data>");
342            for item in items {
343                write_value(xml, item);
344            }
345            xml.push_str("</data></array>");
346        }
347        Value::Struct(map) => {
348            xml.push_str("<struct>");
349            for (key, val) in map {
350                xml.push_str(&format!("<member><name>{key}</name>"));
351                write_value(xml, val);
352                xml.push_str("</member>");
353            }
354            xml.push_str("</struct>");
355        }
356        Value::Nil => {
357            xml.push_str("<nil/>");
358        }
359    }
360    xml.push_str("</value>");
361}
362
363// --- Response parsing ---
364
365pub fn parse_response(xml: &str) -> Result<Value, Error> {
366    // Text is not trimmed: a string's own spaces are part of it, and
367    // quick-xml splits text at each entity (`Crha &lt;mcrha@…&gt;`), so
368    // trimming each piece ate the spaces beside one. The parsers skip
369    // the whitespace between elements themselves.
370    let mut reader = Reader::from_str(xml);
371
372    loop {
373        match reader.read_event() {
374            Ok(Event::Start(e)) => match e.name().as_ref() {
375                "params" => return parse_params(&mut reader),
376                "fault" => return parse_fault(&mut reader),
377                _ => {}
378            },
379            Ok(Event::Eof) => {
380                return Err(Error::Parse("unexpected EOF before params or fault".into()));
381            }
382            Err(e) => return Err(Error::Xml(e.to_string())),
383            _ => {}
384        }
385    }
386}
387
388fn parse_params(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
389    loop {
390        match reader.read_event() {
391            Ok(Event::Start(e)) if e.name().as_ref() == "value" => {
392                return parse_value_content(reader);
393            }
394            Ok(Event::End(e)) if e.name().as_ref() == "params" => {
395                return Ok(Value::Nil);
396            }
397            Ok(Event::Eof) => {
398                return Err(Error::Parse("unexpected EOF in params".into()));
399            }
400            Err(e) => return Err(e.into()),
401            _ => {}
402        }
403    }
404}
405
406fn parse_fault(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
407    loop {
408        match reader.read_event() {
409            Ok(Event::Start(e)) if e.name().as_ref() == "value" => {
410                let value = parse_value_content(reader)?;
411                let code = value
412                    .get("faultCode")
413                    .and_then(|v| v.as_int())
414                    .unwrap_or(-1);
415                let message = value
416                    .get("faultString")
417                    .and_then(|v| v.as_str())
418                    .unwrap_or("unknown fault")
419                    .to_string();
420                return Err(Error::Fault { code, message });
421            }
422            Ok(Event::Eof) => {
423                return Err(Error::Parse("unexpected EOF in fault".into()));
424            }
425            Err(e) => return Err(e.into()),
426            _ => {}
427        }
428    }
429}
430
431/// Parse the content inside a `<value>` tag (opening `<value>` already consumed).
432fn parse_value_content(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
433    // Text outside a type tag: whitespace before one, or a bare string,
434    // which may be split at entities like any other text.
435    let mut bare = String::new();
436    loop {
437        match reader.read_event() {
438            Ok(Event::Start(e)) => {
439                let tag = e.name().as_ref().to_string();
440                match tag.as_str() {
441                    "int" | "i4" | "i8" => {
442                        let text = read_text_content(reader)?;
443                        let text = text.trim();
444                        skip_to_end(reader, "value")?;
445                        return Ok(Value::Int(text.parse::<i64>().map_err(|e| {
446                            Error::Parse(format!("invalid int '{text}': {e}"))
447                        })?));
448                    }
449                    "string" => {
450                        let text = read_text_content(reader)?;
451                        skip_to_end(reader, "value")?;
452                        return Ok(Value::String(text));
453                    }
454                    "boolean" => {
455                        let text = read_text_content(reader)?;
456                        let text = text.trim();
457                        skip_to_end(reader, "value")?;
458                        return Ok(Value::Boolean(text == "1" || text == "true"));
459                    }
460                    "double" => {
461                        let text = read_text_content(reader)?;
462                        let text = text.trim();
463                        skip_to_end(reader, "value")?;
464                        return Ok(Value::Double(text.parse::<f64>().map_err(|e| {
465                            Error::Parse(format!("invalid double '{text}': {e}"))
466                        })?));
467                    }
468                    "struct" => {
469                        let s = parse_struct_content(reader)?;
470                        skip_to_end(reader, "value")?;
471                        return Ok(s);
472                    }
473                    "array" => {
474                        let a = parse_array_content(reader)?;
475                        skip_to_end(reader, "value")?;
476                        return Ok(a);
477                    }
478                    _ => {
479                        // Unknown type tag (`base64`, `dateTime.iso8601`)
480                        // — treat content as string. Python writes base64
481                        // across lines, so its whitespace is not data.
482                        let text = read_text_content(reader)?;
483                        skip_to_end(reader, "value")?;
484                        return Ok(Value::String(text.trim().to_string()));
485                    }
486                }
487            }
488            Ok(Event::Empty(e)) if e.name().as_ref() == "nil" => {
489                skip_to_end(reader, "value")?;
490                return Ok(Value::Nil);
491            }
492            // Bare text in <value> is implicitly a string; whitespace
493            // alone is the indentation of an empty one.
494            Ok(Event::End(e)) if e.name().as_ref() == "value" => {
495                if bare.trim().is_empty() {
496                    bare.clear();
497                }
498                return Ok(Value::String(bare));
499            }
500            Ok(ev) if push_text(&mut bare, &ev)? => {}
501            Ok(Event::Eof) => {
502                return Err(Error::Parse("unexpected EOF in value".into()));
503            }
504            Err(e) => return Err(e.into()),
505            _ => {}
506        }
507    }
508}
509
510fn parse_struct_content(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
511    let mut map = HashMap::new();
512    loop {
513        match reader.read_event() {
514            Ok(Event::Start(e)) if e.name().as_ref() == "member" => {
515                let (name, value) = parse_member(reader)?;
516                map.insert(name, value);
517            }
518            Ok(Event::End(e)) if e.name().as_ref() == "struct" => {
519                return Ok(Value::Struct(map));
520            }
521            Ok(Event::Eof) => {
522                return Err(Error::Parse("unexpected EOF in struct".into()));
523            }
524            Err(e) => return Err(e.into()),
525            _ => {}
526        }
527    }
528}
529
530fn parse_member(reader: &mut Reader<&[u8]>) -> Result<(String, Value), Error> {
531    let mut name = String::new();
532    let mut value = Value::Nil;
533    loop {
534        match reader.read_event() {
535            Ok(Event::Start(e)) => match e.name().as_ref() {
536                "name" => {
537                    name = read_text_content(reader)?.trim().to_string();
538                }
539                "value" => {
540                    value = parse_value_content(reader)?;
541                }
542                _ => {}
543            },
544            Ok(Event::End(e)) if e.name().as_ref() == "member" => {
545                return Ok((name, value));
546            }
547            Ok(Event::Eof) => {
548                return Err(Error::Parse("unexpected EOF in member".into()));
549            }
550            Err(e) => return Err(e.into()),
551            _ => {}
552        }
553    }
554}
555
556fn parse_array_content(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
557    let mut items = Vec::new();
558    loop {
559        match reader.read_event() {
560            Ok(Event::Start(e)) => {
561                if e.name().as_ref() == "data" {
562                    loop {
563                        match reader.read_event() {
564                            Ok(Event::Start(e2)) if e2.name().as_ref() == "value" => {
565                                items.push(parse_value_content(reader)?);
566                            }
567                            Ok(Event::End(e2)) if e2.name().as_ref() == "data" => break,
568                            Ok(Event::Eof) => {
569                                return Err(Error::Parse("unexpected EOF in array data".into()));
570                            }
571                            Err(e) => return Err(e.into()),
572                            _ => {}
573                        }
574                    }
575                }
576            }
577            Ok(Event::End(e)) if e.name().as_ref() == "array" => {
578                return Ok(Value::Array(items));
579            }
580            Ok(Event::Eof) => {
581                return Err(Error::Parse("unexpected EOF in array".into()));
582            }
583            Err(e) => return Err(e.into()),
584            _ => {}
585        }
586    }
587}
588
589/// What an entity or character reference stands for: `&lt;` is `<`,
590/// `&#233;` is `é`.
591fn resolve_ref(r: &BytesRef) -> Result<String, Error> {
592    if let Some(c) = r
593        .resolve_char_ref()
594        .map_err(|e| Error::Xml(e.to_string()))?
595    {
596        return Ok(c.to_string());
597    }
598    quick_xml::escape::resolve_predefined_entity(r)
599        .map(str::to_string)
600        .ok_or_else(|| Error::Parse(format!("unknown entity &{};", &**r)))
601}
602
603/// Append to `buf` the text `event` carries, if it carries any, and say
604/// whether it did. quick-xml 0.42 splits text at every reference, which
605/// arrives as an event of its own (`Crha &lt;mcrha@…&gt;` is a text, a
606/// reference, a text, …), and CDATA is another; a reader collecting an
607/// element's text has to take all three, and trim only the whole.
608pub fn push_text(buf: &mut String, event: &Event) -> Result<bool, Error> {
609    match event {
610        Event::Text(t) => buf.push_str(t),
611        Event::CData(c) => buf.push_str(c),
612        Event::GeneralRef(r) => buf.push_str(&resolve_ref(r)?),
613        _ => return Ok(false),
614    }
615    Ok(true)
616}
617
618/// Read text content until the matching end tag.
619fn read_text_content(reader: &mut Reader<&[u8]>) -> Result<String, Error> {
620    let mut text = String::new();
621    loop {
622        match reader.read_event() {
623            Ok(Event::End(_)) => return Ok(text),
624            Ok(Event::Eof) => {
625                return Err(Error::Parse("unexpected EOF reading text".into()));
626            }
627            Ok(ev) => {
628                push_text(&mut text, &ev)?;
629            }
630            Err(e) => return Err(e.into()),
631        }
632    }
633}
634
635/// Skip events until we find an end tag matching the given name at depth 0.
636fn skip_to_end(reader: &mut Reader<&[u8]>, end_tag: &str) -> Result<(), Error> {
637    let mut depth: u32 = 0;
638    loop {
639        match reader.read_event() {
640            Ok(Event::Start(_)) => depth += 1,
641            Ok(Event::End(e)) => {
642                if depth == 0 && e.name().as_ref() == end_tag {
643                    return Ok(());
644                }
645                depth = depth.saturating_sub(1);
646            }
647            Ok(Event::Eof) => return Ok(()),
648            Err(e) => return Err(e.into()),
649            _ => {}
650        }
651    }
652}
653
654#[cfg(test)]
655mod tests {
656    use super::*;
657
658    #[test]
659    fn test_build_request_int() {
660        let xml = build_request("getBuild", &[Value::Int(42)]);
661        assert!(xml.contains("<methodName>getBuild</methodName>"));
662        assert!(xml.contains("<int>42</int>"));
663    }
664
665    #[test]
666    fn test_build_request_string_escaping() {
667        let xml = build_request("test", &[Value::String("a<b&c".into())]);
668        assert!(xml.contains("a&lt;b&amp;c"));
669    }
670
671    #[test]
672    fn test_parse_int_response() {
673        let xml = r#"<?xml version="1.0"?>
674            <methodResponse><params><param>
675            <value><int>42</int></value>
676            </param></params></methodResponse>"#;
677        let v = parse_response(xml).unwrap();
678        assert_eq!(v.as_int(), Some(42));
679    }
680
681    #[test]
682    fn test_parse_string_response() {
683        let xml = r#"<?xml version="1.0"?>
684            <methodResponse><params><param>
685            <value><string>hello world</string></value>
686            </param></params></methodResponse>"#;
687        let v = parse_response(xml).unwrap();
688        assert_eq!(v.as_str(), Some("hello world"));
689    }
690
691    #[test]
692    fn test_parse_struct_response() {
693        let xml = r#"<?xml version="1.0"?>
694            <methodResponse><params><param>
695            <value><struct>
696                <member><name>task_id</name><value><int>12345</int></value></member>
697                <member><name>nvr</name><value><string>foo-1.0-1.fc42</string></value></member>
698            </struct></value>
699            </param></params></methodResponse>"#;
700        let v = parse_response(xml).unwrap();
701        assert_eq!(v.get("task_id").unwrap().as_int(), Some(12345));
702        assert_eq!(v.get("nvr").unwrap().as_str(), Some("foo-1.0-1.fc42"));
703    }
704
705    #[test]
706    fn test_parse_array_response() {
707        let xml = r#"<?xml version="1.0"?>
708            <methodResponse><params><param>
709            <value><array><data>
710                <value><int>1</int></value>
711                <value><int>2</int></value>
712                <value><int>3</int></value>
713            </data></array></value>
714            </param></params></methodResponse>"#;
715        let v = parse_response(xml).unwrap();
716        let arr = v.as_array().unwrap();
717        assert_eq!(arr.len(), 3);
718        assert_eq!(arr[0].as_int(), Some(1));
719        assert_eq!(arr[2].as_int(), Some(3));
720    }
721
722    #[test]
723    fn test_parse_nested_struct_array() {
724        let xml = r#"<?xml version="1.0"?>
725            <methodResponse><params><param>
726            <value><array><data>
727                <value><struct>
728                    <member><name>id</name><value><int>100</int></value></member>
729                    <member><name>method</name><value><string>buildArch</string></value></member>
730                    <member><name>arch</name><value><string>x86_64</string></value></member>
731                </struct></value>
732                <value><struct>
733                    <member><name>id</name><value><int>101</int></value></member>
734                    <member><name>method</name><value><string>buildArch</string></value></member>
735                    <member><name>arch</name><value><string>aarch64</string></value></member>
736                </struct></value>
737            </data></array></value>
738            </param></params></methodResponse>"#;
739        let v = parse_response(xml).unwrap();
740        let arr = v.as_array().unwrap();
741        assert_eq!(arr.len(), 2);
742        assert_eq!(arr[0].get("id").unwrap().as_int(), Some(100));
743        assert_eq!(arr[0].get("arch").unwrap().as_str(), Some("x86_64"));
744        assert_eq!(arr[1].get("id").unwrap().as_int(), Some(101));
745    }
746
747    #[test]
748    fn test_parse_boolean_response() {
749        let xml = r#"<?xml version="1.0"?>
750            <methodResponse><params><param>
751            <value><boolean>1</boolean></value>
752            </param></params></methodResponse>"#;
753        let v = parse_response(xml).unwrap();
754        assert_eq!(v.as_int(), None);
755        match v {
756            Value::Boolean(b) => assert!(b),
757            _ => panic!("expected boolean"),
758        }
759    }
760
761    #[test]
762    fn test_parse_nil_response() {
763        let xml = r#"<?xml version="1.0"?>
764            <methodResponse><params><param>
765            <value><nil/></value>
766            </param></params></methodResponse>"#;
767        let v = parse_response(xml).unwrap();
768        assert!(matches!(v, Value::Nil));
769    }
770
771    #[test]
772    fn test_parse_fault_response() {
773        let xml = r#"<?xml version="1.0"?>
774            <methodResponse><fault><value><struct>
775                <member><name>faultCode</name><value><int>1000</int></value></member>
776                <member><name>faultString</name><value><string>No such build</string></value></member>
777            </struct></value></fault></methodResponse>"#;
778        let err = parse_response(xml).unwrap_err();
779        match err {
780            Error::Fault { code, message } => {
781                assert_eq!(code, 1000);
782                assert_eq!(message, "No such build");
783            }
784            _ => panic!("expected Fault error, got: {err}"),
785        }
786    }
787
788    /// Koji escapes `<`, `>` and `&` in every string, and quick-xml
789    /// reports each reference as an event of its own: a changelog
790    /// author came back as `Milan Crhamcrha@redhat.com- 4.0.7-1`,
791    /// references dropped and the spaces beside them trimmed away.
792    #[test]
793    fn a_string_keeps_its_escaped_characters_and_the_spaces_beside_them() {
794        let xml = r#"<?xml version="1.0"?>
795            <methodResponse><params><param>
796            <value><string>Milan Crha &lt;mcrha@redhat.com&gt; - 4.0.7-1</string></value>
797            </param></params></methodResponse>"#;
798        let v = parse_response(xml).unwrap();
799        assert_eq!(v.as_str(), Some("Milan Crha <mcrha@redhat.com> - 4.0.7-1"));
800
801        let xml = r#"<?xml version="1.0"?>
802            <methodResponse><params><param>
803            <value><string> a &amp; b &#233;&#x2014;&quot;c&apos; </string></value>
804            </param></params></methodResponse>"#;
805        let v = parse_response(xml).unwrap();
806        assert_eq!(v.as_str(), Some(" a & b é—\"c' "));
807
808        // Bare text is a string too, split at references the same way.
809        let xml = r#"<?xml version="1.0"?>
810            <methodResponse><params><param>
811            <value>x &lt; y</value>
812            </param></params></methodResponse>"#;
813        assert_eq!(parse_response(xml).unwrap().as_str(), Some("x < y"));
814
815        // Numbers and booleans read through surrounding whitespace.
816        let xml = r#"<?xml version="1.0"?>
817            <methodResponse><params><param>
818            <value><array><data>
819              <value><int> 42 </int></value>
820              <value><boolean> 1 </boolean></value>
821              <value><double> 2.5 </double></value>
822            </data></array></value>
823            </param></params></methodResponse>"#;
824        let v = parse_response(xml).unwrap();
825        let a = v.as_array().unwrap();
826        assert_eq!(a[0].as_int(), Some(42));
827        assert!(matches!(a[1], Value::Boolean(true)));
828        assert!(matches!(a[2], Value::Double(d) if d == 2.5));
829
830        // CDATA is text too; a member name and a base64 value are read
831        // through whitespace; an empty value's indentation is not text.
832        let xml = r#"<?xml version="1.0"?>
833            <methodResponse><params><param>
834            <value><struct>
835              <member><name>
836                a
837              </name><value><string>x<![CDATA[<b>]]>y</string></value></member>
838              <member><name>b</name><value><base64>
839                QUJD
840              </base64></value></member>
841              <member><name>c</name><value>
842              </value></member>
843            </struct></value>
844            </param></params></methodResponse>"#;
845        let v = parse_response(xml).unwrap();
846        assert_eq!(v.get("a").and_then(Value::as_str), Some("x<b>y"));
847        assert_eq!(v.get("b").and_then(Value::as_str), Some("QUJD"));
848        assert_eq!(v.get("c").and_then(Value::as_str), Some(""));
849
850        // An entity XML does not define is an error, not dropped text.
851        let xml = r#"<?xml version="1.0"?>
852            <methodResponse><params><param>
853            <value><string>&nbsp;</string></value>
854            </param></params></methodResponse>"#;
855        assert!(parse_response(xml).is_err());
856    }
857
858    #[test]
859    fn test_parse_bare_text_as_string() {
860        let xml = r#"<?xml version="1.0"?>
861            <methodResponse><params><param>
862            <value>bare text</value>
863            </param></params></methodResponse>"#;
864        let v = parse_response(xml).unwrap();
865        assert_eq!(v.as_str(), Some("bare text"));
866    }
867
868    #[test]
869    fn test_is_retriable_http_error() {
870        // reqwest errors are retriable (connection failures, etc.)
871        let err = Error::Xml("unexpected token".into());
872        assert!(err.is_retriable());
873    }
874
875    #[test]
876    fn test_is_retriable_parse_502() {
877        let err = Error::Parse("koji download-logs failed: 502 Bad Gateway".into());
878        assert!(err.is_retriable());
879    }
880
881    #[test]
882    fn test_is_retriable_parse_503() {
883        let err = Error::Parse("503 Service Unavailable".into());
884        assert!(err.is_retriable());
885    }
886
887    #[test]
888    fn test_is_not_retriable_fault() {
889        let err = Error::Fault {
890            code: 1000,
891            message: "No such build".into(),
892        };
893        assert!(!err.is_retriable());
894    }
895
896    #[test]
897    fn test_is_not_retriable_parse_not_found() {
898        let err = Error::Parse("root.log not found for task 123".into());
899        assert!(!err.is_retriable());
900    }
901}