stygian-graph 0.14.1

High-performance graph-based web scraping engine with AI extraction, multi-modal support, and anti-bot capabilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! Fallback chain service adapter.
//!
//! Implements [`crate::ports::ScrapingService`] by trying a prioritised list of inner services
//! with per-service circuit breakers.  When a service's circuit is **Open** or
//! its execution fails, the chain automatically moves to the next lower-priority
//! service.
//!
//! # Behaviour
//!
//! 1. Services are tried in registration order (index 0 = highest priority).
//! 2. A service is **skipped** when its circuit breaker is [`crate::ports::CircuitState::Open`]
//!    and the reset timeout has not yet elapsed.  The chain then probes it once
//!    the timeout passes (half-open probe).
//! 3. On **success** the corresponding circuit breaker records the success and the
//!    result is returned immediately — no further services are tried.
//! 4. On **failure** the circuit breaker records the failure and the next service
//!    is tried.
//! 5. If every service is exhausted the last error is propagated.
//!
//! # Example
//!
//! ```
//! use std::sync::Arc;
//! use std::time::Duration;
//! use stygian_graph::adapters::fallback::FallbackChainService;
//! use stygian_graph::adapters::noop::NoopService;
//! use stygian_graph::adapters::resilience::CircuitBreakerImpl;
//!
//! let chain = FallbackChainService::builder()
//!     .add(Arc::new(NoopService), CircuitBreakerImpl::new(3, Duration::from_secs(30)))
//!     .named("primary-with-plugin-fallback")
//!     .build();
//! ```

use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use tracing::{debug, info, warn};

use crate::adapters::resilience::CircuitBreakerImpl;
use crate::domain::error::{Result, ServiceError, StygianError};
use crate::ports::{CircuitBreaker, CircuitState, ScrapingService, ServiceInput, ServiceOutput};

// ── Chain entry ───────────────────────────────────────────────────────────────

/// A single link in the fallback chain: a service paired with its circuit breaker.
struct ChainEntry {
    service: Arc<dyn ScrapingService>,
    breaker: Arc<CircuitBreakerImpl>,
}

// ── FallbackChainService ──────────────────────────────────────────────────────

/// A [`ScrapingService`] that tries multiple inner services in priority order,
/// automatically routing around open circuit breakers and failed services.
///
/// Construct via [`FallbackChainService::builder()`].
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use std::time::Duration;
/// use stygian_graph::adapters::fallback::FallbackChainService;
/// use stygian_graph::adapters::noop::NoopService;
/// use stygian_graph::adapters::resilience::CircuitBreakerImpl;
/// use stygian_graph::ports::ScrapingService;
///
/// let chain = FallbackChainService::builder()
///     .add(Arc::new(NoopService), CircuitBreakerImpl::new(5, Duration::from_secs(60)))
///     .build();
///
/// assert_eq!(chain.name(), "fallback-chain");
/// ```
pub struct FallbackChainService {
    entries: Vec<ChainEntry>,
    name: &'static str,
}

impl FallbackChainService {
    /// Return a [`FallbackChainBuilder`] for ergonomic construction.
    ///
    /// # Example
    ///
    /// ```
    /// use stygian_graph::adapters::fallback::FallbackChainService;
    ///
    /// let builder = FallbackChainService::builder();
    /// ```
    #[must_use]
    pub const fn builder() -> FallbackChainBuilder {
        FallbackChainBuilder::new()
    }

    /// Return the number of services in this chain.
    ///
    /// # Example
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::time::Duration;
    /// use stygian_graph::adapters::fallback::FallbackChainService;
    /// use stygian_graph::adapters::noop::NoopService;
    /// use stygian_graph::adapters::resilience::CircuitBreakerImpl;
    ///
    /// let chain = FallbackChainService::builder()
    ///     .add(Arc::new(NoopService), CircuitBreakerImpl::new(3, Duration::from_secs(30)))
    ///     .add(Arc::new(NoopService), CircuitBreakerImpl::new(3, Duration::from_secs(30)))
    ///     .build();
    ///
    /// assert_eq!(chain.len(), 2);
    /// ```
    #[must_use]
    pub const fn len(&self) -> usize {
        self.entries.len()
    }

    /// Return `true` when no services are registered.
    ///
    /// An empty chain always returns [`ServiceError::Unavailable`].
    ///
    /// # Example
    ///
    /// ```
    /// use stygian_graph::adapters::fallback::FallbackChainService;
    ///
    /// let chain = FallbackChainService::builder().build();
    /// assert!(chain.is_empty());
    /// ```
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

#[async_trait]
impl ScrapingService for FallbackChainService {
    /// Execute the fallback chain.
    ///
    /// Tries each registered service in order, respecting circuit breaker state.
    /// Returns the first successful result, or the last error if all services fail.
    async fn execute(&self, input: ServiceInput) -> Result<ServiceOutput> {
        let mut last_err: Option<StygianError> = None;

        for (idx, entry) in self.entries.iter().enumerate() {
            let state = entry.breaker.state();

            // Skip services whose circuit is Open and hasn't timed out yet.
            if state == CircuitState::Open {
                if !entry.breaker.attempt_reset() {
                    debug!(
                        service = entry.service.name(),
                        chain = self.name,
                        idx,
                        "circuit open — skipping service in fallback chain"
                    );
                    continue;
                }
                debug!(
                    service = entry.service.name(),
                    chain = self.name,
                    idx,
                    "circuit half-open — probing service"
                );
            }

            debug!(
                service = entry.service.name(),
                chain = self.name,
                idx,
                url = %input.url,
                "fallback chain: attempting service"
            );

            match entry.service.execute(input.clone()).await {
                Ok(output) => {
                    entry.breaker.record_success();
                    info!(
                        service = entry.service.name(),
                        chain = self.name,
                        idx,
                        "fallback chain: service succeeded"
                    );
                    return Ok(output);
                }
                Err(e) => {
                    entry.breaker.record_failure();
                    warn!(
                        service = entry.service.name(),
                        chain = self.name,
                        idx,
                        error = %e,
                        "fallback chain: service failed — advancing to next"
                    );
                    last_err = Some(e);
                }
            }
        }

        Err(last_err.unwrap_or_else(|| {
            StygianError::Service(ServiceError::Unavailable(format!(
                "fallback chain '{}' exhausted: no services registered or available",
                self.name
            )))
        }))
    }

    fn name(&self) -> &'static str {
        self.name
    }
}

// ── FallbackChainBuilder ──────────────────────────────────────────────────────

/// Builder for [`FallbackChainService`].
///
/// Services are tried in the order they are added.  Add the highest-priority
/// (cheapest / most reliable) service first; add the plugin extraction adapter
/// last as the final fallback.
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use std::time::Duration;
/// use stygian_graph::adapters::fallback::FallbackChainBuilder;
/// use stygian_graph::adapters::noop::NoopService;
/// use stygian_graph::adapters::resilience::CircuitBreakerImpl;
/// use stygian_graph::ports::ScrapingService;
///
/// let chain = FallbackChainBuilder::new()
///     .add(Arc::new(NoopService), CircuitBreakerImpl::new(5, Duration::from_secs(60)))
///     .add(Arc::new(NoopService), CircuitBreakerImpl::new(3, Duration::from_secs(30)))
///     .named("http-to-plugin")
///     .build();
///
/// assert_eq!(chain.len(), 2);
/// assert_eq!(chain.name(), "http-to-plugin");
/// ```
pub struct FallbackChainBuilder {
    entries: Vec<ChainEntry>,
    name: &'static str,
}

impl FallbackChainBuilder {
    /// Create an empty builder with the default name `"fallback-chain"`.
    ///
    /// # Example
    ///
    /// ```
    /// use stygian_graph::adapters::fallback::FallbackChainBuilder;
    ///
    /// let builder = FallbackChainBuilder::new();
    /// ```
    #[must_use]
    pub const fn new() -> Self {
        Self {
            entries: Vec::new(),
            name: "fallback-chain",
        }
    }

    /// Add a service and its dedicated circuit breaker (highest to lowest priority).
    ///
    /// # Arguments
    ///
    /// * `service` — The [`ScrapingService`] to add.
    /// * `breaker` — A [`CircuitBreakerImpl`] configured for this specific service.
    ///
    /// # Example
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::time::Duration;
    /// use stygian_graph::adapters::fallback::FallbackChainBuilder;
    /// use stygian_graph::adapters::noop::NoopService;
    /// use stygian_graph::adapters::resilience::CircuitBreakerImpl;
    ///
    /// let builder = FallbackChainBuilder::new()
    ///     .add(Arc::new(NoopService), CircuitBreakerImpl::new(5, Duration::from_secs(60)));
    /// ```
    #[must_use]
    pub fn add(mut self, service: Arc<dyn ScrapingService>, breaker: CircuitBreakerImpl) -> Self {
        self.entries.push(ChainEntry {
            service,
            breaker: Arc::new(breaker),
        });
        self
    }

    /// Override the static name reported by [`ScrapingService::name`].
    ///
    /// # Example
    ///
    /// ```
    /// use stygian_graph::adapters::fallback::FallbackChainBuilder;
    /// use stygian_graph::ports::ScrapingService;
    ///
    /// let chain = FallbackChainBuilder::new().named("http-to-plugin-fallback").build();
    /// assert_eq!(chain.name(), "http-to-plugin-fallback");
    /// ```
    #[must_use]
    pub const fn named(mut self, name: &'static str) -> Self {
        self.name = name;
        self
    }

    /// Build the [`FallbackChainService`].
    ///
    /// An empty chain (no services added) is valid but will immediately return
    /// [`ServiceError::Unavailable`] on every call.
    ///
    /// # Example
    ///
    /// ```
    /// use stygian_graph::adapters::fallback::FallbackChainBuilder;
    ///
    /// let chain = FallbackChainBuilder::new().build();
    /// assert!(chain.is_empty());
    /// ```
    #[must_use]
    pub fn build(self) -> FallbackChainService {
        FallbackChainService {
            entries: self.entries,
            name: self.name,
        }
    }
}

impl Default for FallbackChainBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ── Default circuit breaker parameters ───────────────────────────────────────

/// Sensible default for a production circuit breaker on a primary scraper.
///
/// Opens after **5 consecutive failures** and attempts reset after **30 seconds**.
///
/// # Example
///
/// ```
/// use stygian_graph::adapters::fallback::default_primary_breaker;
///
/// let breaker = default_primary_breaker();
/// ```
#[must_use]
pub fn default_primary_breaker() -> CircuitBreakerImpl {
    CircuitBreakerImpl::new(5, Duration::from_secs(30))
}

/// Sensible default for a production circuit breaker on a fallback scraper.
///
/// Opens after **3 consecutive failures** and attempts reset after **60 seconds**.
/// The longer reset timeout gives the fallback more time to recover since it is
/// typically a heavier operation.
///
/// # Example
///
/// ```
/// use stygian_graph::adapters::fallback::default_fallback_breaker;
///
/// let breaker = default_fallback_breaker();
/// ```
#[must_use]
pub fn default_fallback_breaker() -> CircuitBreakerImpl {
    #[allow(clippy::duration_suboptimal_units)]
    {
        CircuitBreakerImpl::new(3, Duration::from_secs(60))
    }
}

// ── Unit tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::adapters::noop::NoopService;
    use crate::domain::error::ServiceError;
    use crate::ports::{ServiceInput, ServiceOutput};
    use serde_json::json;

    // ── helper: always-failing service ────────────────────────────────────

    struct AlwaysFailService;

    #[async_trait]
    impl ScrapingService for AlwaysFailService {
        async fn execute(&self, _input: ServiceInput) -> Result<ServiceOutput> {
            Err(StygianError::Service(ServiceError::Unavailable(
                "simulated failure".into(),
            )))
        }

        fn name(&self) -> &'static str {
            "always-fail"
        }
    }

    fn make_input() -> ServiceInput {
        ServiceInput {
            url: "https://example.com".to_string(),
            params: json!({}),
        }
    }

    // ── tests ─────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_first_service_succeeds() -> Result<()> {
        let chain = FallbackChainService::builder()
            .add(
                Arc::new(NoopService),
                CircuitBreakerImpl::new(5, Duration::from_secs(30)),
            )
            .add(
                Arc::new(AlwaysFailService),
                CircuitBreakerImpl::new(5, Duration::from_secs(30)),
            )
            .build();

        let output = chain.execute(make_input()).await?;
        match output.metadata.get("service") {
            Some(service) => assert_eq!(service, "noop", "noop should win"),
            None => {
                return Err(
                    ServiceError::Unavailable("service key should exist".to_string()).into(),
                );
            }
        }
        Ok(())
    }

    #[tokio::test]
    async fn test_fallback_fires_when_primary_fails() -> Result<()> {
        let chain = FallbackChainService::builder()
            .add(
                Arc::new(AlwaysFailService),
                CircuitBreakerImpl::new(5, Duration::from_secs(30)),
            )
            .add(
                Arc::new(NoopService),
                CircuitBreakerImpl::new(5, Duration::from_secs(30)),
            )
            .named("primary-then-noop")
            .build();

        let output = chain.execute(make_input()).await?;
        match output.metadata.get("service") {
            Some(service) => assert_eq!(
                service, "noop",
                "fallback noop should win after primary failure"
            ),
            None => {
                return Err(
                    ServiceError::Unavailable("service key should exist".to_string()).into(),
                );
            }
        }
        Ok(())
    }

    #[tokio::test]
    async fn test_all_services_fail_returns_error() {
        let chain = FallbackChainService::builder()
            .add(
                Arc::new(AlwaysFailService),
                CircuitBreakerImpl::new(5, Duration::from_secs(30)),
            )
            .add(
                Arc::new(AlwaysFailService),
                CircuitBreakerImpl::new(5, Duration::from_secs(30)),
            )
            .build();

        let result = chain.execute(make_input()).await;
        assert!(result.is_err(), "all-failing chain must return error");
    }

    #[tokio::test]
    async fn test_empty_chain_returns_unavailable() {
        let chain = FallbackChainService::builder().build();
        let result = chain.execute(make_input()).await;
        assert!(
            result.is_err(),
            "empty chain must return ServiceError::Unavailable"
        );
    }

    #[tokio::test]
    async fn test_chain_name_default() {
        let chain = FallbackChainService::builder().build();
        assert_eq!(chain.name(), "fallback-chain");
    }

    #[tokio::test]
    async fn test_chain_name_custom() {
        let chain = FallbackChainService::builder()
            .named("http-to-plugin")
            .build();
        assert_eq!(chain.name(), "http-to-plugin");
    }

    #[tokio::test]
    async fn test_open_circuit_skipped_advances_to_next() -> Result<()> {
        // Breaker with threshold 1: one failure opens the circuit
        let failing_breaker = CircuitBreakerImpl::new(1, {
            #[allow(clippy::duration_suboptimal_units)]
            {
                Duration::from_secs(3600)
            } // 1 hour
        });

        // Pre-open the circuit by recording the one required failure
        failing_breaker.record_failure();
        assert_eq!(
            failing_breaker.state(),
            CircuitState::Open,
            "breaker should be open after threshold hit"
        );

        let chain = FallbackChainService::builder()
            .add(Arc::new(AlwaysFailService), failing_breaker)
            .add(
                Arc::new(NoopService),
                CircuitBreakerImpl::new(5, Duration::from_secs(30)),
            )
            .named("open-circuit-skip-test")
            .build();

        // The first service's circuit is open and the timeout is 3600s so it
        // should be skipped entirely, and noop (second) should succeed.
        let output = chain.execute(make_input()).await?;
        match output.metadata.get("service") {
            Some(service) => assert_eq!(
                service, "noop",
                "open-circuit service must be skipped; noop must serve the request"
            ),
            None => {
                return Err(
                    ServiceError::Unavailable("service key should exist".to_string()).into(),
                );
            }
        }
        Ok(())
    }

    #[tokio::test]
    async fn test_circuit_records_success_on_recovery() -> Result<()> {
        // Build a chain with two noop services
        let chain = FallbackChainService::builder()
            .add(
                Arc::new(NoopService),
                CircuitBreakerImpl::new(5, Duration::from_secs(30)),
            )
            .build();

        // Execute twice — both should succeed and circuit stays closed
        chain.execute(make_input()).await?;
        chain.execute(make_input()).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_len_and_is_empty() {
        let empty = FallbackChainService::builder().build();
        assert!(empty.is_empty());
        assert_eq!(empty.len(), 0);

        let one = FallbackChainService::builder()
            .add(
                Arc::new(NoopService),
                CircuitBreakerImpl::new(5, Duration::from_secs(30)),
            )
            .build();
        assert!(!one.is_empty());
        assert_eq!(one.len(), 1);
    }

    #[tokio::test]
    async fn test_default_breaker_helpers() {
        let primary = default_primary_breaker();
        let fallback = default_fallback_breaker();
        assert_eq!(primary.state(), CircuitState::Closed);
        assert_eq!(fallback.state(), CircuitState::Closed);
    }
}