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/// 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 ".../kojihub" — 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    pub fn call(&self, method: &str, params: &[Value]) -> Result<Value, Error> {
236        let body = build_request(method, params);
237        let resp = self
238            .http
239            .post(&self.hub_url)
240            .header("Content-Type", "text/xml")
241            .body(body)
242            .send()?
243            // Surface HTTP-level failures (proxy 502s and friends)
244            // as retriable Http errors instead of depending on
245            // whatever body shape the error page happens to have.
246            .error_for_status()?
247            .text()?;
248        parse_response(&resp)
249    }
250}
251
252// --- Request building ---
253
254fn build_request(method: &str, params: &[Value]) -> String {
255    let mut xml = format!(
256        "<?xml version=\"1.0\"?>\n\
257         <methodCall>\n\
258         <methodName>{method}</methodName>\n\
259         <params>\n"
260    );
261    for param in params {
262        xml.push_str("<param>");
263        write_value(&mut xml, param);
264        xml.push_str("</param>\n");
265    }
266    xml.push_str("</params>\n</methodCall>");
267    xml
268}
269
270fn write_value(xml: &mut String, value: &Value) {
271    xml.push_str("<value>");
272    match value {
273        Value::Int(i) => {
274            xml.push_str(&format!("<int>{i}</int>"));
275        }
276        Value::String(s) => {
277            xml.push_str("<string>");
278            xml.push_str(&quick_xml::escape::escape(s));
279            xml.push_str("</string>");
280        }
281        Value::Boolean(b) => {
282            xml.push_str(&format!("<boolean>{}</boolean>", if *b { 1 } else { 0 }));
283        }
284        Value::Double(d) => {
285            xml.push_str(&format!("<double>{d}</double>"));
286        }
287        Value::Array(items) => {
288            xml.push_str("<array><data>");
289            for item in items {
290                write_value(xml, item);
291            }
292            xml.push_str("</data></array>");
293        }
294        Value::Struct(map) => {
295            xml.push_str("<struct>");
296            for (key, val) in map {
297                xml.push_str(&format!("<member><name>{key}</name>"));
298                write_value(xml, val);
299                xml.push_str("</member>");
300            }
301            xml.push_str("</struct>");
302        }
303        Value::Nil => {
304            xml.push_str("<nil/>");
305        }
306    }
307    xml.push_str("</value>");
308}
309
310// --- Response parsing ---
311
312pub fn parse_response(xml: &str) -> Result<Value, Error> {
313    let mut reader = Reader::from_str(xml);
314    reader.config_mut().trim_text(true);
315
316    loop {
317        match reader.read_event() {
318            Ok(Event::Start(e)) => match e.name().as_ref() {
319                b"params" => return parse_params(&mut reader),
320                b"fault" => return parse_fault(&mut reader),
321                _ => {}
322            },
323            Ok(Event::Eof) => {
324                return Err(Error::Parse("unexpected EOF before params or fault".into()));
325            }
326            Err(e) => return Err(Error::Xml(e.to_string())),
327            _ => {}
328        }
329    }
330}
331
332fn parse_params(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
333    loop {
334        match reader.read_event() {
335            Ok(Event::Start(e)) if e.name().as_ref() == b"value" => {
336                return parse_value_content(reader);
337            }
338            Ok(Event::End(e)) if e.name().as_ref() == b"params" => {
339                return Ok(Value::Nil);
340            }
341            Ok(Event::Eof) => {
342                return Err(Error::Parse("unexpected EOF in params".into()));
343            }
344            Err(e) => return Err(e.into()),
345            _ => {}
346        }
347    }
348}
349
350fn parse_fault(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
351    loop {
352        match reader.read_event() {
353            Ok(Event::Start(e)) if e.name().as_ref() == b"value" => {
354                let value = parse_value_content(reader)?;
355                let code = value
356                    .get("faultCode")
357                    .and_then(|v| v.as_int())
358                    .unwrap_or(-1);
359                let message = value
360                    .get("faultString")
361                    .and_then(|v| v.as_str())
362                    .unwrap_or("unknown fault")
363                    .to_string();
364                return Err(Error::Fault { code, message });
365            }
366            Ok(Event::Eof) => {
367                return Err(Error::Parse("unexpected EOF in fault".into()));
368            }
369            Err(e) => return Err(e.into()),
370            _ => {}
371        }
372    }
373}
374
375/// Parse the content inside a `<value>` tag (opening `<value>` already consumed).
376fn parse_value_content(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
377    loop {
378        match reader.read_event() {
379            Ok(Event::Start(e)) => {
380                let tag = e.name().as_ref().to_vec();
381                match tag.as_slice() {
382                    b"int" | b"i4" | b"i8" => {
383                        let text = read_text_content(reader)?;
384                        skip_to_end(reader, b"value")?;
385                        return Ok(Value::Int(text.parse::<i64>().map_err(|e| {
386                            Error::Parse(format!("invalid int '{text}': {e}"))
387                        })?));
388                    }
389                    b"string" => {
390                        let text = read_text_content(reader)?;
391                        skip_to_end(reader, b"value")?;
392                        return Ok(Value::String(text));
393                    }
394                    b"boolean" => {
395                        let text = read_text_content(reader)?;
396                        skip_to_end(reader, b"value")?;
397                        return Ok(Value::Boolean(text == "1" || text == "true"));
398                    }
399                    b"double" => {
400                        let text = read_text_content(reader)?;
401                        skip_to_end(reader, b"value")?;
402                        return Ok(Value::Double(text.parse::<f64>().map_err(|e| {
403                            Error::Parse(format!("invalid double '{text}': {e}"))
404                        })?));
405                    }
406                    b"struct" => {
407                        let s = parse_struct_content(reader)?;
408                        skip_to_end(reader, b"value")?;
409                        return Ok(s);
410                    }
411                    b"array" => {
412                        let a = parse_array_content(reader)?;
413                        skip_to_end(reader, b"value")?;
414                        return Ok(a);
415                    }
416                    _ => {
417                        // Unknown type tag — treat content as string.
418                        let text = read_text_content(reader)?;
419                        skip_to_end(reader, b"value")?;
420                        return Ok(Value::String(text));
421                    }
422                }
423            }
424            Ok(Event::Empty(e)) if e.name().as_ref() == b"nil" => {
425                skip_to_end(reader, b"value")?;
426                return Ok(Value::Nil);
427            }
428            Ok(Event::Text(t)) => {
429                let text = decode_text(&t)?;
430                if !text.trim().is_empty() {
431                    // Bare text in <value> is implicitly a string.
432                    skip_to_end(reader, b"value")?;
433                    return Ok(Value::String(text));
434                }
435            }
436            Ok(Event::End(e)) if e.name().as_ref() == b"value" => {
437                return Ok(Value::String(String::new()));
438            }
439            Ok(Event::Eof) => {
440                return Err(Error::Parse("unexpected EOF in value".into()));
441            }
442            Err(e) => return Err(e.into()),
443            _ => {}
444        }
445    }
446}
447
448fn parse_struct_content(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
449    let mut map = HashMap::new();
450    loop {
451        match reader.read_event() {
452            Ok(Event::Start(e)) if e.name().as_ref() == b"member" => {
453                let (name, value) = parse_member(reader)?;
454                map.insert(name, value);
455            }
456            Ok(Event::End(e)) if e.name().as_ref() == b"struct" => {
457                return Ok(Value::Struct(map));
458            }
459            Ok(Event::Eof) => {
460                return Err(Error::Parse("unexpected EOF in struct".into()));
461            }
462            Err(e) => return Err(e.into()),
463            _ => {}
464        }
465    }
466}
467
468fn parse_member(reader: &mut Reader<&[u8]>) -> Result<(String, Value), Error> {
469    let mut name = String::new();
470    let mut value = Value::Nil;
471    loop {
472        match reader.read_event() {
473            Ok(Event::Start(e)) => match e.name().as_ref() {
474                b"name" => {
475                    name = read_text_content(reader)?;
476                }
477                b"value" => {
478                    value = parse_value_content(reader)?;
479                }
480                _ => {}
481            },
482            Ok(Event::End(e)) if e.name().as_ref() == b"member" => {
483                return Ok((name, value));
484            }
485            Ok(Event::Eof) => {
486                return Err(Error::Parse("unexpected EOF in member".into()));
487            }
488            Err(e) => return Err(e.into()),
489            _ => {}
490        }
491    }
492}
493
494fn parse_array_content(reader: &mut Reader<&[u8]>) -> Result<Value, Error> {
495    let mut items = Vec::new();
496    loop {
497        match reader.read_event() {
498            Ok(Event::Start(e)) => {
499                if e.name().as_ref() == b"data" {
500                    loop {
501                        match reader.read_event() {
502                            Ok(Event::Start(e2)) if e2.name().as_ref() == b"value" => {
503                                items.push(parse_value_content(reader)?);
504                            }
505                            Ok(Event::End(e2)) if e2.name().as_ref() == b"data" => break,
506                            Ok(Event::Eof) => {
507                                return Err(Error::Parse("unexpected EOF in array data".into()));
508                            }
509                            Err(e) => return Err(e.into()),
510                            _ => {}
511                        }
512                    }
513                }
514            }
515            Ok(Event::End(e)) if e.name().as_ref() == b"array" => {
516                return Ok(Value::Array(items));
517            }
518            Ok(Event::Eof) => {
519                return Err(Error::Parse("unexpected EOF in array".into()));
520            }
521            Err(e) => return Err(e.into()),
522            _ => {}
523        }
524    }
525}
526
527/// Read text content until the matching end tag.
528/// Decode and unescape a quick-xml text node to an owned String.
529///
530/// quick-xml 0.40 dropped `BytesText::unescape`; decoding and
531/// entity-unescaping are now separate explicit steps.
532fn decode_text(t: &BytesText) -> Result<String, Error> {
533    let decoded = t.decode().map_err(|e| Error::Xml(e.to_string()))?;
534    Ok(quick_xml::escape::unescape(&decoded)
535        .map_err(|e| Error::Xml(e.to_string()))?
536        .into_owned())
537}
538
539fn read_text_content(reader: &mut Reader<&[u8]>) -> Result<String, Error> {
540    let mut text = String::new();
541    loop {
542        match reader.read_event() {
543            Ok(Event::Text(t)) => {
544                text.push_str(&decode_text(&t)?);
545            }
546            Ok(Event::End(_)) => return Ok(text),
547            Ok(Event::Eof) => {
548                return Err(Error::Parse("unexpected EOF reading text".into()));
549            }
550            Err(e) => return Err(e.into()),
551            _ => {}
552        }
553    }
554}
555
556/// Skip events until we find an end tag matching the given name at depth 0.
557fn skip_to_end(reader: &mut Reader<&[u8]>, end_tag: &[u8]) -> Result<(), Error> {
558    let mut depth: u32 = 0;
559    loop {
560        match reader.read_event() {
561            Ok(Event::Start(_)) => depth += 1,
562            Ok(Event::End(e)) => {
563                if depth == 0 && e.name().as_ref() == end_tag {
564                    return Ok(());
565                }
566                depth = depth.saturating_sub(1);
567            }
568            Ok(Event::Eof) => return Ok(()),
569            Err(e) => return Err(e.into()),
570            _ => {}
571        }
572    }
573}
574
575#[cfg(test)]
576mod tests {
577    use super::*;
578
579    #[test]
580    fn test_build_request_int() {
581        let xml = build_request("getBuild", &[Value::Int(42)]);
582        assert!(xml.contains("<methodName>getBuild</methodName>"));
583        assert!(xml.contains("<int>42</int>"));
584    }
585
586    #[test]
587    fn test_build_request_string_escaping() {
588        let xml = build_request("test", &[Value::String("a<b&c".into())]);
589        assert!(xml.contains("a&lt;b&amp;c"));
590    }
591
592    #[test]
593    fn test_parse_int_response() {
594        let xml = r#"<?xml version="1.0"?>
595            <methodResponse><params><param>
596            <value><int>42</int></value>
597            </param></params></methodResponse>"#;
598        let v = parse_response(xml).unwrap();
599        assert_eq!(v.as_int(), Some(42));
600    }
601
602    #[test]
603    fn test_parse_string_response() {
604        let xml = r#"<?xml version="1.0"?>
605            <methodResponse><params><param>
606            <value><string>hello world</string></value>
607            </param></params></methodResponse>"#;
608        let v = parse_response(xml).unwrap();
609        assert_eq!(v.as_str(), Some("hello world"));
610    }
611
612    #[test]
613    fn test_parse_struct_response() {
614        let xml = r#"<?xml version="1.0"?>
615            <methodResponse><params><param>
616            <value><struct>
617                <member><name>task_id</name><value><int>12345</int></value></member>
618                <member><name>nvr</name><value><string>foo-1.0-1.fc42</string></value></member>
619            </struct></value>
620            </param></params></methodResponse>"#;
621        let v = parse_response(xml).unwrap();
622        assert_eq!(v.get("task_id").unwrap().as_int(), Some(12345));
623        assert_eq!(v.get("nvr").unwrap().as_str(), Some("foo-1.0-1.fc42"));
624    }
625
626    #[test]
627    fn test_parse_array_response() {
628        let xml = r#"<?xml version="1.0"?>
629            <methodResponse><params><param>
630            <value><array><data>
631                <value><int>1</int></value>
632                <value><int>2</int></value>
633                <value><int>3</int></value>
634            </data></array></value>
635            </param></params></methodResponse>"#;
636        let v = parse_response(xml).unwrap();
637        let arr = v.as_array().unwrap();
638        assert_eq!(arr.len(), 3);
639        assert_eq!(arr[0].as_int(), Some(1));
640        assert_eq!(arr[2].as_int(), Some(3));
641    }
642
643    #[test]
644    fn test_parse_nested_struct_array() {
645        let xml = r#"<?xml version="1.0"?>
646            <methodResponse><params><param>
647            <value><array><data>
648                <value><struct>
649                    <member><name>id</name><value><int>100</int></value></member>
650                    <member><name>method</name><value><string>buildArch</string></value></member>
651                    <member><name>arch</name><value><string>x86_64</string></value></member>
652                </struct></value>
653                <value><struct>
654                    <member><name>id</name><value><int>101</int></value></member>
655                    <member><name>method</name><value><string>buildArch</string></value></member>
656                    <member><name>arch</name><value><string>aarch64</string></value></member>
657                </struct></value>
658            </data></array></value>
659            </param></params></methodResponse>"#;
660        let v = parse_response(xml).unwrap();
661        let arr = v.as_array().unwrap();
662        assert_eq!(arr.len(), 2);
663        assert_eq!(arr[0].get("id").unwrap().as_int(), Some(100));
664        assert_eq!(arr[0].get("arch").unwrap().as_str(), Some("x86_64"));
665        assert_eq!(arr[1].get("id").unwrap().as_int(), Some(101));
666    }
667
668    #[test]
669    fn test_parse_boolean_response() {
670        let xml = r#"<?xml version="1.0"?>
671            <methodResponse><params><param>
672            <value><boolean>1</boolean></value>
673            </param></params></methodResponse>"#;
674        let v = parse_response(xml).unwrap();
675        assert_eq!(v.as_int(), None);
676        match v {
677            Value::Boolean(b) => assert!(b),
678            _ => panic!("expected boolean"),
679        }
680    }
681
682    #[test]
683    fn test_parse_nil_response() {
684        let xml = r#"<?xml version="1.0"?>
685            <methodResponse><params><param>
686            <value><nil/></value>
687            </param></params></methodResponse>"#;
688        let v = parse_response(xml).unwrap();
689        assert!(matches!(v, Value::Nil));
690    }
691
692    #[test]
693    fn test_parse_fault_response() {
694        let xml = r#"<?xml version="1.0"?>
695            <methodResponse><fault><value><struct>
696                <member><name>faultCode</name><value><int>1000</int></value></member>
697                <member><name>faultString</name><value><string>No such build</string></value></member>
698            </struct></value></fault></methodResponse>"#;
699        let err = parse_response(xml).unwrap_err();
700        match err {
701            Error::Fault { code, message } => {
702                assert_eq!(code, 1000);
703                assert_eq!(message, "No such build");
704            }
705            _ => panic!("expected Fault error, got: {err}"),
706        }
707    }
708
709    #[test]
710    fn test_parse_bare_text_as_string() {
711        let xml = r#"<?xml version="1.0"?>
712            <methodResponse><params><param>
713            <value>bare text</value>
714            </param></params></methodResponse>"#;
715        let v = parse_response(xml).unwrap();
716        assert_eq!(v.as_str(), Some("bare text"));
717    }
718
719    #[test]
720    fn test_is_retriable_http_error() {
721        // reqwest errors are retriable (connection failures, etc.)
722        let err = Error::Xml("unexpected token".into());
723        assert!(err.is_retriable());
724    }
725
726    #[test]
727    fn test_is_retriable_parse_502() {
728        let err = Error::Parse("koji download-logs failed: 502 Bad Gateway".into());
729        assert!(err.is_retriable());
730    }
731
732    #[test]
733    fn test_is_retriable_parse_503() {
734        let err = Error::Parse("503 Service Unavailable".into());
735        assert!(err.is_retriable());
736    }
737
738    #[test]
739    fn test_is_not_retriable_fault() {
740        let err = Error::Fault {
741            code: 1000,
742            message: "No such build".into(),
743        };
744        assert!(!err.is_retriable());
745    }
746
747    #[test]
748    fn test_is_not_retriable_parse_not_found() {
749        let err = Error::Parse("root.log not found for task 123".into());
750        assert!(!err.is_retriable());
751    }
752}