Skip to main content

omega_cognitive_kernel/l0/
observer.rs

1#[allow(unused_imports)]
2use crate::prelude::*;
3
4#[cfg(feature = "std")]
5use crate::error::OmegaError;
6use crate::error::Result;
7use crate::types::{Modality, Observation};
8#[cfg(all(feature = "std", feature = "async"))]
9use std::future::Future;
10#[cfg(all(
11    feature = "std",
12    any(feature = "ureq", all(feature = "async", feature = "reqwest"))
13))]
14use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
15#[cfg(feature = "std")]
16use std::path::{Path, PathBuf};
17#[cfg(all(feature = "std", feature = "async"))]
18use std::sync::{Arc, Mutex};
19#[cfg(feature = "std")]
20use std::time::Duration;
21#[cfg(all(
22    feature = "std",
23    any(feature = "ureq", all(feature = "async", feature = "reqwest"))
24))]
25use std::time::Instant;
26#[cfg(all(
27    feature = "std",
28    any(feature = "ureq", all(feature = "async", feature = "reqwest"))
29))]
30use url::Url;
31
32/// External world observation interface (synchronous).
33///
34/// Implement this trait to feed real sensors, files, HTTP status, or any other
35/// source into the kernel. The default `MultiModalObserver` is a pure simulation.
36pub trait Observer {
37    /// Performs item for this type.
38    fn observe(&mut self) -> Result<Vec<Observation>>;
39}
40
41/// External world observation interface (asynchronous).
42///
43/// Async version of [`Observer`] for use with async runtimes (tokio).
44/// Requires the `async` feature (which implies `std`).
45#[cfg(all(feature = "std", feature = "async"))]
46#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
47pub trait AsyncObserver {
48    /// Performs output for this type.
49    fn observe_async(&mut self) -> impl Future<Output = Result<Vec<Observation>>> + Send;
50}
51
52/// Adapter to use a synchronous [`Observer`] as an [`AsyncObserver`] by running
53/// the blocking call on a thread pool (tokio).
54#[cfg(all(feature = "std", feature = "async"))]
55#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
56pub struct AsyncObserverAdapter<O> {
57    inner: Arc<Mutex<Option<O>>>,
58}
59
60#[cfg(feature = "async")]
61#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
62impl<O> AsyncObserverAdapter<O> {
63    /// Creates a new value of this type.
64    pub fn new(observer: O) -> Self {
65        Self {
66            inner: Arc::new(Mutex::new(Some(observer))),
67        }
68    }
69    /// Attempt to unwrap the inner observer without panicking.
70    ///
71    /// Returns `None` if another clone or in-flight task still holds the adapter.
72    pub fn try_into_inner(self) -> Option<O> {
73        Arc::try_unwrap(self.inner)
74            .ok()
75            .and_then(|mutex| mutex.into_inner().ok())
76            .and_then(Option::from)
77    }
78
79    /// Unwrap the inner observer.
80    ///
81    /// # Panics
82    ///
83    /// Panics if another clone or in-flight task still holds the adapter.
84    /// Prefer [`Self::try_into_inner`] when exclusive ownership is not guaranteed.
85    pub fn into_inner(self) -> O {
86        self.try_into_inner()
87            .expect("AsyncObserverAdapter is still in use")
88    }
89}
90
91#[cfg(feature = "async")]
92#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
93impl<O: Observer + Send + 'static> AsyncObserver for AsyncObserverAdapter<O> {
94    fn observe_async(&mut self) -> impl Future<Output = Result<Vec<Observation>>> + Send {
95        let inner = Arc::clone(&self.inner);
96        async move {
97            tokio::task::spawn_blocking(move || {
98                let mut guard = inner.lock().map_err(|_| {
99                    OmegaError::ExecutionBlocked("observer adapter lock poisoned".into())
100                })?;
101                let observer = guard.as_mut().ok_or_else(|| {
102                    OmegaError::ExecutionBlocked("AsyncObserverAdapter already consumed".into())
103                })?;
104                observer.observe()
105            })
106            .await
107            .map_err(|e| OmegaError::Other(anyhow::anyhow!(e)))?
108        }
109    }
110}
111
112/// Blanket implementation: any sync `Observer` can be used as an `AsyncObserver`
113/// by wrapping it in `AsyncObserverAdapter`.
114#[cfg(feature = "async")]
115#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
116impl<O: Observer + Send + 'static> From<O> for AsyncObserverAdapter<O> {
117    fn from(observer: O) -> Self {
118        Self::new(observer)
119    }
120}
121
122/// Data structure representing multi modal observer.
123pub struct MultiModalObserver {
124    /// Step counter for this value.
125    pub step_counter: u64,
126}
127
128impl MultiModalObserver {
129    /// Creates a new value of this type.
130    pub fn new() -> Self {
131        Self { step_counter: 0 }
132    }
133}
134
135impl Default for MultiModalObserver {
136    fn default() -> Self {
137        Self::new()
138    }
139}
140
141impl Observer for MultiModalObserver {
142    fn observe(&mut self) -> Result<Vec<Observation>> {
143        self.step_counter += 1;
144        Ok(vec![Observation {
145            timestamp: crate::now_utc(),
146            modality: Modality::Structured,
147            content: serde_json::json!({
148                "step": self.step_counter,
149                "signal": "world_tick",
150                "value": libm::sin(self.step_counter as f64 * 0.1)
151            }),
152            confidence: 0.95,
153            source: "sim_sensor".into(),
154        }])
155    }
156}
157
158/// Reads a single JSON (or plain-text) file on each observe call.
159#[cfg(feature = "std")]
160pub struct FileObserver {
161    path: PathBuf,
162    step_counter: u64,
163}
164
165#[cfg(feature = "std")]
166impl FileObserver {
167    /// Creates a new value of this type.
168    pub fn new(path: impl AsRef<Path>) -> Self {
169        Self {
170            path: path.as_ref().to_path_buf(),
171            step_counter: 0,
172        }
173    }
174}
175
176#[cfg(feature = "std")]
177impl Observer for FileObserver {
178    fn observe(&mut self) -> Result<Vec<Observation>> {
179        self.step_counter += 1;
180        let raw = std::fs::read_to_string(&self.path).map_err(|e| {
181            OmegaError::ExecutionBlocked(format!(
182                "FileObserver failed to read {}: {e}",
183                self.path.display()
184            ))
185        })?;
186
187        let content = serde_json::from_str::<serde_json::Value>(&raw).unwrap_or_else(|_| {
188            serde_json::json!({
189                "raw": raw,
190                "step": self.step_counter
191            })
192        });
193
194        Ok(vec![Observation {
195            timestamp: crate::now_utc(),
196            modality: Modality::Structured,
197            content,
198            confidence: 0.9,
199            source: format!("file:{}", self.path.display()),
200        }])
201    }
202}
203
204/// Snapshot of a directory: file names, sizes, modified times.
205///
206/// Offline-friendly monitoring adapter — good for log folders or drop directories.
207#[cfg(feature = "std")]
208pub struct DirSnapshotObserver {
209    path: PathBuf,
210    step_counter: u64,
211    max_entries: usize,
212}
213
214#[cfg(feature = "std")]
215impl DirSnapshotObserver {
216    /// Creates a new value of this type.
217    pub fn new(path: impl AsRef<Path>) -> Self {
218        Self {
219            path: path.as_ref().to_path_buf(),
220            step_counter: 0,
221            max_entries: 64,
222        }
223    }
224
225    /// Performs maximum entries for this type.
226    pub fn max_entries(mut self, n: usize) -> Self {
227        self.max_entries = n.max(1);
228        self
229    }
230}
231
232#[cfg(feature = "std")]
233impl Observer for DirSnapshotObserver {
234    fn observe(&mut self) -> Result<Vec<Observation>> {
235        self.step_counter += 1;
236        let rd = std::fs::read_dir(&self.path).map_err(|e| {
237            OmegaError::ExecutionBlocked(format!(
238                "DirSnapshotObserver {}: {e}",
239                self.path.display()
240            ))
241        })?;
242
243        let mut entries = Vec::new();
244        for ent in rd.flatten().take(self.max_entries) {
245            let meta = ent.metadata().ok();
246            let modified = meta.as_ref().and_then(|m| m.modified().ok()).and_then(|t| {
247                t.duration_since(std::time::UNIX_EPOCH)
248                    .ok()
249                    .map(|d| d.as_secs())
250            });
251            entries.push(serde_json::json!({
252                "name": ent.file_name().to_string_lossy(),
253                "is_dir": meta.as_ref().map(|m| m.is_dir()).unwrap_or(false),
254                "len": meta.as_ref().map(|m| m.len()).unwrap_or(0),
255                "modified_unix": modified,
256            }));
257        }
258
259        Ok(vec![Observation {
260            timestamp: crate::now_utc(),
261            modality: Modality::Structured,
262            content: serde_json::json!({
263                "step": self.step_counter,
264                "dir": self.path.display().to_string(),
265                "entry_count": entries.len(),
266                "entries": entries,
267            }),
268            confidence: 0.92,
269            source: format!("dir:{}", self.path.display()),
270        }])
271    }
272}
273
274#[cfg(all(
275    feature = "std",
276    any(feature = "ureq", all(feature = "async", feature = "reqwest"))
277))]
278const MAX_HTTP_REDIRECTS: usize = 5;
279
280#[cfg(all(
281    feature = "std",
282    any(feature = "ureq", all(feature = "async", feature = "reqwest"))
283))]
284pub(crate) fn parse_http_url(raw: &str) -> Result<Url> {
285    let url = Url::parse(raw)
286        .map_err(|_| OmegaError::ExecutionBlocked("HttpObserver URL is invalid".into()))?;
287    if !matches!(url.scheme(), "http" | "https")
288        || url.host_str().is_none()
289        || !url.username().is_empty()
290        || url.password().is_some()
291    {
292        return Err(OmegaError::ExecutionBlocked(
293            "HttpObserver only accepts credential-free HTTP(S) URLs".into(),
294        ));
295    }
296    Ok(url)
297}
298
299#[cfg(all(
300    feature = "std",
301    any(feature = "ureq", all(feature = "async", feature = "reqwest"))
302))]
303fn is_public_ip(ip: IpAddr) -> bool {
304    match ip {
305        IpAddr::V4(address) => {
306            let octets = address.octets();
307            let (a, b, c) = (octets[0], octets[1], octets[2]);
308            !(address.is_unspecified()
309                || address.is_private()
310                || address.is_loopback()
311                || address.is_link_local()
312                || address.is_broadcast()
313                || address.is_multicast()
314                || a == 0
315                || a >= 224
316                || (a == 100 && (64..=127).contains(&b))
317                || (a == 192 && (b == 0 || (b == 88 && c == 99)))
318                || (a == 198 && (b == 18 || b == 19 || (b == 51 && c == 100)))
319                || (a == 203 && b == 0 && c == 113))
320        }
321        IpAddr::V6(address) => {
322            let segments = address.segments();
323            let global_unicast = segments[0] & 0xe000 == 0x2000;
324            global_unicast
325                && !address.is_unspecified()
326                && !address.is_loopback()
327                && !address.is_multicast()
328                // Exclude 6to4/Teredo and special-purpose/documentation space.
329                && segments[0] != 0x2002
330                && !(segments[0] == 0x2001
331                    && (segments[1] <= 0x01ff || segments[1] == 0x0db8))
332        }
333    }
334}
335
336#[cfg(all(
337    feature = "std",
338    any(feature = "ureq", all(feature = "async", feature = "reqwest"))
339))]
340static ACTIVE_HTTP_DNS_LOOKUPS: std::sync::atomic::AtomicUsize =
341    std::sync::atomic::AtomicUsize::new(0);
342#[cfg(all(
343    feature = "std",
344    any(feature = "ureq", all(feature = "async", feature = "reqwest"))
345))]
346const MAX_ACTIVE_HTTP_DNS_LOOKUPS: usize = 8;
347
348#[cfg(all(
349    feature = "std",
350    any(feature = "ureq", all(feature = "async", feature = "reqwest"))
351))]
352struct HttpDnsLookupSlot;
353
354#[cfg(all(
355    feature = "std",
356    any(feature = "ureq", all(feature = "async", feature = "reqwest"))
357))]
358impl Drop for HttpDnsLookupSlot {
359    fn drop(&mut self) {
360        use std::sync::atomic::Ordering;
361        ACTIVE_HTTP_DNS_LOOKUPS.fetch_sub(1, Ordering::AcqRel);
362    }
363}
364
365/// Run the platform resolver off-thread, enforce its share of the request
366/// deadline, and cap abandoned lookups if the OS resolver stalls.
367#[cfg(all(
368    feature = "std",
369    any(feature = "ureq", all(feature = "async", feature = "reqwest"))
370))]
371fn bounded_http_dns_lookup<F>(timeout: Duration, lookup: F) -> Result<Vec<SocketAddr>>
372where
373    F: FnOnce() -> std::io::Result<Vec<SocketAddr>> + Send + 'static,
374{
375    use std::sync::atomic::Ordering;
376    use std::sync::mpsc;
377
378    if timeout.is_zero() {
379        return Err(OmegaError::ExecutionBlocked(
380            "HttpObserver total timeout during DNS lookup".into(),
381        ));
382    }
383    let mut active = ACTIVE_HTTP_DNS_LOOKUPS.load(Ordering::Acquire);
384    loop {
385        if active >= MAX_ACTIVE_HTTP_DNS_LOOKUPS {
386            return Err(OmegaError::ExecutionBlocked(
387                "HttpObserver DNS lookup capacity exhausted".into(),
388            ));
389        }
390        match ACTIVE_HTTP_DNS_LOOKUPS.compare_exchange_weak(
391            active,
392            active + 1,
393            Ordering::AcqRel,
394            Ordering::Acquire,
395        ) {
396            Ok(_) => break,
397            Err(observed) => active = observed,
398        }
399    }
400
401    let slot = HttpDnsLookupSlot;
402    let (sender, receiver) = mpsc::sync_channel(1);
403    std::thread::Builder::new()
404        .name("http-observer-dns".into())
405        .spawn(move || {
406            let _slot = slot;
407            let _ = sender.send(lookup());
408        })
409        .map_err(|_| OmegaError::ExecutionBlocked("HttpObserver DNS worker unavailable".into()))?;
410
411    match receiver.recv_timeout(timeout) {
412        Ok(Ok(addresses)) => Ok(addresses),
413        Ok(Err(_)) => Err(OmegaError::ExecutionBlocked(
414            "HttpObserver DNS lookup failed".into(),
415        )),
416        Err(mpsc::RecvTimeoutError::Timeout) => Err(OmegaError::ExecutionBlocked(
417            "HttpObserver total timeout during DNS lookup".into(),
418        )),
419        Err(mpsc::RecvTimeoutError::Disconnected) => Err(OmegaError::ExecutionBlocked(
420            "HttpObserver DNS worker failed".into(),
421        )),
422    }
423}
424
425/// Resolve once, reject the whole answer set if any address is non-public, and
426/// pass this exact vetted set to the HTTP client's resolver to prevent rebinding.
427#[cfg(all(
428    feature = "std",
429    any(feature = "ureq", all(feature = "async", feature = "reqwest"))
430))]
431fn resolve_public_http_target(url: &Url, dns_timeout: Duration) -> Result<Vec<SocketAddr>> {
432    let host = url
433        .host_str()
434        .ok_or_else(|| OmegaError::ExecutionBlocked("HttpObserver URL has no host".into()))?;
435    let port = url
436        .port_or_known_default()
437        .ok_or_else(|| OmegaError::ExecutionBlocked("HttpObserver URL has no port".into()))?;
438    let addresses = if let Ok(ip) = host.parse::<IpAddr>() {
439        vec![SocketAddr::new(ip, port)]
440    } else {
441        let host = host.to_owned();
442        bounded_http_dns_lookup(dns_timeout, move || {
443            (host.as_str(), port)
444                .to_socket_addrs()
445                .map(|addresses| addresses.collect::<Vec<_>>())
446        })?
447    };
448
449    if addresses.is_empty() {
450        return Err(OmegaError::ExecutionBlocked(
451            "HttpObserver DNS lookup returned no addresses".into(),
452        ));
453    }
454    if addresses.iter().any(|address| !is_public_ip(address.ip())) {
455        return Err(OmegaError::ExecutionBlocked(
456            "HttpObserver target resolves to a non-public address".into(),
457        ));
458    }
459
460    let mut addresses = addresses;
461    addresses.sort_unstable();
462    addresses.dedup();
463    Ok(addresses)
464}
465
466#[cfg(all(
467    feature = "std",
468    any(feature = "ureq", all(feature = "async", feature = "reqwest"))
469))]
470fn redirected_http_url(current: &Url, status: u16, location: Option<&str>) -> Result<Option<Url>> {
471    if !(300..400).contains(&status) {
472        return Ok(None);
473    }
474    let Some(location) = location else {
475        return Ok(None);
476    };
477    let joined = current
478        .join(location)
479        .map_err(|_| OmegaError::ExecutionBlocked("HttpObserver redirect URL is invalid".into()))?;
480    let next = parse_http_url(joined.as_str())?;
481    if current.scheme() == "https" && next.scheme() == "http" {
482        return Err(OmegaError::ExecutionBlocked(
483            "HttpObserver refused an HTTPS-to-HTTP redirect".into(),
484        ));
485    }
486    Ok(Some(next))
487}
488
489#[cfg(all(feature = "std", feature = "ureq"))]
490pub(crate) fn fetch_http_sync_preview(
491    current: Url,
492    timeout: Duration,
493    connect_timeout: Duration,
494    max_response_bytes: usize,
495) -> Result<(u16, Vec<u8>, bool)> {
496    fetch_http_sync_preview_with_resolver(
497        current,
498        timeout,
499        connect_timeout,
500        max_response_bytes,
501        resolve_public_http_target,
502    )
503}
504
505#[cfg(all(feature = "std", feature = "ureq"))]
506pub(crate) fn fetch_http_sync_preview_with_resolver<F>(
507    current: Url,
508    timeout: Duration,
509    connect_timeout: Duration,
510    max_response_bytes: usize,
511    resolve: F,
512) -> Result<(u16, Vec<u8>, bool)>
513where
514    F: FnMut(&Url, Duration) -> Result<Vec<SocketAddr>>,
515{
516    fetch_http_sync_with_resolver_mode(
517        current,
518        timeout,
519        connect_timeout,
520        max_response_bytes,
521        true,
522        resolve,
523    )
524}
525
526#[cfg(all(feature = "std", feature = "ureq"))]
527fn fetch_http_sync_with_resolver<F>(
528    current: Url,
529    timeout: Duration,
530    connect_timeout: Duration,
531    max_response_bytes: usize,
532    resolve: F,
533) -> Result<(u16, Vec<u8>)>
534where
535    F: FnMut(&Url, Duration) -> Result<Vec<SocketAddr>>,
536{
537    let (status, body, _) = fetch_http_sync_with_resolver_mode(
538        current,
539        timeout,
540        connect_timeout,
541        max_response_bytes,
542        false,
543        resolve,
544    )?;
545    Ok((status, body))
546}
547
548#[cfg(all(feature = "std", feature = "ureq"))]
549#[derive(Debug)]
550struct PinnedHttpResolver {
551    addresses: ureq::unversioned::resolver::ResolvedSocketAddrs,
552}
553
554#[cfg(all(feature = "std", feature = "ureq"))]
555impl PinnedHttpResolver {
556    fn new(addresses: Vec<SocketAddr>) -> Result<Self> {
557        let mut pinned = ureq::unversioned::resolver::ResolvedSocketAddrs::from_fn(|_| {
558            SocketAddr::new(IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), 0)
559        });
560        for address in addresses {
561            if pinned.try_push(address).is_err() {
562                return Err(OmegaError::ExecutionBlocked(
563                    "HttpObserver DNS lookup returned too many addresses".into(),
564                ));
565            }
566        }
567        if pinned.is_empty() {
568            return Err(OmegaError::ExecutionBlocked(
569                "HttpObserver has no vetted target addresses".into(),
570            ));
571        }
572        Ok(Self { addresses: pinned })
573    }
574}
575
576#[cfg(all(feature = "std", feature = "ureq"))]
577impl ureq::unversioned::resolver::Resolver for PinnedHttpResolver {
578    fn resolve(
579        &self,
580        _uri: &ureq::http::Uri,
581        _config: &ureq::config::Config,
582        _timeout: ureq::unversioned::transport::NextTimeout,
583    ) -> std::result::Result<ureq::unversioned::resolver::ResolvedSocketAddrs, ureq::Error> {
584        Ok(self.addresses.clone())
585    }
586}
587
588#[cfg(all(feature = "std", feature = "ureq"))]
589fn fetch_http_sync_with_resolver_mode<F>(
590    mut current: Url,
591    timeout: Duration,
592    connect_timeout: Duration,
593    max_response_bytes: usize,
594    truncate_to_limit: bool,
595    mut resolve: F,
596) -> Result<(u16, Vec<u8>, bool)>
597where
598    F: FnMut(&Url, Duration) -> Result<Vec<SocketAddr>>,
599{
600    use std::io::Read;
601
602    let started = Instant::now();
603    for redirect_count in 0..=MAX_HTTP_REDIRECTS {
604        let remaining = timeout
605            .checked_sub(started.elapsed())
606            .filter(|remaining| !remaining.is_zero())
607            .ok_or_else(|| OmegaError::ExecutionBlocked("HttpObserver total timeout".into()))?;
608        let addresses = resolve(&current, remaining)?;
609        if addresses.is_empty() {
610            return Err(OmegaError::ExecutionBlocked(
611                "HttpObserver has no vetted target addresses".into(),
612            ));
613        }
614        let remaining = timeout
615            .checked_sub(started.elapsed())
616            .filter(|remaining| !remaining.is_zero())
617            .ok_or_else(|| OmegaError::ExecutionBlocked("HttpObserver total timeout".into()))?;
618        let config = ureq::Agent::config_builder()
619            .http_status_as_error(false)
620            .max_redirects(0)
621            .proxy(None)
622            .timeout_connect(Some(connect_timeout.min(remaining)))
623            .timeout_global(Some(remaining))
624            .build();
625        let agent = ureq::Agent::with_parts(
626            config,
627            ureq::unversioned::transport::DefaultConnector::new(),
628            PinnedHttpResolver::new(addresses)?,
629        );
630        let response = agent
631            .get(current.as_str())
632            .call()
633            .map_err(|_| OmegaError::ExecutionBlocked("HttpObserver request failed".into()))?;
634        let status = response.status().as_u16();
635        let location = response
636            .headers()
637            .get("Location")
638            .and_then(|value| value.to_str().ok())
639            .map(str::to_owned);
640        if let Some(next) = redirected_http_url(&current, status, location.as_deref())? {
641            if redirect_count == MAX_HTTP_REDIRECTS {
642                return Err(OmegaError::ExecutionBlocked(
643                    "HttpObserver exceeded redirect limit".into(),
644                ));
645            }
646            current = next;
647            continue;
648        }
649
650        let read_limit = u64::try_from(max_response_bytes.saturating_add(1)).unwrap_or(u64::MAX);
651        let mut body = Vec::with_capacity(max_response_bytes.min(8192));
652        response
653            .into_body()
654            .into_reader()
655            .take(read_limit)
656            .read_to_end(&mut body)
657            .map_err(|_| OmegaError::ExecutionBlocked("HttpObserver body read failed".into()))?;
658        let truncated = body.len() > max_response_bytes;
659        if truncated && !truncate_to_limit {
660            return Err(OmegaError::ExecutionBlocked(
661                "HttpObserver response body exceeds configured limit".into(),
662            ));
663        }
664        body.truncate(max_response_bytes);
665        return Ok((status, body, truncated));
666    }
667    Err(OmegaError::ExecutionBlocked(
668        "HttpObserver exceeded redirect limit".into(),
669    ))
670}
671
672#[cfg(all(feature = "std", feature = "ureq"))]
673fn fetch_http_sync(
674    url: Url,
675    timeout: Duration,
676    connect_timeout: Duration,
677    max_response_bytes: usize,
678) -> Result<(u16, Vec<u8>)> {
679    fetch_http_sync_with_resolver(
680        url,
681        timeout,
682        connect_timeout,
683        max_response_bytes,
684        resolve_public_http_target,
685    )
686}
687
688/// GET a URL and treat the body as observation (JSON if possible, else raw text).
689///
690/// Requires network. Only public HTTP(S) targets are allowed. Requests have a
691/// 5-second total timeout, a 2-second connect timeout, and a 1 MiB body limit
692/// by default. Redirects are revalidated individually.
693#[cfg(feature = "std")]
694#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
695#[allow(dead_code)]
696pub struct HttpObserver {
697    url: String,
698    step_counter: u64,
699    timeout: Duration,
700    connect_timeout: Duration,
701    max_response_bytes: usize,
702    #[cfg(feature = "ureq")]
703    _ureq: (),
704}
705
706#[cfg(feature = "std")]
707impl HttpObserver {
708    /// Creates a new value of this type.
709    pub fn new(url: impl Into<String>) -> Self {
710        Self {
711            url: url.into(),
712            step_counter: 0,
713            timeout: Duration::from_secs(5),
714            connect_timeout: Duration::from_secs(2),
715            max_response_bytes: 1024 * 1024,
716            #[cfg(feature = "ureq")]
717            _ureq: (),
718        }
719    }
720
721    /// Performs timeout for this type.
722    pub fn timeout(mut self, d: Duration) -> Self {
723        self.timeout = d;
724        self
725    }
726
727    /// Performs connect timeout for this type.
728    pub fn connect_timeout(mut self, d: Duration) -> Self {
729        self.connect_timeout = d;
730        self
731    }
732
733    /// Performs maximum response bytes for this type.
734    pub fn max_response_bytes(mut self, max: usize) -> Self {
735        self.max_response_bytes = max.max(1);
736        self
737    }
738}
739
740#[cfg(all(feature = "std", feature = "ureq"))]
741impl Observer for HttpObserver {
742    fn observe(&mut self) -> Result<Vec<Observation>> {
743        self.step_counter += 1;
744        let url = parse_http_url(&self.url)?;
745        let (status, body) = fetch_http_sync(
746            url,
747            self.timeout,
748            self.connect_timeout,
749            self.max_response_bytes,
750        )?;
751        let body = String::from_utf8(body).map_err(|e| {
752            OmegaError::ExecutionBlocked(format!("HttpObserver body is not UTF-8: {e}"))
753        })?;
754
755        let content = serde_json::from_str::<serde_json::Value>(&body).unwrap_or_else(|_| {
756            serde_json::json!({
757                "raw": body,
758                "http_status": status,
759                "step": self.step_counter
760            })
761        });
762
763        let confidence = if (200..300).contains(&status) {
764            0.9
765        } else {
766            0.5
767        };
768
769        Ok(vec![Observation {
770            timestamp: crate::now_utc(),
771            modality: Modality::Structured,
772            content,
773            confidence,
774            source: format!("http:{}", self.url),
775        }])
776    }
777}
778
779/// Async file observer using tokio's async filesystem.
780#[cfg(all(feature = "std", feature = "async"))]
781#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
782pub struct AsyncFileObserver {
783    path: PathBuf,
784    step_counter: u64,
785}
786
787#[cfg(all(feature = "std", feature = "async"))]
788#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
789impl AsyncFileObserver {
790    /// Creates a new value of this type.
791    pub fn new(path: impl AsRef<Path>) -> Self {
792        Self {
793            path: path.as_ref().to_path_buf(),
794            step_counter: 0,
795        }
796    }
797}
798
799#[cfg(all(feature = "std", feature = "async"))]
800#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
801impl AsyncObserver for AsyncFileObserver {
802    fn observe_async(&mut self) -> impl Future<Output = Result<Vec<Observation>>> + Send {
803        let path = self.path.clone();
804        self.step_counter += 1;
805        let step = self.step_counter;
806        async move {
807            let raw = tokio::fs::read_to_string(&path).await.map_err(|e| {
808                OmegaError::ExecutionBlocked(format!(
809                    "AsyncFileObserver failed to read {}: {e}",
810                    path.display()
811                ))
812            })?;
813
814            let content = serde_json::from_str::<serde_json::Value>(&raw).unwrap_or_else(|_| {
815                serde_json::json!({
816                    "raw": raw,
817                    "step": step
818                })
819            });
820
821            Ok(vec![Observation {
822                timestamp: crate::now_utc(),
823                modality: Modality::Structured,
824                content,
825                confidence: 0.9,
826                source: format!("async_file:{}", path.display()),
827            }])
828        }
829    }
830}
831
832/// Async directory snapshot observer using tokio's async filesystem.
833#[cfg(all(feature = "std", feature = "async"))]
834#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
835pub struct AsyncDirSnapshotObserver {
836    path: PathBuf,
837    step_counter: u64,
838    max_entries: usize,
839}
840
841#[cfg(all(feature = "std", feature = "async"))]
842#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
843impl AsyncDirSnapshotObserver {
844    /// Creates a new value of this type.
845    pub fn new(path: impl AsRef<Path>) -> Self {
846        Self {
847            path: path.as_ref().to_path_buf(),
848            step_counter: 0,
849            max_entries: 64,
850        }
851    }
852
853    /// Performs maximum entries for this type.
854    pub fn max_entries(mut self, n: usize) -> Self {
855        self.max_entries = n.max(1);
856        self
857    }
858}
859
860#[cfg(all(feature = "std", feature = "async"))]
861#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
862impl AsyncObserver for AsyncDirSnapshotObserver {
863    fn observe_async(&mut self) -> impl Future<Output = Result<Vec<Observation>>> + Send {
864        let path = self.path.clone();
865        self.step_counter += 1;
866        let step = self.step_counter;
867        let max_entries = self.max_entries;
868        async move {
869            let mut rd = tokio::fs::read_dir(&path).await.map_err(|e| {
870                OmegaError::ExecutionBlocked(format!(
871                    "AsyncDirSnapshotObserver {}: {e}",
872                    path.display()
873                ))
874            })?;
875
876            let mut entries = Vec::new();
877            while let Some(ent) = rd.next_entry().await.map_err(|e| {
878                OmegaError::ExecutionBlocked(format!("AsyncDirSnapshotObserver read entry: {e}"))
879            })? {
880                if entries.len() >= max_entries {
881                    break;
882                }
883                let meta = ent.metadata().await.ok();
884                let modified = meta.as_ref().and_then(|m| m.modified().ok()).and_then(|t| {
885                    t.duration_since(std::time::UNIX_EPOCH)
886                        .ok()
887                        .map(|d| d.as_secs())
888                });
889                entries.push(serde_json::json!({
890                    "name": ent.file_name().to_string_lossy(),
891                    "is_dir": meta.as_ref().map(|m| m.is_dir()).unwrap_or(false),
892                    "len": meta.as_ref().map(|m| m.len()).unwrap_or(0),
893                    "modified_unix": modified,
894                }));
895            }
896
897            Ok(vec![Observation {
898                timestamp: crate::now_utc(),
899                modality: Modality::Structured,
900                content: serde_json::json!({
901                    "step": step,
902                    "dir": path.display().to_string(),
903                    "entry_count": entries.len(),
904                    "entries": entries,
905                }),
906                confidence: 0.92,
907                source: format!("async_dir:{}", path.display()),
908            }])
909        }
910    }
911}
912
913#[cfg(all(feature = "std", feature = "async", feature = "reqwest"))]
914async fn fetch_http_async_with_resolver<F>(
915    mut current: Url,
916    timeout: Duration,
917    connect_timeout: Duration,
918    max_response_bytes: usize,
919    resolve: F,
920) -> Result<(u16, Vec<u8>)>
921where
922    F: Fn(&Url, Duration) -> Result<Vec<SocketAddr>> + Send + Sync + 'static,
923{
924    use futures::StreamExt;
925
926    let started = Instant::now();
927    let resolve = Arc::new(resolve);
928    for redirect_count in 0..=MAX_HTTP_REDIRECTS {
929        let remaining = timeout
930            .checked_sub(started.elapsed())
931            .filter(|remaining| !remaining.is_zero())
932            .ok_or_else(|| {
933                OmegaError::ExecutionBlocked("AsyncHttpObserver total timeout".into())
934            })?;
935        let resolver = Arc::clone(&resolve);
936        let url = current.clone();
937        let addresses = tokio::task::spawn_blocking(move || resolver(&url, remaining))
938            .await
939            .map_err(|_| {
940                OmegaError::ExecutionBlocked("AsyncHttpObserver DNS worker failed".into())
941            })??;
942        if addresses.is_empty() {
943            return Err(OmegaError::ExecutionBlocked(
944                "AsyncHttpObserver has no vetted target addresses".into(),
945            ));
946        }
947        let remaining = timeout
948            .checked_sub(started.elapsed())
949            .filter(|remaining| !remaining.is_zero())
950            .ok_or_else(|| {
951                OmegaError::ExecutionBlocked("AsyncHttpObserver total timeout".into())
952            })?;
953        let mut builder = reqwest::Client::builder()
954            .redirect(reqwest::redirect::Policy::none())
955            .no_proxy()
956            .connect_timeout(connect_timeout.min(remaining))
957            .timeout(remaining);
958        if let Some(host) = current.host_str() {
959            if host.parse::<IpAddr>().is_err() {
960                builder = builder.resolve_to_addrs(host, &addresses);
961            }
962        }
963        let client = builder.build().map_err(|_| {
964            OmegaError::ExecutionBlocked("AsyncHttpObserver client setup failed".into())
965        })?;
966        let response =
967            client.get(current.clone()).send().await.map_err(|_| {
968                OmegaError::ExecutionBlocked("AsyncHttpObserver request failed".into())
969            })?;
970        let status = response.status().as_u16();
971        let location = response
972            .headers()
973            .get(reqwest::header::LOCATION)
974            .map(|value| {
975                value.to_str().map(str::to_owned).map_err(|_| {
976                    OmegaError::ExecutionBlocked(
977                        "AsyncHttpObserver redirect location is invalid".into(),
978                    )
979                })
980            })
981            .transpose()?;
982        if let Some(next) = redirected_http_url(&current, status, location.as_deref())? {
983            if redirect_count == MAX_HTTP_REDIRECTS {
984                return Err(OmegaError::ExecutionBlocked(
985                    "AsyncHttpObserver exceeded redirect limit".into(),
986                ));
987            }
988            current = next;
989            continue;
990        }
991
992        if response
993            .content_length()
994            .is_some_and(|length| length > max_response_bytes as u64)
995        {
996            return Err(OmegaError::ExecutionBlocked(
997                "AsyncHttpObserver response body exceeds configured limit".into(),
998            ));
999        }
1000        let mut stream = response.bytes_stream();
1001        let mut body = Vec::with_capacity(max_response_bytes.min(8192));
1002        while let Some(chunk) = stream.next().await {
1003            let chunk = chunk.map_err(|_| {
1004                OmegaError::ExecutionBlocked("AsyncHttpObserver body read failed".into())
1005            })?;
1006            if body.len().saturating_add(chunk.len()) > max_response_bytes {
1007                return Err(OmegaError::ExecutionBlocked(
1008                    "AsyncHttpObserver response body exceeds configured limit".into(),
1009                ));
1010            }
1011            body.extend_from_slice(&chunk);
1012        }
1013        return Ok((status, body));
1014    }
1015    Err(OmegaError::ExecutionBlocked(
1016        "AsyncHttpObserver exceeded redirect limit".into(),
1017    ))
1018}
1019
1020#[cfg(all(feature = "std", feature = "async", feature = "reqwest"))]
1021async fn fetch_http_async(
1022    url: Url,
1023    timeout: Duration,
1024    connect_timeout: Duration,
1025    max_response_bytes: usize,
1026) -> Result<(u16, Vec<u8>)> {
1027    fetch_http_async_with_resolver(
1028        url,
1029        timeout,
1030        connect_timeout,
1031        max_response_bytes,
1032        resolve_public_http_target,
1033    )
1034    .await
1035}
1036
1037/// Async HTTP observer using reqwest with the same address and resource limits
1038/// as [`HttpObserver`].
1039#[cfg(all(feature = "std", feature = "async"))]
1040#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
1041pub struct AsyncHttpObserver {
1042    url: String,
1043    step_counter: u64,
1044    timeout: Duration,
1045    connect_timeout: Duration,
1046    max_response_bytes: usize,
1047}
1048
1049#[cfg(all(feature = "std", feature = "async"))]
1050#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
1051impl AsyncHttpObserver {
1052    /// Creates a new value of this type.
1053    pub fn new(url: impl Into<String>) -> Self {
1054        Self {
1055            url: url.into(),
1056            step_counter: 0,
1057            timeout: Duration::from_secs(5),
1058            connect_timeout: Duration::from_secs(2),
1059            max_response_bytes: 1024 * 1024,
1060        }
1061    }
1062
1063    /// Performs timeout for this type.
1064    pub fn timeout(mut self, d: Duration) -> Self {
1065        self.timeout = d;
1066        self
1067    }
1068
1069    /// Performs connect timeout for this type.
1070    pub fn connect_timeout(mut self, d: Duration) -> Self {
1071        self.connect_timeout = d;
1072        self
1073    }
1074
1075    /// Performs maximum response bytes for this type.
1076    pub fn max_response_bytes(mut self, max: usize) -> Self {
1077        self.max_response_bytes = max.max(1);
1078        self
1079    }
1080}
1081
1082#[cfg(all(feature = "std", feature = "async"))]
1083#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
1084impl AsyncObserver for AsyncHttpObserver {
1085    fn observe_async(&mut self) -> impl Future<Output = Result<Vec<Observation>>> + Send {
1086        let url = self.url.clone();
1087        self.step_counter += 1;
1088        let step = self.step_counter;
1089        let timeout = self.timeout;
1090        let connect_timeout = self.connect_timeout;
1091        let max_response_bytes = self.max_response_bytes;
1092        async move {
1093            let parsed_url = parse_http_url(&url)?;
1094            let (status, body) =
1095                fetch_http_async(parsed_url, timeout, connect_timeout, max_response_bytes).await?;
1096            let body = String::from_utf8(body).map_err(|e| {
1097                OmegaError::ExecutionBlocked(format!("AsyncHttpObserver body is not UTF-8: {e}"))
1098            })?;
1099            let content = serde_json::from_str::<serde_json::Value>(&body).unwrap_or_else(|_| {
1100                serde_json::json!({
1101                    "raw": body,
1102                    "http_status": status,
1103                    "step": step
1104                })
1105            });
1106            let confidence = if (200..300).contains(&status) {
1107                0.9
1108            } else {
1109                0.5
1110            };
1111            Ok(vec![Observation {
1112                timestamp: crate::now_utc(),
1113                modality: Modality::Structured,
1114                content,
1115                confidence,
1116                source: format!("async_http:{}", url),
1117            }])
1118        }
1119    }
1120}
1121
1122#[cfg(test)]
1123mod tests {
1124    use super::*;
1125    use std::env::temp_dir;
1126
1127    #[cfg(any(feature = "ureq", all(feature = "async", feature = "reqwest")))]
1128    fn test_response(
1129        status: &str,
1130        headers: &str,
1131        body: &str,
1132        delay: Duration,
1133    ) -> (String, Duration) {
1134        (
1135            format!(
1136                "HTTP/1.1 {status}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
1137                body.len()
1138            ),
1139            delay,
1140        )
1141    }
1142
1143    #[cfg(any(feature = "ureq", all(feature = "async", feature = "reqwest")))]
1144    fn start_test_http_server(
1145        responses: Vec<(String, Duration)>,
1146    ) -> (SocketAddr, std::thread::JoinHandle<()>) {
1147        use std::io::{Read, Write};
1148        use std::net::TcpListener;
1149
1150        let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
1151        let address = listener.local_addr().unwrap();
1152        let thread = std::thread::spawn(move || {
1153            for (response, delay) in responses {
1154                let (mut stream, _) = listener.accept().unwrap();
1155                let mut request = [0u8; 4096];
1156                let _ = stream.read(&mut request);
1157                let (headers, body) = response.split_once("\r\n\r\n").unwrap();
1158                stream.write_all(headers.as_bytes()).unwrap();
1159                stream.write_all(b"\r\n\r\n").unwrap();
1160                stream.flush().unwrap();
1161                if !delay.is_zero() {
1162                    std::thread::sleep(delay);
1163                }
1164                stream.write_all(body.as_bytes()).unwrap();
1165                stream.flush().unwrap();
1166            }
1167        });
1168        (address, thread)
1169    }
1170
1171    #[cfg(any(feature = "ureq", all(feature = "async", feature = "reqwest")))]
1172    fn chunked_test_response(body: &str) -> (String, Duration) {
1173        (
1174            format!(
1175                "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n{:x}\r\n{}\r\n0\r\n\r\n",
1176                body.len(), body
1177            ),
1178            Duration::ZERO,
1179        )
1180    }
1181
1182    #[cfg(feature = "ureq")]
1183    #[test]
1184    fn http_target_policy_rejects_private_reserved_and_credential_urls() {
1185        for address in [
1186            "0.0.0.0",
1187            "10.0.0.1",
1188            "100.64.0.1",
1189            "127.0.0.1",
1190            "169.254.169.254",
1191            "172.16.0.1",
1192            "192.168.1.1",
1193            "198.18.0.1",
1194            "224.0.0.1",
1195            "240.0.0.1",
1196            "::1",
1197            "fd00::1",
1198            "fe80::1",
1199            "2001:db8::1",
1200            "2002::1",
1201        ] {
1202            assert!(!is_public_ip(address.parse().unwrap()), "{address}");
1203        }
1204        for address in ["1.1.1.1", "8.8.8.8", "2606:4700:4700::1111"] {
1205            assert!(is_public_ip(address.parse().unwrap()), "{address}");
1206        }
1207        for raw in [
1208            "http://127.0.0.1/",
1209            "http://169.254.169.254/latest/meta-data/",
1210            "http://[::1]/",
1211        ] {
1212            let url = parse_http_url(raw).unwrap();
1213            assert!(
1214                resolve_public_http_target(&url, Duration::from_secs(1)).is_err(),
1215                "{raw}"
1216            );
1217        }
1218        assert!(parse_http_url("file:///etc/passwd").is_err());
1219        assert!(parse_http_url("http://user:password@example.com/").is_err());
1220    }
1221
1222    #[cfg(any(feature = "ureq", all(feature = "async", feature = "reqwest")))]
1223    #[test]
1224    fn http_dns_lookup_obeys_deadline_and_releases_bounded_worker() {
1225        use std::sync::atomic::Ordering;
1226
1227        let baseline = ACTIVE_HTTP_DNS_LOOKUPS.load(Ordering::Acquire);
1228        let (started_tx, started_rx) = std::sync::mpsc::channel();
1229        let result = bounded_http_dns_lookup(Duration::from_millis(10), move || {
1230            let _ = started_tx.send(());
1231            std::thread::sleep(Duration::from_millis(50));
1232            Ok(Vec::new())
1233        });
1234        assert!(result.is_err());
1235        started_rx
1236            .recv_timeout(Duration::from_secs(1))
1237            .expect("DNS worker should start");
1238
1239        let deadline = Instant::now() + Duration::from_secs(1);
1240        while ACTIVE_HTTP_DNS_LOOKUPS.load(Ordering::Acquire) > baseline
1241            && Instant::now() < deadline
1242        {
1243            std::thread::sleep(Duration::from_millis(1));
1244        }
1245        assert_eq!(ACTIVE_HTTP_DNS_LOOKUPS.load(Ordering::Acquire), baseline);
1246    }
1247
1248    #[cfg(all(feature = "std", feature = "async", feature = "reqwest"))]
1249    #[tokio::test(flavor = "current_thread")]
1250    async fn async_http_dns_lookup_does_not_block_runtime_timers() {
1251        let (address, server) =
1252            start_test_http_server(vec![test_response("200 OK", "", "ok", Duration::ZERO)]);
1253        let dns_delay = Duration::from_millis(400);
1254        let dns_started = std::sync::Arc::new(std::sync::Mutex::new(None));
1255        let started = std::sync::Arc::clone(&dns_started);
1256        let request = tokio::spawn(fetch_http_async_with_resolver(
1257            Url::parse("http://safe.example/slow-dns").unwrap(),
1258            Duration::from_secs(2),
1259            Duration::from_millis(300),
1260            1024,
1261            move |_url, _remaining| {
1262                *started.lock().unwrap() = Some(Instant::now());
1263                std::thread::sleep(dns_delay);
1264                Ok(vec![address])
1265            },
1266        ));
1267
1268        let dns_started_at = loop {
1269            if let Some(started_at) = *dns_started.lock().unwrap() {
1270                break started_at;
1271            }
1272            tokio::time::sleep(Duration::from_millis(1)).await;
1273        };
1274        tokio::time::sleep(Duration::from_millis(20)).await;
1275        assert!(
1276            Instant::now().duration_since(dns_started_at) < dns_delay / 2,
1277            "runtime timer should progress while the DNS resolver is blocked"
1278        );
1279
1280        let (status, body) = request.await.unwrap().unwrap();
1281        assert_eq!(status, 200);
1282        assert_eq!(body, b"ok");
1283        server.join().unwrap();
1284    }
1285
1286    #[cfg(any(feature = "ureq", all(feature = "async", feature = "reqwest")))]
1287    #[test]
1288    fn http_redirect_refuses_https_downgrade() {
1289        let current = Url::parse("https://example.com/start").unwrap();
1290        assert!(redirected_http_url(&current, 307, Some("http://example.com/final")).is_err());
1291    }
1292
1293    #[cfg(feature = "ureq")]
1294    #[test]
1295    fn http_redirect_is_revalidated_before_following() {
1296        let (address, server) = start_test_http_server(vec![test_response(
1297            "302 Found",
1298            "Location: http://127.0.0.1:1/private\r\n",
1299            "",
1300            Duration::ZERO,
1301        )]);
1302        let calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1303        let seen = calls.clone();
1304        let result = fetch_http_sync_with_resolver(
1305            Url::parse("http://safe.example/start").unwrap(),
1306            Duration::from_secs(2),
1307            Duration::from_millis(300),
1308            1024,
1309            move |url, remaining| {
1310                seen.lock().unwrap().push(url.to_string());
1311                if url.host_str() == Some("safe.example") {
1312                    Ok(vec![address])
1313                } else {
1314                    resolve_public_http_target(url, remaining)
1315                }
1316            },
1317        );
1318        assert!(result.is_err());
1319        let calls = calls.lock().unwrap();
1320        assert_eq!(calls.len(), 2, "each redirect target must be revalidated");
1321        assert!(calls[1].contains("127.0.0.1"));
1322        drop(calls);
1323        server.join().unwrap();
1324    }
1325
1326    #[cfg(feature = "ureq")]
1327    #[test]
1328    fn http_redirects_are_followed_only_after_each_safe_validation() {
1329        let (address, server) = start_test_http_server(vec![
1330            test_response("302 Found", "Location: /final\r\n", "", Duration::ZERO),
1331            test_response("200 OK", "", "ok", Duration::ZERO),
1332        ]);
1333        let calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
1334        let seen = calls.clone();
1335        let (status, body) = fetch_http_sync_with_resolver(
1336            Url::parse("http://safe.example/start").unwrap(),
1337            Duration::from_secs(2),
1338            Duration::from_millis(300),
1339            16,
1340            move |url, _remaining| {
1341                seen.lock().unwrap().push(url.path().to_owned());
1342                Ok(vec![address])
1343            },
1344        )
1345        .unwrap();
1346        assert_eq!(status, 200);
1347        assert_eq!(body, b"ok");
1348        assert_eq!(*calls.lock().unwrap(), vec!["/start", "/final"]);
1349        server.join().unwrap();
1350    }
1351
1352    #[cfg(feature = "ureq")]
1353    #[test]
1354    fn http_response_body_limit_and_total_timeout_are_enforced() {
1355        let (address, server) = start_test_http_server(vec![chunked_test_response("abcdef")]);
1356        let result = fetch_http_sync_with_resolver(
1357            Url::parse("http://safe.example/large").unwrap(),
1358            Duration::from_secs(2),
1359            Duration::from_millis(300),
1360            5,
1361            move |_, _remaining| Ok(vec![address]),
1362        );
1363        assert!(result.is_err());
1364        server.join().unwrap();
1365
1366        let (address, server) = start_test_http_server(vec![test_response(
1367            "200 OK",
1368            "",
1369            "slow",
1370            Duration::from_millis(300),
1371        )]);
1372        let result = fetch_http_sync_with_resolver(
1373            Url::parse("http://safe.example/slow").unwrap(),
1374            Duration::from_millis(100),
1375            Duration::from_millis(100),
1376            16,
1377            move |_, _remaining| Ok(vec![address]),
1378        );
1379        assert!(result.is_err());
1380        server.join().unwrap();
1381    }
1382
1383    #[cfg(all(feature = "std", feature = "async", feature = "reqwest"))]
1384    #[tokio::test]
1385    async fn async_http_redirect_and_streaming_body_limit_are_enforced() {
1386        let (address, server) = start_test_http_server(vec![test_response(
1387            "302 Found",
1388            "Location: http://127.0.0.1:1/private\r\n",
1389            "",
1390            Duration::ZERO,
1391        )]);
1392        let result = fetch_http_async_with_resolver(
1393            Url::parse("http://safe.example/start").unwrap(),
1394            Duration::from_secs(2),
1395            Duration::from_millis(300),
1396            1024,
1397            move |url, remaining| {
1398                if url.host_str() == Some("safe.example") {
1399                    Ok(vec![address])
1400                } else {
1401                    resolve_public_http_target(url, remaining)
1402                }
1403            },
1404        )
1405        .await;
1406        assert!(result.is_err());
1407        server.join().unwrap();
1408
1409        let (address, server) = start_test_http_server(vec![chunked_test_response("abcdef")]);
1410        let result = fetch_http_async_with_resolver(
1411            Url::parse("http://safe.example/large").unwrap(),
1412            Duration::from_secs(2),
1413            Duration::from_millis(300),
1414            5,
1415            move |_, _remaining| Ok(vec![address]),
1416        )
1417        .await;
1418        assert!(result.is_err());
1419        server.join().unwrap();
1420
1421        let (address, server) = start_test_http_server(vec![test_response(
1422            "200 OK",
1423            "",
1424            "slow",
1425            Duration::from_millis(200),
1426        )]);
1427        let result = fetch_http_async_with_resolver(
1428            Url::parse("http://safe.example/slow").unwrap(),
1429            Duration::from_millis(50),
1430            Duration::from_millis(50),
1431            16,
1432            move |_, _remaining| Ok(vec![address]),
1433        )
1434        .await;
1435        assert!(result.is_err());
1436        server.join().unwrap();
1437    }
1438
1439    #[test]
1440    fn dir_snapshot_sees_file() {
1441        let dir = temp_dir().join(format!("omega-dir-{}", crate::new_uuid()));
1442        std::fs::create_dir_all(&dir).unwrap();
1443        std::fs::write(dir.join("a.txt"), b"hi").unwrap();
1444        let mut obs = DirSnapshotObserver::new(&dir);
1445        let v = obs.observe().unwrap();
1446        assert_eq!(v.len(), 1);
1447        let count = v[0].content["entry_count"].as_u64().unwrap();
1448        assert!(count >= 1);
1449        let _ = std::fs::remove_dir_all(&dir);
1450    }
1451
1452    #[test]
1453    #[cfg(all(feature = "std", feature = "async"))]
1454    fn async_adapter_can_observe_repeatedly() {
1455        let runtime = tokio::runtime::Runtime::new().unwrap();
1456        runtime.block_on(async {
1457            let mut observer = AsyncObserverAdapter::new(MultiModalObserver::new());
1458            for expected_step in 1..=2 {
1459                let observations = observer.observe_async().await.unwrap();
1460                assert_eq!(observations[0].content["step"], expected_step);
1461            }
1462            assert_eq!(observer.into_inner().step_counter, 2);
1463        });
1464    }
1465}