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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! Tier-dispatch types: escalation strategy, retry policy, WAF classifier,
//! per-domain state, and budget interfaces.
//!
//! Pure type declarations. The engine wires these in [`crate::engine`]
//! starting in Commit 1.3.
use fmt;
use Arc;
use async_trait;
use ;
use Error;
use crateCrawlError;
use crateHttpResponse;
use crateDynBypassProvider;
/// Defines the escalation chain when a tier produces a block signal.
///
/// `BrowserOnly` is the `#[default]` — preserves the pre-tier-dispatch behavior
/// of the engine: HTTP → Browser on `WafBlocked` / `Forbidden` when
/// `BrowserMode::Auto` is set, no vendor escalation.
///
/// ## Choosing a strategy
///
/// | Strategy | Best for |
/// |---|---|
/// | `None` | Diagnostic / audit crawls where you want raw HTTP errors |
/// | `BrowserOnly` | Default; JS-heavy sites where browser is already configured |
/// | `BypassFirst` | Legacy: engine auto-selects this when `bypass` is set and strategy is unset |
/// | `BypassOnly` | WAF-heavy targets without a browser backend configured |
/// | `BypassThenBrowser` | Maximum resilience: vendor bypass then headless Chrome |
///
/// # Examples
///
/// ```
/// # use crawlberg::EscalationStrategy;
/// let audit_strategy = EscalationStrategy::None;
/// let browser_strategy = EscalationStrategy::BrowserOnly;
/// let resilient_strategy = EscalationStrategy::BypassThenBrowser;
/// // Use BrowserOnly for JS-heavy sites, BypassThenBrowser for maximum resilience.
/// ```
/// Which tier produced the current attempt's outcome.
///
/// # Examples
///
/// ```
/// # use crawlberg::Tier;
/// let tier = Tier::Http;
/// match tier {
/// Tier::Http => println!("HTTP tier"),
/// Tier::Bypass => println!("Bypass tier"),
/// Tier::Browser => println!("Browser tier"),
/// // `#[non_exhaustive]`: callers outside the crate must include a wildcard
/// // so future variants do not break their match.
/// _ => println!("unknown tier"),
/// }
/// ```
/// Why the dispatcher should escalate to the next tier.
///
/// # Examples
///
/// ```
/// # use crawlberg::EscalationReason;
/// let waf_block = EscalationReason::WafBlocked {
/// vendor: "cloudflare".to_string(),
/// };
/// let soft_block = EscalationReason::SoftBlock;
/// let render = EscalationReason::RenderNeeded;
/// let unreliable = EscalationReason::OriginUnreliable;
///
/// match waf_block {
/// EscalationReason::WafBlocked { vendor } => println!("Blocked by {}", vendor),
/// EscalationReason::SoftBlock => println!("Soft block detected"),
/// EscalationReason::RenderNeeded => println!("JS render needed"),
/// EscalationReason::OriginUnreliable => println!("Origin unreachable"),
/// // `#[non_exhaustive]`: callers outside the crate must include a wildcard
/// // so future variants do not break their match.
/// _ => println!("unknown reason"),
/// }
/// ```
/// Rich context passed to [`RetryPolicy::decide`] on each attempt.
///
/// Inspired by spider-rs `AttemptOutcome`
/// (<https://github.com/spider-rs/spider> — `spider/src/retry_strategy.rs`).
/// Field set is intentionally a subset — we omit UA / fingerprint /
/// chrome_connection because those are caller (xberg-enterprise) concerns.
///
/// All fields are owned so async impls can clone or move into spawned tasks
/// without borrow-checker issues. The previous `<'a>` lifetime was incompatible
/// with policies that record outcomes to background tasks.
///
/// # Examples
///
/// ```
/// # use crawlberg::{AttemptOutcome, Tier, WafSignal};
/// # use std::sync::Arc;
/// let outcome = AttemptOutcome {
/// attempt: 0,
/// url: Arc::from("https://example.com"),
/// status: Some(403),
/// error: None,
/// waf_signal: Some(WafSignal {
/// vendor: "cloudflare".to_string(),
/// fingerprint_id: "challenge_slug".to_string(),
/// weight: 0.95,
/// }),
/// body_size: 1024,
/// content_density: 0.05,
/// bytes_transferred: Some(2048),
/// previous_tier: Tier::Http,
/// };
/// assert_eq!(outcome.status, Some(403));
/// assert_eq!(outcome.attempt, 0);
/// ```
/// Errors returned by [`WafClassifier::classify`].
///
/// `BuildError` is for classifier-internal construction problems (TOML parse
/// failures, AC matcher build failures). `ClassifyError` is for per-call
/// problems (e.g. response body decoding failures).
///
/// The engine treats both variants as `None` for dispatch purposes and logs
/// them at WARN — a misconfigured classifier does NOT crash the dispatcher.
///
/// # Examples
///
/// ```
/// # use crawlberg::WafClassifyError;
/// let build_err = WafClassifyError::BuildError("invalid toml".to_string());
/// let classify_err = WafClassifyError::ClassifyError("bad encoding".to_string());
///
/// match build_err {
/// WafClassifyError::BuildError(msg) => println!("Build failed: {}", msg),
/// WafClassifyError::ClassifyError(msg) => println!("Classify failed: {}", msg),
/// // `#[non_exhaustive]`: callers outside the crate must include a wildcard
/// // so future variants do not break their match.
/// _ => println!("other classify error"),
/// }
/// ```
/// What the dispatcher does next, returned by [`RetryPolicy::decide`].
///
/// # Examples
///
/// ```
/// # use crawlberg::{RetryDirective, EscalationReason};
/// let stop = RetryDirective::Stop;
/// let retry = RetryDirective::Retry { backoff_ms: 1000 };
/// let escalate = RetryDirective::Escalate {
/// reason: EscalationReason::SoftBlock,
/// };
///
/// match escalate {
/// RetryDirective::Stop => println!("Stop"),
/// RetryDirective::Retry { backoff_ms } => println!("Wait {}ms", backoff_ms),
/// RetryDirective::Escalate { reason } => println!("Escalate: {:?}", reason),
/// // `#[non_exhaustive]`: callers outside the crate must include a wildcard
/// // so future variants do not break their match.
/// _ => println!("other directive"),
/// }
/// ```
/// Pluggable per-attempt decision policy.
///
/// Default impl in `crate::defaults::dispatch::SimpleRetryPolicy` (Commit 1.2)
/// uses a per-error mapping with no learning. Callers can wire
/// state-backed policies (e.g. EWMA, per-domain priors) via this trait.
///
/// # Examples
///
/// ```
/// # use crawlberg::{RetryPolicy, RetryDirective, AttemptOutcome};
/// # use async_trait::async_trait;
/// # use std::fmt;
/// #[derive(Debug)]
/// struct AlwaysStop;
///
/// #[async_trait]
/// impl RetryPolicy for AlwaysStop {
/// async fn decide(&self, _outcome: &AttemptOutcome) -> RetryDirective {
/// RetryDirective::Stop
/// }
/// fn name(&self) -> &'static str {
/// "always_stop"
/// }
/// }
/// ```
/// Convenience alias for an owned, type-erased retry policy on
/// [`crate::types::CrawlConfig`].
pub type DynRetryPolicy = ;
/// Output of a WAF classifier — a single fingerprint match.
///
/// # Examples
///
/// ```
/// # use crawlberg::WafSignal;
/// let signal = WafSignal {
/// vendor: "cloudflare".to_string(),
/// fingerprint_id: "challenge_slug".to_string(),
/// weight: 0.95,
/// };
/// assert_eq!(signal.vendor, "cloudflare");
/// assert!(signal.weight > 0.9);
/// ```
/// Pluggable WAF detection.
///
/// Default impl in `crate::waf::TomlClassifier` (Commit 1.4) loads
/// `rules/waf_fingerprints.toml`, runs Aho-Corasick over the body and
/// checks response headers.
///
/// # Examples
///
/// ```
/// # use crawlberg::{WafClassifier, WafSignal, WafClassifyError};
/// # use crawlberg::http::HttpResponse;
/// # use std::fmt;
/// #[derive(Debug)]
/// struct AlwaysClean;
///
/// impl WafClassifier for AlwaysClean {
/// fn classify(&self, _response: &HttpResponse) -> Result<Option<WafSignal>, WafClassifyError> {
/// Ok(None)
/// }
/// }
/// ```
/// Convenience alias for an owned, type-erased WAF classifier.
pub type DynWafClassifier = ;
/// Recommendation returned by [`DomainStatePort::recommend`] for the next
/// fetch attempt against a domain. Generic over the backend's internal
/// model — the only data the engine needs to act on is which tier to
/// start at and how confident the backend is in that choice.
///
/// # Examples
///
/// ```
/// # use crawlberg::{DomainRecommendation, Tier};
/// let rec = DomainRecommendation {
/// starting_tier: Tier::Browser,
/// confidence: Some(0.85),
/// };
/// println!("Start at {:?} with confidence {:?}", rec.starting_tier, rec.confidence);
/// ```
/// Default `DomainRecommendation` is "no information": HTTP tier, no confidence.
/// Single fetch outcome reported to [`DomainStatePort::observe`]. The
/// backend turns these into its own state model (EWMA, rule-based,
/// histogram, etc).
///
/// # Examples
///
/// ```
/// # use crawlberg::{DomainObservation, Tier, ObservedOutcome};
/// let obs = DomainObservation::now(Tier::Http, ObservedOutcome::Success);
/// assert_eq!(obs.tier, Tier::Http);
/// assert_eq!(obs.outcome, ObservedOutcome::Success);
/// ```
/// Classification of a single fetch outcome.
///
/// # Examples
///
/// ```
/// # use crawlberg::ObservedOutcome;
/// let success = ObservedOutcome::Success;
/// let blocked = ObservedOutcome::WafBlocked {
/// vendor: "datadome".to_string(),
/// };
/// let transient = ObservedOutcome::Transient;
/// let permanent = ObservedOutcome::Permanent;
///
/// match success {
/// ObservedOutcome::Success => println!("Clean response"),
/// ObservedOutcome::WafBlocked { vendor } => println!("Blocked by {}", vendor),
/// ObservedOutcome::Transient => println!("Transient failure"),
/// ObservedOutcome::Permanent => println!("Permanent failure"),
/// // `#[non_exhaustive]`: callers outside the crate must include a wildcard
/// // so future variants do not break their match.
/// _ => println!("unknown outcome"),
/// }
/// ```
/// Persistent per-domain dispatch state.
///
/// Default impl in `crate::defaults::domain_state::EwmaDomainState`
/// (Commit 1.5) is a process-local `DashMap`. xberg-enterprise provides a
/// Postgres-backed impl in its `dispatch-postgres` crate.
///
/// The trait is generic over the observation model — self-hosters with
/// non-EWMA backends (Redis, rule-based, ML-driven) implement against
/// `DomainRecommendation` / `DomainObservation` without forced EWMA semantics.
///
/// # Examples
///
/// ```
/// # use crawlberg::{DomainStatePort, DomainRecommendation, DomainObservation, Tier};
/// # use async_trait::async_trait;
/// # use std::fmt;
/// #[derive(Debug)]
/// struct AlwaysDefault;
///
/// #[async_trait]
/// impl DomainStatePort for AlwaysDefault {
/// async fn recommend(&self, _domain: &str) -> DomainRecommendation {
/// DomainRecommendation::default()
/// }
///
/// async fn observe(&self, _domain: &str, _observation: &DomainObservation) {
/// // No-op for this example
/// }
/// }
/// ```
/// Convenience alias for an owned, type-erased domain-state backend.
pub type DynDomainStatePort = ;
/// Pluggable per-job escalation budget.
///
/// Returned `BudgetExhausted` causes the dispatcher to refuse further
/// escalation. Implementations decide whether the job degrades to the
/// cheapest tier or fails outright.
///
/// # Examples
///
/// ```
/// # use crawlberg::{EscalationBudget, BudgetExhausted};
/// # use async_trait::async_trait;
/// # use std::fmt;
/// #[derive(Debug)]
/// struct UnlimitedBudget;
///
/// #[async_trait]
/// impl EscalationBudget for UnlimitedBudget {
/// async fn try_consume(&self, _cost_cents: u32) -> Result<(), BudgetExhausted> {
/// Ok(())
/// }
/// }
/// ```
/// Convenience alias for an owned, type-erased budget.
pub type DynEscalationBudget = ;
/// Returned by [`EscalationBudget::try_consume`] when no budget remains.
///
/// # Examples
///
/// ```
/// # use crawlberg::BudgetExhausted;
/// let err = BudgetExhausted;
/// match Err::<(), _>(err) {
/// Err(BudgetExhausted) => println!("No budget"),
/// Ok(()) => println!("Budget available"),
/// }
/// ```
;
/// Bundle of pluggable dispatch components attached to [`crate::types::CrawlConfig`].
///
/// The `antibot_strategy` field accepts an optional `Arc<dyn AntibotStrategy>`.
/// Because it holds an opaque trait object it is excluded from alef-generated
/// polyglot bindings (`#[cfg_attr(alef, alef(skip))]`). Language clients that
/// need custom antibot logic must subclass or wrap `DefaultAntibotStrategy` at
/// the Rust layer and expose a language-friendly surface separately.
///
/// When `antibot_strategy` is `None` (the default), the engine's built-in
/// WAF-signal → escalation behaviour is preserved unchanged.
///
/// Move the seven Session 1 / 1.5 trait-object and config fields off
/// `CrawlConfig` into a single `Option<DispatchProfile>` field. Callers that
/// relied on `CrawlConfig.bypass.is_some()` auto-promoting the strategy to
/// `BypassFirst` must now set `strategy: EscalationStrategy::BypassFirst`
/// explicitly in this struct (Commit 1.5.12 breaking change).
///
/// # Examples
///
/// ```
/// # use crawlberg::{DispatchProfile, EscalationStrategy};
/// let profile = DispatchProfile::builder()
/// .strategy(EscalationStrategy::BypassThenBrowser)
/// .max_total_attempts(15)
/// .build();
/// assert_eq!(profile.strategy, EscalationStrategy::BypassThenBrowser);
/// assert_eq!(profile.max_total_attempts, 15);
/// ```
// `DispatchProfile` contains `Arc<dyn Trait>` fields which are `Send + Sync`.
// The `Option<DynXxx>` fields are all `Arc`-wrapped, so the struct is `Send + Sync`.
// Manual assertion to catch future regressions if a non-Send field is added.
const _: = ;