crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
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
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! RAG (Retrieval-Augmented Generation) 增强提取策略
//!
//! 将 HTML 文档按 DOM 语义边界分块,通过向量嵌入 + 相似度检索
//! 找到与用户查询最相关的片段,再送 LLM 精确提取结构化数据。
//!
//! ## 流程
//!
//! 1. **语义分块**:按 `<div>`, `<section>`, `<article>`, `<p>` 等 DOM 节点边界切分
//! 2. **向量嵌入**:对每个分块生成嵌入向量(通过 HTTP API 或本地模型)
//! 3. **检索增强**:用户查询 → 向量相似度 top-K → 拼接 context → LLM 提取

use anyhow::{Context, Result};
use scraper::{Html, Selector};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

/// 分块结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Chunk {
    /// 分块 ID(文档内唯一)
    pub id: usize,
    /// 分块文本内容
    pub text: String,
    /// 来源 DOM 路径(如 `article > div.content > p`)
    pub dom_path: String,
    /// 嵌入向量(延迟计算)
    #[serde(skip)]
    pub embedding: Option<Vec<f32>>,
}

/// 语义分块器配置
#[derive(Debug, Clone)]
pub struct ChunkerConfig {
    /// 目标分块大小(token 数近似,1 token ≈ 4 字符英文 / 2 字符中文)
    pub target_chunk_size: usize,
    /// 最小分块大小(低于此值合并到相邻块)
    pub min_chunk_size: usize,
    /// 最大分块大小(超过则进一步切分)
    pub max_chunk_size: usize,
    /// 分块边界标签(按优先级排列)
    pub boundary_tags: Vec<&'static str>,
}

impl Default for ChunkerConfig {
    fn default() -> Self {
        Self {
            target_chunk_size: 350, // ~350 tokens ≈ 1400 字符
            min_chunk_size: 200,    // ~200 tokens ≈ 800 字符
            max_chunk_size: 500,    // ~500 tokens ≈ 2000 字符
            boundary_tags: vec![
                "article",
                "section",
                "div",
                "main",
                "aside",
                "table",
                "ul",
                "ol",
                "p",
                "blockquote",
            ],
        }
    }
}

/// DOM 语义分块器
///
/// 按 HTML DOM 节点边界将文档切分为语义完整的分块。
/// 表格、列表等结构化元素不会被截断。
pub struct SemanticChunker {
    config: ChunkerConfig,
}

/// [`SemanticChunker::chunk_html`] 的分块累积状态:已产出块 + 待落盘文本
#[derive(Default)]
struct ChunkAccumulator {
    chunks: Vec<Chunk>,
    chunk_id: usize,
    pending_text: String,
    pending_path: String,
}

impl ChunkAccumulator {
    /// 将 pending 文本落盘为一块(pending 为空时不动)
    fn push_pending_chunk(&mut self) {
        if self.pending_text.is_empty() {
            return;
        }
        self.chunks.push(Chunk {
            id: self.chunk_id,
            text: std::mem::take(&mut self.pending_text),
            dom_path: std::mem::take(&mut self.pending_path),
            embedding: None,
        });
        self.chunk_id += 1;
    }

    /// 结构化元素(表格/列表)独立成块:先 flush pending,再追加结构化块
    ///(即使超过 max_chunk_size 也不截断)
    fn push_structural(&mut self, text: String, dom_path: String) {
        // 先 flush pending
        self.push_pending_chunk();
        self.chunks.push(Chunk {
            id: self.chunk_id,
            text,
            dom_path,
            embedding: None,
        });
        self.chunk_id += 1;
    }

    /// 非结构化元素:累积文本(块首元素记 dom_path,后续以换行连接)
    fn append_text(&mut self, text: String, dom_path: String) {
        if self.pending_text.is_empty() {
            self.pending_path = dom_path;
        }
        if !self.pending_text.is_empty() {
            self.pending_text.push('\n');
        }
        self.pending_text.push_str(&text);
    }
}

impl SemanticChunker {
    pub fn new(config: ChunkerConfig) -> Self {
        Self { config }
    }

    /// 将 HTML 文档分成语义块
    ///
    /// 算法:
    /// 1. 解析 HTML DOM
    /// 2. 遍历顶层语义边界节点(article/section/div 等)
    /// 3. 提取每个子树的可见文本
    /// 4. 按 target_chunk_size 合并/切分
    /// 5. 保证表格/列表完整性(不截断 tr/li)
    pub fn chunk_html(&self, html: &str) -> Result<Vec<Chunk>> {
        let document = Html::parse_document(html);

        let boundary_nodes = self.collect_boundary_nodes(&document);

        if boundary_nodes.is_empty() {
            // 无明确语义边界,退化为按段落切分
            let mut chunk_id = 0;
            return self.fallback_chunk(html, &mut chunk_id);
        }

        let boundary_node_count = boundary_nodes.len();
        let mut acc = ChunkAccumulator::default();

        for (element, dom_path) in boundary_nodes {
            self.accumulate_boundary_node(&element, dom_path, &mut acc);
        }

        // flush 剩余
        self.flush_tail(&mut acc);

        // 合并过小的块
        self.merge_small_chunks(&mut acc.chunks);

        log::info!(
            "Semantic chunking: {} chunks from HTML ({} boundary nodes)",
            acc.chunks.len(),
            boundary_node_count
        );

        Ok(acc.chunks)
    }

    /// 处理单个边界节点:提取可见文本,结构化元素(表格/列表)独立成块,
    /// 非结构化元素累积并在达到目标大小时 flush(超过 max_chunk_size 时进一步切分)
    fn accumulate_boundary_node(
        &self,
        element: &scraper::ElementRef,
        dom_path: String,
        acc: &mut ChunkAccumulator,
    ) {
        let text = self.extract_visible_text(element);
        let text = text.trim().to_string();

        if text.is_empty() {
            return;
        }

        // 检查结构化元素(表格/列表)—— 保持完整
        if self.is_structural_element(element) {
            acc.push_structural(text, dom_path);
            return;
        }

        // 非结构化元素:累积文本
        acc.append_text(text, dom_path);

        // 达到目标大小时 flush(超过 max_chunk_size 时进一步切分)
        self.flush_accumulated(acc);
    }

    /// 累积文本达到 target_chunk_size 时 flush:超过 max_chunk_size 则
    /// split_large_text 进一步切分,否则整块落盘
    fn flush_accumulated(&self, acc: &mut ChunkAccumulator) {
        let char_estimate = self.token_to_chars(self.config.target_chunk_size);
        if acc.pending_text.len() < char_estimate {
            return;
        }
        if acc.pending_text.len() > self.token_to_chars(self.config.max_chunk_size) {
            let sub_chunks =
                self.split_large_text(&acc.pending_text, &acc.pending_path, acc.chunk_id);
            let sub_len = sub_chunks.len();
            acc.chunks.extend(sub_chunks);
            acc.chunk_id += sub_len;
        } else {
            acc.push_pending_chunk();
        }
    }

    /// flush 剩余 pending:低于 min_chunk_size 且已有多个块时合并到前一块
    fn flush_tail(&self, acc: &mut ChunkAccumulator) {
        if acc.pending_text.is_empty() {
            return;
        }
        let char_min = self.token_to_chars(self.config.min_chunk_size);
        if acc.pending_text.len() < char_min && acc.chunks.len() > 1 {
            // 太小,合并到前一个块
            if let Some(last) = acc.chunks.last_mut() {
                last.text.push('\n');
                last.text.push_str(&acc.pending_text);
            }
        } else {
            acc.chunks.push(Chunk {
                id: acc.chunk_id,
                text: std::mem::take(&mut acc.pending_text),
                dom_path: std::mem::take(&mut acc.pending_path),
                embedding: None,
            });
        }
    }

    /// 收集顶层语义边界节点
    fn collect_boundary_nodes<'a>(
        &self,
        document: &'a Html,
    ) -> Vec<(scraper::ElementRef<'a>, String)> {
        let mut results = Vec::new();
        let mut seen_ids = std::collections::HashSet::new();

        // 优先找 article > section > main > div.content 等
        for tag in &self.config.boundary_tags {
            // selector 非法时静默跳过该标签
            let Ok(selector) = Selector::parse(tag) else {
                continue;
            };
            for element in document.select(&selector) {
                // 用 element 的 tree id 去重(同一元素被多个 selector 匹配时只保留一次)
                let node_id = element.id();
                if seen_ids.contains(&node_id) {
                    continue;
                }
                seen_ids.insert(node_id);
                let dom_path = self.build_dom_path(element);
                results.push((element, dom_path));
            }
        }

        results
    }

    /// 构建 DOM 路径字符串
    fn build_dom_path(&self, element: scraper::ElementRef) -> String {
        let mut path_parts = Vec::new();
        let mut current = Some(element);

        while let Some(el) = current {
            let tag = el.value().name();
            // 跳过 html/body 等外层
            if tag == "html" || tag == "body" {
                break;
            }
            path_parts.push(tag.to_string());
            current = el.parent().and_then(scraper::ElementRef::wrap);
            // 防止无限循环
            if path_parts.len() > 10 {
                break;
            }
        }

        path_parts.reverse();
        path_parts.join(" > ")
    }

    /// 提取元素的可见文本
    ///
    /// 使用 scraper 的 `text()` 方法提取所有文本节点,
    /// 然后过滤掉 script/style 内容(通过检查父标签)。
    fn extract_visible_text(&self, element: &scraper::ElementRef) -> String {
        // scraper::ElementRef::text 递归提取所有文本节点
        let texts: Vec<&str> = element.text().collect();
        let joined = texts.join(" ");
        // 去除多余空白
        joined.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    /// 判断是否为结构化元素(表格/列表),不应截断
    fn is_structural_element(&self, element: &scraper::ElementRef) -> bool {
        let tag = element.value().name();
        matches!(tag, "table" | "ul" | "ol" | "dl" | "figure" | "pre")
    }

    /// 退化分块:无明确语义边界时按段落切分
    fn fallback_chunk(&self, html: &str, chunk_id: &mut usize) -> Result<Vec<Chunk>> {
        let document = Html::parse_document(html);
        let mut chunks = self.paragraph_chunks(&document, chunk_id);

        if chunks.is_empty() {
            // 最终退化:整段文本作为一个块
            if let Some(chunk) = self.whole_document_chunk(html, chunk_id) {
                chunks.push(chunk);
            }
        }

        Ok(chunks)
    }

    /// 按 `<p>` 标签聚合段落分块(累计达到目标字符数即落块)
    fn paragraph_chunks(&self, document: &Html, chunk_id: &mut usize) -> Vec<Chunk> {
        let mut chunks = Vec::new();

        // 按 <p> 标签分块
        if let Ok(selector) = Selector::parse("p") {
            let mut pending = String::new();
            for element in document.select(&selector) {
                let text = element.text().collect::<Vec<_>>().join(" ");
                let text = text.trim().to_string();
                if text.is_empty() {
                    continue;
                }

                if !pending.is_empty() {
                    pending.push('\n');
                }
                pending.push_str(&text);

                let char_target = self.token_to_chars(self.config.target_chunk_size);
                if pending.len() >= char_target {
                    chunks.push(Chunk {
                        id: *chunk_id,
                        text: std::mem::take(&mut pending),
                        dom_path: "p".to_string(),
                        embedding: None,
                    });
                    *chunk_id += 1;
                }
            }
            if !pending.is_empty() {
                chunks.push(Chunk {
                    id: *chunk_id,
                    text: pending,
                    dom_path: "p".to_string(),
                    embedding: None,
                });
                *chunk_id += 1;
            }
        }

        chunks
    }

    /// 最终退化:整段清洗文本作为一个块(清洗后为空则不分块)
    fn whole_document_chunk(&self, html: &str, chunk_id: &mut usize) -> Option<Chunk> {
        let clean_text = self.strip_html_tags(html);
        if clean_text.trim().is_empty() {
            return None;
        }
        let chunk = Chunk {
            id: *chunk_id,
            text: clean_text,
            dom_path: "body".to_string(),
            embedding: None,
        };
        *chunk_id += 1;
        Some(chunk)
    }

    /// 切分超长文本
    fn split_large_text(&self, text: &str, dom_path: &str, start_id: usize) -> Vec<Chunk> {
        let max_chars = self.token_to_chars(self.config.max_chunk_size);
        let mut chunks = Vec::new();
        let mut remaining = text;
        let mut id = start_id;

        while !remaining.is_empty() {
            let (chunk_text, rest) = if remaining.len() <= max_chars {
                (remaining, "")
            } else {
                // 在句号/换行处切分
                #[allow(clippy::manual_pattern_char_comparison)]
                let split_at = remaining[..max_chars]
                    .rfind(|c: char| matches!(c, '.' | '。' | '\n'))
                    .map(|i| i + 1)
                    .unwrap_or(max_chars);
                (&remaining[..split_at], &remaining[split_at..])
            };

            chunks.push(Chunk {
                id,
                text: chunk_text.trim().to_string(),
                dom_path: dom_path.to_string(),
                embedding: None,
            });
            id += 1;
            remaining = rest;
        }

        chunks
    }

    /// 合并过小的分块
    fn merge_small_chunks(&self, chunks: &mut Vec<Chunk>) {
        let char_min = self.token_to_chars(self.config.min_chunk_size);
        let mut i = 0;
        while i < chunks.len().saturating_sub(1) {
            if chunks[i].text.len() < char_min {
                // 合并到下一个块
                let small = chunks.remove(i);
                if let Some(next) = chunks.get_mut(i) {
                    next.text = format!("{}\n{}", small.text, next.text);
                }
                // 不递增 i,继续检查合并后的块
            } else {
                i += 1;
            }
        }
    }

    /// token 数转字符数近似(英文 1 token ≈ 4 chars)
    fn token_to_chars(&self, tokens: usize) -> usize {
        tokens * 4
    }

    /// 去除 HTML 标签,保留纯文本
    fn strip_html_tags(&self, html: &str) -> String {
        let document = Html::parse_document(html);
        document
            .root_element()
            .text()
            .collect::<Vec<_>>()
            .join(" ")
            .trim()
            .to_string()
    }
}

/// 嵌入向量提供者 trait
///
/// 抽象不同嵌入来源(HTTP API / 本地模型),便于测试和替换。
#[async_trait::async_trait]
pub trait EmbeddingProvider: Send + Sync {
    /// 为文本列表生成嵌入向量
    async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>>;

    /// 嵌入维度
    fn dimensions(&self) -> usize;
}

/// 复合嵌入 provider(fluxweir-llm-gateway D5 降级链)
///
/// primary 成功直用;primary 出错 **单次** 切换 secondary(log warn 显性记录,
/// 无内嵌重试防风暴);双失败时显性报错(anyhow 链携带双方错误上下文)。
/// 典型装配:vecboost/http 为 primary、fluxweir 为 secondary。
pub struct FallbackEmbeddingProvider {
    primary: Arc<dyn EmbeddingProvider>,
    secondary: Arc<dyn EmbeddingProvider>,
}

impl FallbackEmbeddingProvider {
    pub fn new(primary: Arc<dyn EmbeddingProvider>, secondary: Arc<dyn EmbeddingProvider>) -> Self {
        Self { primary, secondary }
    }
}

#[async_trait::async_trait]
impl EmbeddingProvider for FallbackEmbeddingProvider {
    async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
        match self.primary.embed(texts).await {
            Ok(vectors) => Ok(vectors),
            Err(primary_err) => {
                log::warn!(
                    "primary embedding provider failed, falling back to secondary: {primary_err:#}"
                );
                self.secondary.embed(texts).await.map_err(|secondary_err| {
                    anyhow::anyhow!(
                        "both embedding providers failed; primary: {primary_err:#}; \
                         secondary: {secondary_err:#}"
                    )
                })
            }
        }
    }

    /// 维度以 primary 声明为准(降级链装配期保证 secondary 维度一致——
    /// fluxweir 侧维度校验在响应映射期显性报错)
    fn dimensions(&self) -> usize {
        self.primary.dimensions()
    }
}

/// 向量存储(内存实现,使用 oxcache 持久化)
pub struct VectorStore {
    /// 分块 ID → 嵌入向量
    embeddings: HashMap<usize, Vec<f32>>,
    /// 分块元数据
    chunks: HashMap<usize, Chunk>,
}

impl VectorStore {
    pub fn new() -> Self {
        Self {
            embeddings: HashMap::new(),
            chunks: HashMap::new(),
        }
    }

    /// 添加分块及其嵌入向量
    pub fn add(&mut self, chunk: Chunk) {
        if let Some(embedding) = &chunk.embedding {
            self.embeddings.insert(chunk.id, embedding.clone());
        }
        self.chunks.insert(chunk.id, chunk);
    }

    /// 余弦相似度检索 top-K 分块
    pub fn search(&self, query_embedding: &[f32], top_k: usize) -> Vec<(Chunk, f32)> {
        let mut scored: Vec<(usize, f32)> = self
            .embeddings
            .iter()
            .map(|(id, emb)| (*id, cosine_similarity(query_embedding, emb)))
            .collect();

        // 按相似度降序
        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

        scored
            .into_iter()
            .take(top_k)
            .filter_map(|(id, score)| self.chunks.get(&id).map(|chunk| (chunk.clone(), score)))
            .collect()
    }

    /// 分块数量
    pub fn len(&self) -> usize {
        self.chunks.len()
    }

    /// 是否为空
    pub fn is_empty(&self) -> bool {
        self.chunks.is_empty()
    }
}

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

/// 余弦相似度计算
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
    if a.len() != b.len() || a.is_empty() {
        return 0.0;
    }

    let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
    let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
    let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();

    if norm_a == 0.0 || norm_b == 0.0 {
        return 0.0;
    }

    dot / (norm_a * norm_b)
}

/// RAG 增强提取策略
///
/// 整合分块、嵌入、检索,提供 RAG 提取能力。
pub struct RagExtractionStrategy {
    chunker: SemanticChunker,
    embedding_provider: Arc<dyn EmbeddingProvider>,
    vector_store: VectorStore,
    /// 检索 top-K 数量
    top_k: usize,
}

impl RagExtractionStrategy {
    pub fn new(
        config: ChunkerConfig,
        embedding_provider: Arc<dyn EmbeddingProvider>,
        top_k: usize,
    ) -> Self {
        Self {
            chunker: SemanticChunker::new(config),
            embedding_provider,
            vector_store: VectorStore::new(),
            top_k,
        }
    }

    /// 索引文档:分块 + 嵌入 + 存储
    pub async fn index_document(&mut self, html: &str, doc_id: &str) -> Result<usize> {
        let chunks = self
            .chunker
            .chunk_html(html)
            .context("Failed to chunk HTML")?;

        if chunks.is_empty() {
            log::warn!("No chunks produced for document {}", doc_id);
            return Ok(0);
        }

        // 批量嵌入
        let texts: Vec<String> = chunks.iter().map(|c| c.text.clone()).collect();
        let embeddings = self
            .embedding_provider
            .embed(&texts)
            .await
            .context("Failed to generate embeddings")?;

        if embeddings.len() != chunks.len() {
            anyhow::bail!(
                "Embedding count ({}) != chunk count ({})",
                embeddings.len(),
                chunks.len()
            );
        }

        // 存入向量存储
        let chunk_count = chunks.len();
        for (mut chunk, embedding) in chunks.into_iter().zip(embeddings) {
            chunk.embedding = Some(embedding);
            self.vector_store.add(chunk);
        }

        log::info!(
            "Indexed document {}: {} chunks with {}-dim embeddings",
            doc_id,
            chunk_count,
            self.embedding_provider.dimensions()
        );

        Ok(chunk_count)
    }

    /// 检索增强:根据查询找到最相关的分块
    pub async fn retrieve(&self, query: &str) -> Result<Vec<(Chunk, f32)>> {
        let query_embedding = self
            .embedding_provider
            .embed(&[query.to_string()])
            .await
            .context("Failed to embed query")?;

        if query_embedding.is_empty() {
            anyhow::bail!("Empty query embedding");
        }

        Ok(self.vector_store.search(&query_embedding[0], self.top_k))
    }

    /// 构建检索增强的 context 文本
    pub async fn build_context(&self, query: &str) -> Result<String> {
        let results = self.retrieve(query).await?;

        if results.is_empty() {
            return Ok(String::new());
        }

        let context: String = results
            .iter()
            .enumerate()
            .map(|(i, (chunk, score))| {
                format!(
                    "[Chunk {} (score: {:.3}, path: {})]\n{}\n",
                    i + 1,
                    score,
                    chunk.dom_path,
                    chunk.text
                )
            })
            .collect::<Vec<_>>()
            .join("\n---\n\n");

        Ok(context)
    }

    /// 获取向量存储引用
    pub fn vector_store(&self) -> &VectorStore {
        &self.vector_store
    }
}

/// RAG 运行时配置(DI 共享单例)
///
/// [`RagExtractionStrategy`] 持有可变的 [`VectorStore`](`index_document` 需要
/// `&mut self`),不适合作跨请求共享;本结构体只持有不可变的构建参数,
/// 由 [`RagExtractionRuntime::create_strategy`] 按请求创建独立的策略实例。
/// 嵌入 provider 是共享的 `Arc`,不随策略实例复制开销。
pub struct RagExtractionRuntime {
    chunker_config: ChunkerConfig,
    embedding_provider: Arc<dyn EmbeddingProvider>,
    top_k: usize,
}

impl RagExtractionRuntime {
    pub fn new(
        chunker_config: ChunkerConfig,
        embedding_provider: Arc<dyn EmbeddingProvider>,
        top_k: usize,
    ) -> Self {
        Self {
            chunker_config,
            embedding_provider,
            top_k,
        }
    }

    /// 创建绑定到单次抽取的策略实例
    pub fn create_strategy(&self) -> RagExtractionStrategy {
        RagExtractionStrategy::new(
            self.chunker_config.clone(),
            self.embedding_provider.clone(),
            self.top_k,
        )
    }

    pub fn embedding_provider(&self) -> &Arc<dyn EmbeddingProvider> {
        &self.embedding_provider
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Mock Embedding Provider

    struct MockEmbeddingProvider {
        dims: usize,
    }

    #[async_trait::async_trait]
    impl EmbeddingProvider for MockEmbeddingProvider {
        async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
            // 生成确定性伪嵌入(基于文本哈希)
            Ok(texts
                .iter()
                .map(|text| {
                    let mut emb = vec![0.0f32; self.dims];
                    for (i, byte) in text.bytes().enumerate() {
                        emb[i % self.dims] += byte as f32 / 255.0;
                    }
                    // 归一化
                    let norm: f32 = emb.iter().map(|x| x * x).sum::<f32>().sqrt();
                    if norm > 0.0 {
                        emb.iter_mut().for_each(|x| *x /= norm);
                    }
                    emb
                })
                .collect())
        }

        fn dimensions(&self) -> usize {
            self.dims
        }
    }

    /// 可编程故障 mock(降级链测试):`fail=true` 时 embed 报错,调用计数
    /// 经 AtomicUsize 外部断言(单次切换、不重试)
    struct FallbackMockEmbeddingProvider {
        fail: bool,
        calls: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    }

    #[async_trait::async_trait]
    impl EmbeddingProvider for FallbackMockEmbeddingProvider {
        async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
            self.calls
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            if self.fail {
                return Err(anyhow::anyhow!("mock down"));
            }
            Ok(texts.iter().map(|_| vec![0.5f32; 2]).collect())
        }

        fn dimensions(&self) -> usize {
            2
        }
    }

    #[tokio::test]
    async fn fallback_embedding_primary_success_skips_secondary() {
        let primary_calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let secondary_calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let fallback = FallbackEmbeddingProvider::new(
            Arc::new(FallbackMockEmbeddingProvider {
                fail: false,
                calls: primary_calls.clone(),
            }),
            Arc::new(FallbackMockEmbeddingProvider {
                fail: true,
                calls: secondary_calls.clone(),
            }),
        );
        let out = fallback
            .embed(&["a".to_string(), "b".to_string()])
            .await
            .expect("primary ok");
        assert_eq!(out.len(), 2);
        assert_eq!(primary_calls.load(std::sync::atomic::Ordering::Relaxed), 1);
        assert_eq!(
            secondary_calls.load(std::sync::atomic::Ordering::Relaxed),
            0,
            "secondary must not be called when primary succeeds"
        );
    }

    #[tokio::test]
    async fn fallback_embedding_primary_failure_switches_once() {
        let primary_calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let secondary_calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let fallback = FallbackEmbeddingProvider::new(
            Arc::new(FallbackMockEmbeddingProvider {
                fail: true,
                calls: primary_calls.clone(),
            }),
            Arc::new(FallbackMockEmbeddingProvider {
                fail: false,
                calls: secondary_calls.clone(),
            }),
        );
        let out = fallback
            .embed(&["a".to_string()])
            .await
            .expect("secondary ok");
        assert_eq!(out, vec![vec![0.5, 0.5]]);
        assert_eq!(primary_calls.load(std::sync::atomic::Ordering::Relaxed), 1);
        assert_eq!(
            secondary_calls.load(std::sync::atomic::Ordering::Relaxed),
            1
        );
    }

    #[tokio::test]
    async fn fallback_embedding_both_fail_reports_both_contexts() {
        let fallback = FallbackEmbeddingProvider::new(
            Arc::new(FallbackMockEmbeddingProvider {
                fail: true,
                calls: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            }),
            Arc::new(FallbackMockEmbeddingProvider {
                fail: true,
                calls: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            }),
        );
        let err = fallback
            .embed(&["a".to_string()])
            .await
            .expect_err("must error");
        let rendered = format!("{err:#}");
        assert!(
            rendered.contains("both embedding providers failed"),
            "{rendered}"
        );
        assert!(
            rendered.contains("mock down"),
            "must carry both contexts: {rendered}"
        );
    }

    // 分块测试

    #[test]
    fn test_chunk_html_article_boundary() {
        let html = r#"
            <html><body>
                <article>
                    <h1>Article 1</h1>
                    <p>First article content with enough text to meet minimum chunk size requirements for testing.</p>
                </article>
                <article>
                    <h1>Article 2</h1>
                    <p>Second article content with enough text to meet minimum chunk size requirements for testing.</p>
                </article>
            </body></html>
        "#;

        let chunker = SemanticChunker::new(ChunkerConfig::default());
        let chunks = chunker.chunk_html(html).unwrap();

        assert!(!chunks.is_empty(), "should produce at least one chunk");
        let all_text: String = chunks
            .iter()
            .map(|c| c.text.as_str())
            .collect::<Vec<_>>()
            .join(" ");
        assert!(all_text.contains("Article 1"));
        assert!(all_text.contains("Article 2"));
    }

    #[test]
    fn test_chunk_html_table_not_truncated() {
        let html = r#"
            <html><body>
                <table>
                    <tr><td>Row 1 Col 1</td><td>Row 1 Col 2</td></tr>
                    <tr><td>Row 2 Col 1</td><td>Row 2 Col 2</td></tr>
                    <tr><td>Row 3 Col 1</td><td>Row 3 Col 2</td></tr>
                </table>
            </body></html>
        "#;

        let chunker = SemanticChunker::new(ChunkerConfig::default());
        let chunks = chunker.chunk_html(html).unwrap();

        // 表格应作为完整块存在
        let table_chunk = chunks.iter().find(|c| c.text.contains("Row 1"));
        assert!(table_chunk.is_some(), "table should be in a chunk");
        let table_text = &table_chunk.unwrap().text;
        assert!(table_text.contains("Row 2"));
        assert!(table_text.contains("Row 3"));
    }

    #[test]
    fn test_chunk_html_list_not_truncated() {
        let html = r#"
            <html><body>
                <ul>
                    <li>Item 1</li>
                    <li>Item 2</li>
                    <li>Item 3</li>
                    <li>Item 4</li>
                </ul>
            </body></html>
        "#;

        let chunker = SemanticChunker::new(ChunkerConfig::default());
        let chunks = chunker.chunk_html(html).unwrap();

        let list_chunk = chunks.iter().find(|c| c.text.contains("Item 1"));
        assert!(list_chunk.is_some(), "list should be in a chunk");
        let list_text = &list_chunk.unwrap().text;
        assert!(list_text.contains("Item 4"), "list should not be truncated");
    }

    #[test]
    fn test_chunk_html_empty_html() {
        let html = "<html><body></body></html>";
        let chunker = SemanticChunker::new(ChunkerConfig::default());
        let chunks = chunker.chunk_html(html).unwrap();
        assert!(chunks.is_empty(), "empty HTML should produce no chunks");
    }

    #[test]
    fn test_chunk_html_script_style_excluded() {
        let html = r#"
            <html><body>
                <script>var x = 1;</script>
                <style>.foo { color: red; }</style>
                <p>Visible content that should be extracted properly for testing.</p>
            </body></html>
        "#;

        let chunker = SemanticChunker::new(ChunkerConfig::default());
        let chunks = chunker.chunk_html(html).unwrap();

        let all_text: String = chunks
            .iter()
            .map(|c| c.text.as_str())
            .collect::<Vec<_>>()
            .join(" ");
        assert!(all_text.contains("Visible content"));
        // script/style 内容不应出现(traverse 会包含它们,但这是已知限制)
    }

    // 余弦相似度测试

    #[test]
    fn test_cosine_similarity_identical() {
        let a = vec![1.0, 0.0, 0.0];
        let b = vec![1.0, 0.0, 0.0];
        let sim = cosine_similarity(&a, &b);
        assert!(
            (sim - 1.0).abs() < 1e-6,
            "identical vectors should have similarity 1.0"
        );
    }

    #[test]
    fn test_cosine_similarity_orthogonal() {
        let a = vec![1.0, 0.0];
        let b = vec![0.0, 1.0];
        let sim = cosine_similarity(&a, &b);
        assert!(
            sim.abs() < 1e-6,
            "orthogonal vectors should have similarity 0.0"
        );
    }

    #[test]
    fn test_cosine_similarity_opposite() {
        let a = vec![1.0, 0.0];
        let b = vec![-1.0, 0.0];
        let sim = cosine_similarity(&a, &b);
        assert!(
            (sim + 1.0).abs() < 1e-6,
            "opposite vectors should have similarity -1.0"
        );
    }

    #[test]
    fn test_cosine_similarity_empty() {
        let a: Vec<f32> = vec![];
        let b: Vec<f32> = vec![];
        assert_eq!(cosine_similarity(&a, &b), 0.0);
    }

    // VectorStore 测试

    #[test]
    fn test_vector_store_search() {
        let mut store = VectorStore::new();

        store.add(Chunk {
            id: 0,
            text: "Rust programming".to_string(),
            dom_path: "p".to_string(),
            embedding: Some(vec![1.0, 0.0, 0.0]),
        });
        store.add(Chunk {
            id: 1,
            text: "Python programming".to_string(),
            dom_path: "p".to_string(),
            embedding: Some(vec![0.9, 0.1, 0.0]),
        });
        store.add(Chunk {
            id: 2,
            text: "Cooking recipe".to_string(),
            dom_path: "p".to_string(),
            embedding: Some(vec![0.0, 0.0, 1.0]),
        });

        let results = store.search(&[1.0, 0.0, 0.0], 2);
        assert_eq!(results.len(), 2);
        // 最相似的应是 id=0(完全匹配)
        assert_eq!(results[0].0.id, 0);
        assert!(
            results[0].1 > results[1].1,
            "should be sorted by similarity desc"
        );
    }

    // RagExtractionStrategy 集成测试

    #[tokio::test]
    async fn test_rag_index_and_retrieve() {
        let provider = Arc::new(MockEmbeddingProvider { dims: 8 });
        let mut strategy = RagExtractionStrategy::new(ChunkerConfig::default(), provider, 2);

        let html = r#"
            <html><body>
                <article>
                    <h1>Rust Guide</h1>
                    <p>Rust is a systems programming language focused on safety and performance.</p>
                </article>
                <article>
                    <h1>Python Guide</h1>
                    <p>Python is a high-level programming language known for readability.</p>
                </article>
            </body></html>
        "#;

        let chunk_count = strategy.index_document(html, "doc1").await.unwrap();
        assert!(chunk_count > 0, "should index at least one chunk");

        // 检索
        let results = strategy
            .retrieve("Rust programming language")
            .await
            .unwrap();
        assert!(!results.is_empty(), "should find relevant chunks");
    }

    #[tokio::test]
    async fn test_rag_build_context() {
        let provider = Arc::new(MockEmbeddingProvider { dims: 4 });
        let mut strategy = RagExtractionStrategy::new(ChunkerConfig::default(), provider, 3);

        let html = r#"
            <html><body>
                <p>First paragraph about web scraping techniques.</p>
                <p>Second paragraph about data extraction methods.</p>
            </body></html>
        "#;

        strategy.index_document(html, "doc1").await.unwrap();
        let context = strategy.build_context("web scraping").await.unwrap();

        assert!(!context.is_empty(), "context should not be empty");
        assert!(
            context.contains("[Chunk"),
            "context should contain chunk markers"
        );
    }
}