Skip to main content

pipeflow/source/
http_client.rs

1//! HTTP client source for polling APIs
2//!
3//! Periodically fetches data from an HTTP endpoint and emits it as messages.
4
5use std::collections::HashMap;
6use std::net::IpAddr;
7use std::str::FromStr;
8use std::sync::Arc;
9use std::time::Duration;
10
11use async_trait::async_trait;
12use chrono::Local;
13use cron::Schedule;
14use reqwest::Client;
15use reqwest::Url;
16use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
17use tokio::sync::broadcast;
18
19use crate::common::http::AuthConfig;
20use crate::common::message::{Message, SharedMessage};
21use crate::error::{Error, Result};
22use crate::source::{MessageSender, Source};
23use crate::transform::json_path::CompiledPath;
24
25/// Response body validation configuration
26///
27/// Supports JSONPath-based value checks and keyword search.
28/// At least one validation method must be specified.
29#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
30pub struct ExpectBodyConfig {
31    /// JSONPath to extract value for comparison
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub path: Option<String>,
34    /// Expected value (requires `path`). Use `null` to check for null/missing values.
35    #[serde(
36        default,
37        skip_serializing_if = "Option::is_none",
38        deserialize_with = "deserialize_explicit_null"
39    )]
40    pub eq: Option<serde_json::Value>,
41    /// Value that must NOT match (requires `path`). Use `null` to check for non-null values.
42    #[serde(
43        default,
44        skip_serializing_if = "Option::is_none",
45        deserialize_with = "deserialize_explicit_null"
46    )]
47    pub ne: Option<serde_json::Value>,
48    /// Keyword that must exist in response body
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub contains: Option<String>,
51    /// Keyword that must NOT exist in response body
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub not_contains: Option<String>,
54}
55
56/// Custom deserializer that treats explicit `null` as `Some(Value::Null)` instead of `None`.
57/// This allows distinguishing between "field absent" and "field set to null".
58fn deserialize_explicit_null<'de, D>(
59    deserializer: D,
60) -> std::result::Result<Option<serde_json::Value>, D::Error>
61where
62    D: serde::Deserializer<'de>,
63{
64    use serde::de::Deserialize;
65    // Deserialize as Value first, which will capture null as Value::Null
66    let value = serde_json::Value::deserialize(deserializer)?;
67    // Wrap it in Some, so explicit null becomes Some(Null)
68    Ok(Some(value))
69}
70
71impl ExpectBodyConfig {
72    fn validate(&self) -> Result<()> {
73        let has_path = self.path.is_some();
74        let has_eq_ne = self.eq.is_some() || self.ne.is_some();
75        let has_keyword = self.contains.is_some() || self.not_contains.is_some();
76
77        if !has_path && has_eq_ne {
78            return Err(Error::config(
79                "http_client expect_body requires 'path' when 'eq' or 'ne' is specified",
80            ));
81        }
82
83        if !has_path && !has_keyword {
84            return Err(Error::config(
85                "http_client expect_body requires at least 'path', 'contains', or 'not_contains'",
86            ));
87        }
88
89        if has_path && !has_eq_ne {
90            return Err(Error::config(
91                "http_client expect_body requires 'eq' or 'ne' when 'path' is specified",
92            ));
93        }
94
95        Ok(())
96    }
97}
98
99/// Compiled expect_body for runtime validation
100#[derive(Debug)]
101struct CompiledExpectBody {
102    path: Option<CompiledPath>,
103    eq: Option<serde_json::Value>,
104    ne: Option<serde_json::Value>,
105    contains: Option<String>,
106    not_contains: Option<String>,
107}
108
109impl CompiledExpectBody {
110    fn compile(config: &ExpectBodyConfig) -> Result<Self> {
111        config.validate()?;
112        let path = config
113            .path
114            .as_deref()
115            .map(CompiledPath::compile)
116            .transpose()?;
117        Ok(Self {
118            path,
119            eq: config.eq.clone(),
120            ne: config.ne.clone(),
121            contains: config.contains.clone(),
122            not_contains: config.not_contains.clone(),
123        })
124    }
125
126    fn validate(&self, body_text: &str, payload: &serde_json::Value) -> Result<()> {
127        // Keyword validation
128        if let Some(ref kw) = self.contains
129            && !body_text.contains(kw)
130        {
131            return Err(Error::source(format!(
132                "Response body does not contain expected keyword: {}",
133                kw
134            )));
135        }
136        if let Some(ref kw) = self.not_contains
137            && body_text.contains(kw)
138        {
139            return Err(Error::source(format!(
140                "Response body contains unexpected keyword: {}",
141                kw
142            )));
143        }
144
145        // JSONPath validation
146        if let Some(ref path) = self.path {
147            let actual = path
148                .extract(payload)
149                .cloned()
150                .unwrap_or(serde_json::Value::Null);
151
152            if let Some(ref expected) = self.eq
153                && &actual != expected
154            {
155                return Err(Error::source(format!(
156                    "Response body validation failed: {} expected {:?}, got {:?}",
157                    path, expected, actual
158                )));
159            }
160            if let Some(ref not_expected) = self.ne
161                && &actual == not_expected
162            {
163                return Err(Error::source(format!(
164                    "Response body validation failed: {} should not equal {:?}",
165                    path, not_expected
166                )));
167            }
168        }
169
170        Ok(())
171    }
172}
173
174/// Configuration for the HTTP client source
175#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
176pub struct HttpClientConfig {
177    /// Target URL to poll
178    pub url: String,
179    /// Polling interval (e.g., "30s", "5m", "1h")
180    #[serde(default = "default_interval", with = "humantime_serde")]
181    pub interval: Duration,
182    /// Cron schedule for timed runs (e.g., "0 0 * * *" for daily midnight)
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub schedule: Option<String>,
185    /// HTTP method (GET, POST, etc.)
186    #[serde(default = "default_method")]
187    pub method: String,
188    /// Optional request headers
189    #[serde(default)]
190    pub headers: HashMap<String, String>,
191    /// Max error response body length to include in errors
192    #[serde(default = "default_error_body_limit")]
193    pub error_body_limit: usize,
194    /// Optional authentication configuration
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub auth: Option<AuthConfig>,
197    /// Expected success status codes (default: accept all 2xx)
198    /// Example: [200, 201] to only accept those specific codes
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub expect_status: Option<Vec<u16>>,
201    /// Response body validation via JSONPath or keyword search
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub expect_body: Option<ExpectBodyConfig>,
204}
205
206fn default_interval() -> Duration {
207    Duration::from_secs(60)
208}
209
210fn default_method() -> String {
211    "GET".to_string()
212}
213
214fn default_error_body_limit() -> usize {
215    2048
216}
217
218impl Default for HttpClientConfig {
219    fn default() -> Self {
220        Self {
221            url: String::new(),
222            interval: Duration::from_secs(60),
223            schedule: None,
224            method: "GET".to_string(),
225            headers: HashMap::new(),
226            error_body_limit: default_error_body_limit(),
227            auth: None,
228            expect_status: None,
229            expect_body: None,
230        }
231    }
232}
233
234impl HttpClientConfig {
235    fn validate_and_normalize(&mut self) -> Result<Url> {
236        if self.url.is_empty() {
237            return Err(Error::config("http_client source requires 'url' in config"));
238        }
239
240        if self.interval.is_zero() {
241            return Err(Error::config(
242                "http_client source requires 'interval' to be > 0",
243            ));
244        }
245
246        self.method = self.method.trim().to_uppercase();
247        if self.method.is_empty() {
248            return Err(Error::config(
249                "http_client source requires non-empty 'method'",
250            ));
251        }
252
253        const SUPPORTED_METHODS: &[&str] = &["GET", "POST", "PUT", "DELETE"];
254        if !SUPPORTED_METHODS.contains(&self.method.as_str()) {
255            return Err(Error::config(format!(
256                "http_client source has unsupported 'method': {}",
257                self.method
258            )));
259        }
260
261        if self.error_body_limit == 0 {
262            return Err(Error::config(
263                "http_client source requires 'error_body_limit' to be > 0",
264            ));
265        }
266
267        // Validate expect_status codes are in valid range
268        if let Some(ref codes) = self.expect_status {
269            if codes.is_empty() {
270                return Err(Error::config(
271                    "http_client expect_status must not be empty if specified",
272                ));
273            }
274            for code in codes {
275                if !(100..=599).contains(code) {
276                    return Err(Error::config(format!(
277                        "http_client expect_status has invalid HTTP status code: {}",
278                        code
279                    )));
280                }
281            }
282        }
283
284        Url::parse(&self.url)
285            .map_err(|e| Error::config(format!("http_client source has invalid 'url': {}", e)))
286    }
287
288    fn parse_schedule(&self) -> Result<Option<Schedule>> {
289        let Some(ref schedule) = self.schedule else {
290            return Ok(None);
291        };
292        let normalized = normalize_schedule(schedule);
293        Schedule::from_str(&normalized)
294            .map(Some)
295            .map_err(|e| Error::config(format!("http_client source has invalid 'schedule': {}", e)))
296    }
297
298    fn build_headers(&self) -> Result<HeaderMap> {
299        let mut headers = HeaderMap::new();
300
301        // Default Accept: application/json (can be overridden by user headers)
302        let has_accept = self
303            .headers
304            .keys()
305            .any(|k| k.eq_ignore_ascii_case("accept"));
306        if !has_accept {
307            headers.insert(
308                reqwest::header::ACCEPT,
309                HeaderValue::from_static("application/json"),
310            );
311        }
312
313        for (key, value) in &self.headers {
314            let name = HeaderName::from_bytes(key.as_bytes()).map_err(|e| {
315                Error::config(format!(
316                    "http_client source has invalid header name '{}': {}",
317                    key, e
318                ))
319            })?;
320            let val = HeaderValue::from_str(value).map_err(|e| {
321                // Intentionally do not include the header value to avoid leaking secrets.
322                Error::config(format!(
323                    "http_client source has invalid header value for '{}': {}",
324                    key, e
325                ))
326            })?;
327            headers.insert(name, val);
328        }
329
330        // Apply authentication if configured
331        if let Some(ref auth) = self.auth {
332            auth.apply_to_headers(&mut headers)?;
333        }
334
335        Ok(headers)
336    }
337}
338
339fn normalize_schedule(schedule: &str) -> String {
340    if schedule.split_whitespace().count() == 5 {
341        format!("0 {}", schedule)
342    } else {
343        schedule.to_string()
344    }
345}
346
347/// HTTP client source that polls an API endpoint
348#[derive(Debug)]
349pub struct HttpClientSource {
350    id: String,
351    config: HttpClientConfig,
352    client: Client,
353    headers: HeaderMap,
354    schedule: Option<Schedule>,
355    expect_status: Option<Vec<u16>>,
356    expect_body: Option<CompiledExpectBody>,
357}
358
359/// Check if a host refers to loopback (localhost or 127.0.0.1/::1).
360fn is_loopback_host(host: &str) -> bool {
361    host.eq_ignore_ascii_case("localhost")
362        || host.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback())
363}
364
365impl HttpClientSource {
366    /// Create a new HTTP client source
367    pub fn new(id: impl Into<String>, config: HttpClientConfig) -> Result<Self> {
368        let mut config = config;
369        let parsed_url = config.validate_and_normalize()?;
370        let headers = config.build_headers()?;
371        let schedule = config.parse_schedule()?;
372
373        // NOTE: reqwest honors HTTP(S)_PROXY env vars by default. In some developer/CI
374        // environments, that can accidentally route loopback (127.0.0.1/localhost)
375        // requests through a proxy and break local integration tests.
376        //
377        // We only bypass proxies for loopback destinations; non-loopback URLs keep
378        // default proxy behavior.
379        let bypass_proxy = parsed_url.host_str().is_some_and(is_loopback_host);
380
381        let mut builder = Client::builder().timeout(Duration::from_secs(30));
382        if cfg!(test) || bypass_proxy {
383            builder = builder.no_proxy();
384        }
385
386        let client = builder
387            .build()
388            .map_err(|e| Error::source(format!("Failed to create HTTP client: {}", e)))?;
389
390        // Compile expect_body if configured
391        let expect_body = config
392            .expect_body
393            .as_ref()
394            .map(CompiledExpectBody::compile)
395            .transpose()?;
396
397        Ok(Self {
398            id: id.into(),
399            expect_status: config.expect_status.clone(),
400            expect_body,
401            config,
402            client,
403            headers,
404            schedule,
405        })
406    }
407
408    /// Execute an HTTP request and return the response as JSON
409    async fn fetch(&self) -> Result<serde_json::Value> {
410        fn truncate_for_error(s: &str, max_chars: usize) -> String {
411            match s.char_indices().nth(max_chars) {
412                Some((idx, _)) => format!("{}...(truncated)", &s[..idx]),
413                None => s.to_string(),
414            }
415        }
416
417        tracing::debug!(
418            source_id = %self.id,
419            method = %self.config.method,
420            url = %self.config.url,
421            "Sending HTTP request"
422        );
423
424        let mut request = match self.config.method.as_str() {
425            "GET" => self.client.get(&self.config.url),
426            "POST" => self.client.post(&self.config.url),
427            "PUT" => self.client.put(&self.config.url),
428            "DELETE" => self.client.delete(&self.config.url),
429            other => unreachable!(
430                "Method '{}' should have been validated at construction",
431                other
432            ),
433        };
434
435        if !self.headers.is_empty() {
436            request = request.headers(self.headers.clone());
437        }
438
439        let response = request.send().await.map_err(|e| {
440            tracing::debug!(
441                source_id = %self.id,
442                method = %self.config.method,
443                url = %self.config.url,
444                error = %e,
445                result = "failed",
446                "HTTP request failed to send"
447            );
448            Error::source(format!("HTTP request to {} failed: {}", self.config.url, e))
449        })?;
450
451        let status = response.status();
452
453        // Status code validation
454        let is_status_ok = match &self.expect_status {
455            Some(codes) => codes.contains(&status.as_u16()),
456            None => status.is_success(),
457        };
458
459        // Get body as text (needed for keyword validation and error messages)
460        let body_text = response
461            .text()
462            .await
463            .unwrap_or_else(|e| format!("<failed to read response body: {}>", e));
464
465        if !is_status_ok {
466            let body = truncate_for_error(&body_text, self.config.error_body_limit);
467
468            tracing::debug!(
469                source_id = %self.id,
470                method = %self.config.method,
471                url = %self.config.url,
472                status = %status,
473                result = "failed",
474                "HTTP request returned unexpected status"
475            );
476
477            return Err(Error::source(format!(
478                "HTTP request to {} returned status {}: {}",
479                self.config.url, status, body
480            )));
481        }
482
483        tracing::debug!(
484            source_id = %self.id,
485            method = %self.config.method,
486            url = %self.config.url,
487            status = %status,
488            result = "success",
489            "HTTP request succeeded"
490        );
491
492        // Parse JSON
493        let payload: serde_json::Value = serde_json::from_str(&body_text).map_err(|e| {
494            tracing::debug!(
495                source_id = %self.id,
496                url = %self.config.url,
497                error = %e,
498                "Failed to parse response as JSON"
499            );
500            Error::source(format!(
501                "Failed to parse response from {} as JSON: {}",
502                self.config.url, e
503            ))
504        })?;
505
506        // Body validation
507        if let Some(ref expect) = self.expect_body {
508            expect.validate(&body_text, &payload)?;
509        }
510
511        Ok(payload)
512    }
513
514    /// Fetch data and send it downstream. Returns `false` if the channel is closed.
515    async fn fetch_and_send(&self, sender: &MessageSender) -> bool {
516        match self.fetch().await {
517            Ok(payload) => {
518                let message: SharedMessage = Arc::new(
519                    Message::new(&self.id, payload)
520                        .with_tag(
521                            "interval",
522                            if self.schedule.is_some() {
523                                "".to_string()
524                            } else {
525                                humantime::format_duration(self.config.interval).to_string()
526                            },
527                        )
528                        .with_tag(
529                            "schedule",
530                            self.schedule
531                                .as_ref()
532                                .map(|s| s.to_string())
533                                .unwrap_or_default(),
534                        ),
535                );
536                if sender.send(message).is_err() {
537                    // `broadcast::Sender::send` fails when there are no active receivers.
538                    // In this engine, that typically means the pipeline has no sinks wired
539                    // (or all sinks have exited), so the safe default is to stop the source
540                    // to avoid useless polling.
541                    tracing::debug!(source_id = %self.id, "No active subscribers, stopping source");
542                    return false;
543                }
544                tracing::debug!(source_id = %self.id, "Fetched and sent message");
545            }
546            Err(e) => {
547                tracing::warn!(
548                    source_id = %self.id,
549                    error = %e,
550                    "HTTP fetch failed, will retry on next interval"
551                );
552            }
553        }
554        true
555    }
556}
557
558#[async_trait]
559impl Source for HttpClientSource {
560    fn id(&self) -> &str {
561        &self.id
562    }
563
564    async fn run(
565        &self,
566        sender: MessageSender,
567        mut shutdown: broadcast::Receiver<()>,
568    ) -> Result<()> {
569        // Warn if both schedule and interval are configured
570        if self.schedule.is_some() {
571            tracing::info!(
572                source_id = %self.id,
573                url = %self.config.url,
574                schedule = ?self.config.schedule,
575                "HTTP client source started with schedule"
576            );
577
578            // interval is always present (has default), so we only warn if user explicitly
579            // set a non-default interval alongside schedule
580            if self.config.interval != Duration::from_secs(60) {
581                tracing::warn!(
582                    source_id = %self.id,
583                    interval = ?self.config.interval,
584                    "Both 'schedule' and 'interval' configured; 'interval' will be ignored, using 'schedule'"
585                );
586            }
587        } else {
588            tracing::info!(
589                source_id = %self.id,
590                url = %self.config.url,
591                interval = ?self.config.interval,
592                "HTTP client source started with interval"
593            );
594        }
595
596        if let Some(ref schedule) = self.schedule {
597            loop {
598                let now = Local::now();
599                let next = schedule.upcoming(Local).next().ok_or_else(|| {
600                    Error::source("HTTP client schedule produced no future dates")
601                })?;
602                let delay = (next - now).to_std().map_err(|e| {
603                    Error::source(format!("HTTP client schedule delay error: {}", e))
604                })?;
605
606                tracing::debug!(
607                    source_id = %self.id,
608                    next_run = %next,
609                    delay = ?delay,
610                    "HTTP client source scheduled run"
611                );
612
613                tokio::select! {
614                    biased;
615
616                    _ = shutdown.recv() => {
617                        tracing::info!(source_id = %self.id, "HTTP client source shutting down");
618                        break;
619                    }
620
621                    _ = tokio::time::sleep(delay) => {
622                        if !self.fetch_and_send(&sender).await {
623                            break;
624                        }
625                    }
626                }
627            }
628
629            return Ok(());
630        }
631
632        // Perform immediate first fetch before entering the interval loop
633        if !self.fetch_and_send(&sender).await {
634            return Ok(());
635        }
636
637        // Set up interval for subsequent fetches
638        let mut interval = tokio::time::interval(self.config.interval);
639        interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
640        // Skip the first tick since we already did an immediate fetch
641        interval.tick().await;
642
643        loop {
644            tokio::select! {
645                biased;
646
647                _ = shutdown.recv() => {
648                    tracing::info!(source_id = %self.id, "HTTP client source shutting down");
649                    break;
650                }
651
652                _ = interval.tick() => {
653                    if !self.fetch_and_send(&sender).await {
654                        break;
655                    }
656                }
657            }
658        }
659
660        Ok(())
661    }
662}
663
664#[cfg(test)]
665mod tests {
666    use super::*;
667    use futures::FutureExt;
668    use wiremock::matchers::{method, path};
669    use wiremock::{Mock, MockServer, ResponseTemplate};
670
671    async fn start_mock_server() -> Option<MockServer> {
672        let result = std::panic::AssertUnwindSafe(MockServer::start())
673            .catch_unwind()
674            .await;
675        match result {
676            Ok(server) => Some(server),
677            Err(_) => {
678                eprintln!("Skipping HTTP client test: mock server failed to bind");
679                None
680            }
681        }
682    }
683
684    #[test]
685    fn test_config_default() {
686        let cfg = HttpClientConfig::default();
687        assert_eq!(cfg.interval, Duration::from_secs(60));
688        assert!(cfg.schedule.is_none());
689        assert_eq!(cfg.method, "GET");
690        assert!(cfg.headers.is_empty());
691        assert_eq!(cfg.error_body_limit, 2048);
692    }
693
694    #[test]
695    fn test_new_requires_url() {
696        let cfg = HttpClientConfig::default();
697        let result = HttpClientSource::new("test", cfg);
698        assert!(result.is_err());
699        assert!(result.unwrap_err().to_string().contains("url"));
700    }
701
702    #[test]
703    fn test_new_with_valid_url() {
704        let cfg = HttpClientConfig {
705            url: "https://example.com".to_string(),
706            ..Default::default()
707        };
708        let result = HttpClientSource::new("test", cfg);
709        assert!(result.is_ok());
710    }
711
712    #[test]
713    fn test_new_normalizes_method() {
714        let cfg = HttpClientConfig {
715            url: "https://example.com".to_string(),
716            method: "post".to_string(),
717            ..Default::default()
718        };
719        let source = HttpClientSource::new("test", cfg).unwrap();
720        assert_eq!(source.config.method, "POST");
721    }
722
723    #[test]
724    fn test_new_rejects_interval_zero() {
725        let cfg = HttpClientConfig {
726            url: "https://example.com".to_string(),
727            interval: Duration::ZERO,
728            ..Default::default()
729        };
730        let result = HttpClientSource::new("test", cfg);
731        assert!(result.is_err());
732        assert!(result.unwrap_err().to_string().contains("interval"));
733    }
734
735    #[test]
736    fn test_new_rejects_invalid_url() {
737        let cfg = HttpClientConfig {
738            url: "http://".to_string(),
739            ..Default::default()
740        };
741        let result = HttpClientSource::new("test", cfg);
742        assert!(result.is_err());
743        assert!(result.unwrap_err().to_string().contains("invalid"));
744    }
745
746    #[test]
747    fn test_new_rejects_invalid_schedule() {
748        let cfg = HttpClientConfig {
749            url: "https://example.com".to_string(),
750            schedule: Some("not-a-cron".to_string()),
751            ..Default::default()
752        };
753        let result = HttpClientSource::new("test", cfg);
754        assert!(result.is_err());
755        assert!(result.unwrap_err().to_string().contains("schedule"));
756    }
757
758    #[test]
759    fn test_new_accepts_schedule() {
760        let cfg = HttpClientConfig {
761            url: "https://example.com".to_string(),
762            schedule: Some("0 0 * * *".to_string()),
763            ..Default::default()
764        };
765        let result = HttpClientSource::new("test", cfg);
766        assert!(result.is_ok());
767    }
768
769    #[test]
770    fn test_new_rejects_unsupported_method() {
771        let cfg = HttpClientConfig {
772            url: "https://example.com".to_string(),
773            method: "PATCH".to_string(),
774            ..Default::default()
775        };
776        let result = HttpClientSource::new("test", cfg);
777        assert!(result.is_err());
778        assert!(result.unwrap_err().to_string().contains("unsupported"));
779    }
780
781    #[test]
782    fn test_new_rejects_empty_method() {
783        let cfg = HttpClientConfig {
784            url: "https://example.com".to_string(),
785            method: "".to_string(),
786            ..Default::default()
787        };
788        let result = HttpClientSource::new("test", cfg);
789        assert!(result.is_err());
790        assert!(result.unwrap_err().to_string().contains("non-empty"));
791    }
792
793    #[test]
794    fn test_new_rejects_whitespace_method() {
795        let cfg = HttpClientConfig {
796            url: "https://example.com".to_string(),
797            method: "   ".to_string(),
798            ..Default::default()
799        };
800        let result = HttpClientSource::new("test", cfg);
801        assert!(result.is_err());
802        assert!(result.unwrap_err().to_string().contains("non-empty"));
803    }
804
805    #[test]
806    fn test_new_rejects_invalid_header_name() {
807        let mut headers = HashMap::new();
808        headers.insert("Bad Header".to_string(), "x".to_string());
809        let cfg = HttpClientConfig {
810            url: "https://example.com".to_string(),
811            headers,
812            ..Default::default()
813        };
814        let result = HttpClientSource::new("test", cfg);
815        assert!(result.is_err());
816        assert!(result.unwrap_err().to_string().contains("header name"));
817    }
818
819    #[test]
820    fn test_new_rejects_invalid_header_value() {
821        let mut headers = HashMap::new();
822        headers.insert("X-Test".to_string(), "a\nb".to_string());
823        let cfg = HttpClientConfig {
824            url: "https://example.com".to_string(),
825            headers,
826            ..Default::default()
827        };
828        let result = HttpClientSource::new("test", cfg);
829        assert!(result.is_err());
830        assert!(result.unwrap_err().to_string().contains("header value"));
831    }
832
833    #[test]
834    fn test_new_rejects_error_body_limit_zero() {
835        let cfg = HttpClientConfig {
836            url: "https://example.com".to_string(),
837            error_body_limit: 0,
838            ..Default::default()
839        };
840        let result = HttpClientSource::new("test", cfg);
841        assert!(result.is_err());
842        assert!(result.unwrap_err().to_string().contains("error_body_limit"));
843    }
844
845    #[test]
846    fn test_config_deserialize_with_defaults() {
847        let yaml = r#"
848            url: "https://api.example.com"
849        "#;
850        let cfg: HttpClientConfig = serde_yaml::from_str(yaml).unwrap();
851        assert_eq!(cfg.url, "https://api.example.com");
852        assert_eq!(cfg.interval, Duration::from_secs(60));
853        assert!(cfg.schedule.is_none());
854        assert_eq!(cfg.method, "GET");
855        assert!(cfg.headers.is_empty());
856        assert_eq!(cfg.error_body_limit, 2048);
857    }
858
859    #[test]
860    fn test_config_deserialize_all_fields() {
861        let yaml = r#"
862            url: "https://api.example.com"
863            interval: "10s"
864            schedule: "0 0 * * *"
865            method: "POST"
866            error_body_limit: 512
867            headers:
868              Authorization: "Bearer token"
869              X-Custom: "value"
870        "#;
871        let cfg: HttpClientConfig = serde_yaml::from_str(yaml).unwrap();
872        assert_eq!(cfg.url, "https://api.example.com");
873        assert_eq!(cfg.interval, Duration::from_secs(10));
874        assert_eq!(cfg.schedule.as_deref(), Some("0 0 * * *"));
875        assert_eq!(cfg.method, "POST");
876        assert_eq!(cfg.error_body_limit, 512);
877        assert_eq!(cfg.headers.get("Authorization").unwrap(), "Bearer token");
878        assert_eq!(cfg.headers.get("X-Custom").unwrap(), "value");
879    }
880
881    #[test]
882    fn test_config_deserialize_interval_duration_string() {
883        let yaml = r#"
884            url: "https://api.example.com"
885            interval: "5m"
886        "#;
887        let cfg: HttpClientConfig = serde_yaml::from_str(yaml).unwrap();
888        assert_eq!(cfg.url, "https://api.example.com");
889        assert_eq!(cfg.interval, Duration::from_secs(5 * 60));
890    }
891
892    #[test]
893    fn test_config_deserialize_interval_duration_string_seconds() {
894        let yaml = r#"
895            url: "https://api.example.com"
896            interval: "10s"
897        "#;
898        let cfg: HttpClientConfig = serde_yaml::from_str(yaml).unwrap();
899        assert_eq!(cfg.interval, Duration::from_secs(10));
900    }
901
902    #[test]
903    fn test_config_deserialize_complex_duration() {
904        let yaml = r#"
905            url: "https://api.example.com"
906            interval: "1h 30m"
907        "#;
908        let cfg: HttpClientConfig = serde_yaml::from_str(yaml).unwrap();
909        assert_eq!(cfg.interval, Duration::from_secs(90 * 60));
910    }
911
912    #[tokio::test]
913    async fn test_fetch_success() {
914        let Some(mock_server) = start_mock_server().await else {
915            return;
916        };
917
918        Mock::given(method("GET"))
919            .and(path("/data"))
920            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
921                "status": "ok",
922                "value": 42
923            })))
924            .mount(&mock_server)
925            .await;
926
927        let config = HttpClientConfig {
928            url: format!("{}/data", mock_server.uri()),
929            ..Default::default()
930        };
931
932        let source = HttpClientSource::new("test", config).unwrap();
933        let result = source.fetch().await.unwrap();
934        assert_eq!(result["status"], "ok");
935        assert_eq!(result["value"], 42);
936    }
937
938    #[tokio::test]
939    async fn test_fetch_error_status() {
940        let Some(mock_server) = start_mock_server().await else {
941            return;
942        };
943
944        Mock::given(method("GET"))
945            .and(path("/error"))
946            .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
947            .mount(&mock_server)
948            .await;
949
950        let config = HttpClientConfig {
951            url: format!("{}/error", mock_server.uri()),
952            ..Default::default()
953        };
954
955        let source = HttpClientSource::new("test_source", config).unwrap();
956        let result = source.fetch().await;
957
958        assert!(result.is_err());
959        let error_msg = result.unwrap_err().to_string();
960        assert!(error_msg.contains("returned status 500"));
961        assert!(error_msg.contains("Internal Server Error"));
962    }
963
964    #[tokio::test]
965    async fn test_fetch_invalid_json() {
966        let Some(mock_server) = start_mock_server().await else {
967            return;
968        };
969
970        Mock::given(method("GET"))
971            .and(path("/invalid"))
972            .respond_with(ResponseTemplate::new(200).set_body_string("not json"))
973            .mount(&mock_server)
974            .await;
975
976        let config = HttpClientConfig {
977            url: format!("{}/invalid", mock_server.uri()),
978            ..Default::default()
979        };
980
981        let source = HttpClientSource::new("test_source", config).unwrap();
982        let result = source.fetch().await;
983
984        assert!(result.is_err());
985        assert!(
986            result
987                .unwrap_err()
988                .to_string()
989                .contains("Failed to parse response")
990        );
991    }
992
993    #[tokio::test]
994    async fn test_fetch_post_method() {
995        let Some(mock_server) = start_mock_server().await else {
996            return;
997        };
998
999        Mock::given(method("POST"))
1000            .and(path("/api"))
1001            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1002                "created": true
1003            })))
1004            .mount(&mock_server)
1005            .await;
1006
1007        let config = HttpClientConfig {
1008            url: format!("{}/api", mock_server.uri()),
1009            method: "POST".to_string(),
1010            ..Default::default()
1011        };
1012
1013        let source = HttpClientSource::new("test", config).unwrap();
1014        let result = source.fetch().await.unwrap();
1015        assert_eq!(result["created"], true);
1016    }
1017
1018    #[tokio::test]
1019    async fn test_fetch_put_method() {
1020        let Some(mock_server) = start_mock_server().await else {
1021            return;
1022        };
1023
1024        Mock::given(method("PUT"))
1025            .and(path("/resource"))
1026            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1027                "updated": true
1028            })))
1029            .mount(&mock_server)
1030            .await;
1031
1032        let config = HttpClientConfig {
1033            url: format!("{}/resource", mock_server.uri()),
1034            method: "PUT".to_string(),
1035            ..Default::default()
1036        };
1037
1038        let source = HttpClientSource::new("test", config).unwrap();
1039        let result = source.fetch().await.unwrap();
1040        assert_eq!(result["updated"], true);
1041    }
1042
1043    #[tokio::test]
1044    async fn test_fetch_delete_method() {
1045        let Some(mock_server) = start_mock_server().await else {
1046            return;
1047        };
1048
1049        Mock::given(method("DELETE"))
1050            .and(path("/resource/123"))
1051            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1052                "deleted": true
1053            })))
1054            .mount(&mock_server)
1055            .await;
1056
1057        let config = HttpClientConfig {
1058            url: format!("{}/resource/123", mock_server.uri()),
1059            method: "DELETE".to_string(),
1060            ..Default::default()
1061        };
1062
1063        let source = HttpClientSource::new("test", config).unwrap();
1064        let result = source.fetch().await.unwrap();
1065        assert_eq!(result["deleted"], true);
1066    }
1067
1068    #[tokio::test]
1069    async fn test_fetch_with_headers() {
1070        use wiremock::matchers::header;
1071
1072        let Some(mock_server) = start_mock_server().await else {
1073            return;
1074        };
1075
1076        Mock::given(method("GET"))
1077            .and(path("/auth"))
1078            .and(header("Authorization", "Bearer secret-token"))
1079            .and(header("X-Custom-Header", "custom-value"))
1080            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1081                "authenticated": true
1082            })))
1083            .mount(&mock_server)
1084            .await;
1085
1086        let mut headers = HashMap::new();
1087        headers.insert(
1088            "Authorization".to_string(),
1089            "Bearer secret-token".to_string(),
1090        );
1091        headers.insert("X-Custom-Header".to_string(), "custom-value".to_string());
1092
1093        let config = HttpClientConfig {
1094            url: format!("{}/auth", mock_server.uri()),
1095            headers,
1096            ..Default::default()
1097        };
1098
1099        let source = HttpClientSource::new("test", config).unwrap();
1100        let result = source.fetch().await.unwrap();
1101        assert_eq!(result["authenticated"], true);
1102    }
1103
1104    #[tokio::test]
1105    async fn test_fetch_error_body_truncation() {
1106        let Some(mock_server) = start_mock_server().await else {
1107            return;
1108        };
1109
1110        // Create a response body longer than error_body_limit
1111        let long_body = "x".repeat(3000);
1112
1113        Mock::given(method("GET"))
1114            .and(path("/long-error"))
1115            .respond_with(ResponseTemplate::new(500).set_body_string(&long_body))
1116            .mount(&mock_server)
1117            .await;
1118
1119        let config = HttpClientConfig {
1120            url: format!("{}/long-error", mock_server.uri()),
1121            error_body_limit: 64,
1122            ..Default::default()
1123        };
1124
1125        let source = HttpClientSource::new("test", config).unwrap();
1126        let result = source.fetch().await;
1127
1128        assert!(result.is_err());
1129        let error_msg = result.unwrap_err().to_string();
1130        assert!(error_msg.contains("...(truncated)"));
1131        // Ensure we don't include the full 3000 chars
1132        assert!(error_msg.len() < 200);
1133    }
1134
1135    #[tokio::test]
1136    async fn test_run_lifecycle() {
1137        let Some(mock_server) = start_mock_server().await else {
1138            return;
1139        };
1140
1141        // Mock two successful responses
1142        Mock::given(method("GET"))
1143            .and(path("/stream"))
1144            .respond_with(
1145                ResponseTemplate::new(200).set_body_json(serde_json::json!({"tick": "tock"})),
1146            )
1147            .mount(&mock_server)
1148            .await;
1149
1150        // Use a short interval for testing
1151        let config = HttpClientConfig {
1152            url: format!("{}/stream", mock_server.uri()),
1153            interval: Duration::from_millis(100),
1154            ..Default::default()
1155        };
1156
1157        let source = HttpClientSource::new("test_stream", config).unwrap();
1158        let (tx, mut rx) = broadcast::channel(10);
1159        let tx = MessageSender::new(tx, None);
1160        let (shutdown_tx, shutdown_rx) = broadcast::channel(1);
1161
1162        // Spawn the source task
1163        let source_handle = tokio::spawn(async move { source.run(tx, shutdown_rx).await });
1164
1165        // Verify initial fetch message
1166        let msg = rx.recv().await.expect("Should receive initial message");
1167        assert_eq!(msg.payload["tick"], "tock");
1168
1169        // Wait a bit to ensure we can receive another tick (optional, but good for robust testing)
1170        // With 100ms interval, we should get another one quickly.
1171        let msg2 = rx.recv().await.expect("Should receive second message");
1172        assert_eq!(msg2.payload["tick"], "tock");
1173
1174        // Signal shutdown
1175        shutdown_tx.send(()).unwrap();
1176
1177        // Ensure task finishes
1178        let _ = tokio::time::timeout(Duration::from_secs(1), source_handle)
1179            .await
1180            .expect("Source should shut down gracefully")
1181            .expect("Source task should succeed");
1182    }
1183
1184    #[tokio::test]
1185    async fn test_fetch_with_auth() {
1186        use wiremock::matchers::header;
1187
1188        let Some(mock_server) = start_mock_server().await else {
1189            return;
1190        };
1191
1192        Mock::given(method("GET"))
1193            .and(path("/secure"))
1194            .and(header("Authorization", "Basic dXNlcjpwYXNz")) // user:pass
1195            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1196                "secure_data": true
1197            })))
1198            .mount(&mock_server)
1199            .await;
1200
1201        let config = HttpClientConfig {
1202            url: format!("{}/secure", mock_server.uri()),
1203            auth: Some(AuthConfig::Basic {
1204                username: "user".to_string(),
1205                password: "pass".to_string(),
1206            }),
1207            ..Default::default()
1208        };
1209
1210        let source = HttpClientSource::new("test", config).unwrap();
1211        let result = source.fetch().await.unwrap();
1212        assert_eq!(result["secure_data"], true);
1213    }
1214
1215    #[test]
1216    fn test_expect_status_validation() {
1217        // Empty list is rejected
1218        let cfg = HttpClientConfig {
1219            url: "https://example.com".to_string(),
1220            expect_status: Some(vec![]),
1221            ..Default::default()
1222        };
1223        let result = HttpClientSource::new("test", cfg);
1224        assert!(result.is_err());
1225        assert!(
1226            result
1227                .unwrap_err()
1228                .to_string()
1229                .contains("must not be empty")
1230        );
1231
1232        // Invalid status code is rejected
1233        let cfg = HttpClientConfig {
1234            url: "https://example.com".to_string(),
1235            expect_status: Some(vec![200, 1000]),
1236            ..Default::default()
1237        };
1238        let result = HttpClientSource::new("test", cfg);
1239        assert!(result.is_err());
1240        assert!(
1241            result
1242                .unwrap_err()
1243                .to_string()
1244                .contains("invalid HTTP status code")
1245        );
1246
1247        // Valid status codes are accepted
1248        let cfg = HttpClientConfig {
1249            url: "https://example.com".to_string(),
1250            expect_status: Some(vec![200, 201, 204]),
1251            ..Default::default()
1252        };
1253        let result = HttpClientSource::new("test", cfg);
1254        assert!(result.is_ok());
1255    }
1256
1257    #[test]
1258    fn test_expect_body_validation() {
1259        // path without eq/ne is rejected
1260        let cfg = HttpClientConfig {
1261            url: "https://example.com".to_string(),
1262            expect_body: Some(ExpectBodyConfig {
1263                path: Some("$.status".to_string()),
1264                eq: None,
1265                ne: None,
1266                contains: None,
1267                not_contains: None,
1268            }),
1269            ..Default::default()
1270        };
1271        let result = HttpClientSource::new("test", cfg);
1272        assert!(result.is_err());
1273        assert!(result.unwrap_err().to_string().contains("'eq' or 'ne'"));
1274
1275        // eq without path is rejected
1276        let cfg = HttpClientConfig {
1277            url: "https://example.com".to_string(),
1278            expect_body: Some(ExpectBodyConfig {
1279                path: None,
1280                eq: Some(serde_json::json!(true)),
1281                ne: None,
1282                contains: None,
1283                not_contains: None,
1284            }),
1285            ..Default::default()
1286        };
1287        let result = HttpClientSource::new("test", cfg);
1288        assert!(result.is_err());
1289        assert!(result.unwrap_err().to_string().contains("'path'"));
1290
1291        // contains alone is accepted
1292        let cfg = HttpClientConfig {
1293            url: "https://example.com".to_string(),
1294            expect_body: Some(ExpectBodyConfig {
1295                path: None,
1296                eq: None,
1297                ne: None,
1298                contains: Some("success".to_string()),
1299                not_contains: None,
1300            }),
1301            ..Default::default()
1302        };
1303        let result = HttpClientSource::new("test", cfg);
1304        assert!(result.is_ok());
1305
1306        // path + eq is accepted
1307        let cfg = HttpClientConfig {
1308            url: "https://example.com".to_string(),
1309            expect_body: Some(ExpectBodyConfig {
1310                path: Some("$.status".to_string()),
1311                eq: Some(serde_json::json!("ok")),
1312                ne: None,
1313                contains: None,
1314                not_contains: None,
1315            }),
1316            ..Default::default()
1317        };
1318        let result = HttpClientSource::new("test", cfg);
1319        assert!(result.is_ok());
1320    }
1321
1322    #[tokio::test]
1323    async fn test_fetch_with_custom_expect_status() {
1324        let Some(mock_server) = start_mock_server().await else {
1325            return;
1326        };
1327
1328        Mock::given(method("GET"))
1329            .and(path("/custom"))
1330            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
1331                "created": true
1332            })))
1333            .mount(&mock_server)
1334            .await;
1335
1336        // Default behavior: 201 is successful (2xx)
1337        let config = HttpClientConfig {
1338            url: format!("{}/custom", mock_server.uri()),
1339            ..Default::default()
1340        };
1341        let source = HttpClientSource::new("test", config).unwrap();
1342        let result = source.fetch().await;
1343        assert!(result.is_ok());
1344
1345        // Custom expect_status: only 200 is allowed
1346        let config = HttpClientConfig {
1347            url: format!("{}/custom", mock_server.uri()),
1348            expect_status: Some(vec![200]),
1349            ..Default::default()
1350        };
1351        let source = HttpClientSource::new("test", config).unwrap();
1352        let result = source.fetch().await;
1353        assert!(result.is_err());
1354        assert!(result.unwrap_err().to_string().contains("status 201"));
1355
1356        // Custom expect_status: 201 is allowed
1357        let config = HttpClientConfig {
1358            url: format!("{}/custom", mock_server.uri()),
1359            expect_status: Some(vec![200, 201]),
1360            ..Default::default()
1361        };
1362        let source = HttpClientSource::new("test", config).unwrap();
1363        let result = source.fetch().await;
1364        assert!(result.is_ok());
1365    }
1366
1367    #[tokio::test]
1368    async fn test_fetch_with_body_keyword_validation() {
1369        let Some(mock_server) = start_mock_server().await else {
1370            return;
1371        };
1372
1373        Mock::given(method("GET"))
1374            .and(path("/keyword"))
1375            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1376                "status": "success",
1377                "data": "value"
1378            })))
1379            .mount(&mock_server)
1380            .await;
1381
1382        // contains: "success" - should pass
1383        let config = HttpClientConfig {
1384            url: format!("{}/keyword", mock_server.uri()),
1385            expect_body: Some(ExpectBodyConfig {
1386                path: None,
1387                eq: None,
1388                ne: None,
1389                contains: Some("success".to_string()),
1390                not_contains: None,
1391            }),
1392            ..Default::default()
1393        };
1394        let source = HttpClientSource::new("test", config).unwrap();
1395        assert!(source.fetch().await.is_ok());
1396
1397        // contains: "error" - should fail
1398        let config = HttpClientConfig {
1399            url: format!("{}/keyword", mock_server.uri()),
1400            expect_body: Some(ExpectBodyConfig {
1401                path: None,
1402                eq: None,
1403                ne: None,
1404                contains: Some("error".to_string()),
1405                not_contains: None,
1406            }),
1407            ..Default::default()
1408        };
1409        let source = HttpClientSource::new("test", config).unwrap();
1410        let result = source.fetch().await;
1411        assert!(result.is_err());
1412        assert!(result.unwrap_err().to_string().contains("does not contain"));
1413
1414        // not_contains: "error" - should pass
1415        let config = HttpClientConfig {
1416            url: format!("{}/keyword", mock_server.uri()),
1417            expect_body: Some(ExpectBodyConfig {
1418                path: None,
1419                eq: None,
1420                ne: None,
1421                contains: None,
1422                not_contains: Some("error".to_string()),
1423            }),
1424            ..Default::default()
1425        };
1426        let source = HttpClientSource::new("test", config).unwrap();
1427        assert!(source.fetch().await.is_ok());
1428    }
1429
1430    #[tokio::test]
1431    async fn test_fetch_with_body_jsonpath_validation() {
1432        let Some(mock_server) = start_mock_server().await else {
1433            return;
1434        };
1435
1436        Mock::given(method("GET"))
1437            .and(path("/jsonpath"))
1438            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1439                "status": "ok",
1440                "error": null
1441            })))
1442            .mount(&mock_server)
1443            .await;
1444
1445        // eq: $.status == "ok" - should pass
1446        let config = HttpClientConfig {
1447            url: format!("{}/jsonpath", mock_server.uri()),
1448            expect_body: Some(ExpectBodyConfig {
1449                path: Some("$.status".to_string()),
1450                eq: Some(serde_json::json!("ok")),
1451                ne: None,
1452                contains: None,
1453                not_contains: None,
1454            }),
1455            ..Default::default()
1456        };
1457        let source = HttpClientSource::new("test", config).unwrap();
1458        assert!(source.fetch().await.is_ok());
1459
1460        // eq: $.error == null - should pass
1461        let config = HttpClientConfig {
1462            url: format!("{}/jsonpath", mock_server.uri()),
1463            expect_body: Some(ExpectBodyConfig {
1464                path: Some("$.error".to_string()),
1465                eq: Some(serde_json::Value::Null),
1466                ne: None,
1467                contains: None,
1468                not_contains: None,
1469            }),
1470            ..Default::default()
1471        };
1472        let source = HttpClientSource::new("test", config).unwrap();
1473        assert!(source.fetch().await.is_ok());
1474
1475        // ne: $.status != "error" - should pass
1476        let config = HttpClientConfig {
1477            url: format!("{}/jsonpath", mock_server.uri()),
1478            expect_body: Some(ExpectBodyConfig {
1479                path: Some("$.status".to_string()),
1480                eq: None,
1481                ne: Some(serde_json::json!("error")),
1482                contains: None,
1483                not_contains: None,
1484            }),
1485            ..Default::default()
1486        };
1487        let source = HttpClientSource::new("test", config).unwrap();
1488        assert!(source.fetch().await.is_ok());
1489
1490        // eq: $.status == "error" - should fail
1491        let config = HttpClientConfig {
1492            url: format!("{}/jsonpath", mock_server.uri()),
1493            expect_body: Some(ExpectBodyConfig {
1494                path: Some("$.status".to_string()),
1495                eq: Some(serde_json::json!("error")),
1496                ne: None,
1497                contains: None,
1498                not_contains: None,
1499            }),
1500            ..Default::default()
1501        };
1502        let source = HttpClientSource::new("test", config).unwrap();
1503        let result = source.fetch().await;
1504        assert!(result.is_err());
1505        assert!(
1506            result
1507                .unwrap_err()
1508                .to_string()
1509                .contains("validation failed")
1510        );
1511    }
1512
1513    #[test]
1514    fn test_default_accept_header() {
1515        let cfg = HttpClientConfig {
1516            url: "https://example.com".to_string(),
1517            ..Default::default()
1518        };
1519        let source = HttpClientSource::new("test", cfg).unwrap();
1520        // Default Accept header should be application/json
1521        assert!(source.headers.contains_key(reqwest::header::ACCEPT));
1522        assert_eq!(
1523            source.headers.get(reqwest::header::ACCEPT).unwrap(),
1524            "application/json"
1525        );
1526    }
1527
1528    #[test]
1529    fn test_accept_header_override() {
1530        let mut headers = HashMap::new();
1531        headers.insert("Accept".to_string(), "text/html".to_string());
1532        let cfg = HttpClientConfig {
1533            url: "https://example.com".to_string(),
1534            headers,
1535            ..Default::default()
1536        };
1537        let source = HttpClientSource::new("test", cfg).unwrap();
1538        // User-provided Accept header should override default
1539        assert_eq!(
1540            source.headers.get(reqwest::header::ACCEPT).unwrap(),
1541            "text/html"
1542        );
1543    }
1544
1545    #[test]
1546    fn test_accept_header_case_insensitive_override() {
1547        let mut headers = HashMap::new();
1548        headers.insert("accept".to_string(), "application/xml".to_string());
1549        let cfg = HttpClientConfig {
1550            url: "https://example.com".to_string(),
1551            headers,
1552            ..Default::default()
1553        };
1554        let source = HttpClientSource::new("test", cfg).unwrap();
1555        // Case-insensitive match should still override
1556        assert_eq!(
1557            source.headers.get(reqwest::header::ACCEPT).unwrap(),
1558            "application/xml"
1559        );
1560    }
1561    #[tokio::test]
1562    async fn test_schedule_interval_tag() {
1563        let Some(mock_server) = start_mock_server().await else {
1564            return;
1565        };
1566
1567        Mock::given(method("GET"))
1568            .and(path("/data"))
1569            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1570                "value": 1
1571            })))
1572            .mount(&mock_server)
1573            .await;
1574
1575        // Case 1: With schedule (interval tag should be empty)
1576        let config_scheduled = HttpClientConfig {
1577            url: format!("{}/data", mock_server.uri()),
1578            schedule: Some("0 0 * * *".to_string()),
1579            ..Default::default()
1580        };
1581        let source_scheduled = HttpClientSource::new("test_scheduled", config_scheduled).unwrap();
1582        let (tx, mut rx) = broadcast::channel(1);
1583        let sender = MessageSender::new(tx, None);
1584
1585        // Force a fetch
1586        source_scheduled.fetch_and_send(&sender).await;
1587        let msg = rx.recv().await.unwrap();
1588        assert_eq!(msg.meta.tags.get("interval").map(|s| s.as_str()), Some(""));
1589        assert!(!msg.meta.tags.get("schedule").unwrap().is_empty());
1590
1591        // Case 2: Without schedule (interval tag should be populated)
1592        let config_interval = HttpClientConfig {
1593            url: format!("{}/data", mock_server.uri()),
1594            interval: Duration::from_secs(60),
1595            ..Default::default()
1596        };
1597        let source_interval = HttpClientSource::new("test_interval", config_interval).unwrap();
1598        let (tx2, mut rx2) = broadcast::channel(1);
1599        let sender2 = MessageSender::new(tx2, None);
1600
1601        // Force a fetch
1602        source_interval.fetch_and_send(&sender2).await;
1603        let msg2 = rx2.recv().await.unwrap();
1604        assert_eq!(
1605            msg2.meta.tags.get("interval").map(|s| s.as_str()),
1606            Some("1m")
1607        );
1608        assert_eq!(msg2.meta.tags.get("schedule").map(|s| s.as_str()), Some(""));
1609    }
1610}