vecboost 0.2.0

High-performance embedding vector service written in Rust
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
// Copyright (c) 2025-2026 Kirky.X
//
// Licensed under MIT License
// See LICENSE file in the project root for full license information

#![allow(clippy::all)]

use log::{debug, warn};
use std::collections::{BTreeMap, VecDeque};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::oneshot;

use super::priority::{Priority, RequestSource};
use crate::domain::EmbedRequest;
use crate::error::VecboostError;

/// 队列请求
#[derive(Debug)]
pub struct QueuedRequest {
    /// 请求 ID
    pub request_id: String,
    /// 嵌入请求
    pub embed_request: EmbedRequest,
    /// 优先级
    pub priority: Priority,
    /// 提交时间
    pub submitted_at: Instant,
    /// 超时时间
    pub timeout: Duration,
    /// 请求来源
    pub source: RequestSource,
    /// 响应发送器
    pub response_tx: oneshot::Sender<Result<crate::domain::EmbedResponse, VecboostError>>,
}

/// 优先级请求队列
pub struct PriorityRequestQueue {
    /// 队列: Priority -> 请求队列
    queues: Arc<tokio::sync::RwLock<BTreeMap<Priority, VecDeque<QueuedRequest>>>>,
    /// 最大队列大小
    max_queue_size: usize,
    /// 当前队列大小
    current_size: Arc<AtomicUsize>,
}

impl PriorityRequestQueue {
    pub fn new(max_queue_size: usize) -> Self {
        debug!(
            "Creating PriorityRequestQueue with max_size={}",
            max_queue_size
        );

        Self {
            queues: Arc::new(tokio::sync::RwLock::new(BTreeMap::new())),
            max_queue_size,
            current_size: Arc::new(AtomicUsize::new(0)),
        }
    }

    /// 入队
    pub async fn enqueue(&self, request: QueuedRequest) -> Result<(), VecboostError> {
        // 使用原子操作确保检查和入队的原子性
        loop {
            let current_size = self.current_size.load(Ordering::Acquire);

            if current_size >= self.max_queue_size {
                return Err(VecboostError::RateLimitExceeded(
                    "Queue is full, request rejected".to_string(),
                ));
            }

            // 尝试原子递增
            match self.current_size.compare_exchange_weak(
                current_size,
                current_size + 1,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => {
                    // 成功获取槽位,继续入队
                    break;
                }
                Err(_) => {
                    // 失败,重试
                    continue;
                }
            }
        }

        let mut queues = self.queues.write().await;

        let priority = request.priority;
        let queue = queues.entry(priority).or_insert_with(VecDeque::new);
        queue.push_back(request);

        debug!(
            "Request enqueued, priority={:?}, queue_size={}",
            priority,
            self.current_size.load(Ordering::Relaxed)
        );

        Ok(())
    }

    /// 出队(按优先级,含老化机制防止低优先级饥饿)
    ///
    /// 当高优先级队列队首请求等待超过 30s 时,跳过该优先级处理下级队列,
    /// 防止低优先级请求永久饥饿。`Priority::Low` 不参与老化跳过。
    pub async fn dequeue(&self) -> Option<QueuedRequest> {
        let mut queues = self.queues.write().await;
        let now = Instant::now();
        const AGING_THRESHOLD: Duration = Duration::from_secs(30);

        // 按优先级从高到低查找
        for priority in [
            Priority::Critical,
            Priority::High,
            Priority::Normal,
            Priority::Low,
        ] {
            if let Some(queue) = queues.get_mut(&priority) {
                // 老化检查:高优先级队列队首请求已超时 → 跳到下一优先级
                if priority != Priority::Low
                    && let Some(front) = queue.front()
                    && now.duration_since(front.submitted_at) > AGING_THRESHOLD
                {
                    continue;
                }
                if let Some(request) = queue.pop_front() {
                    let new_size = self.current_size.fetch_sub(1, Ordering::Relaxed) - 1;

                    debug!(
                        "Request dequeued, priority={:?}, queue_size={}",
                        priority, new_size
                    );

                    // 清理空的队列
                    if queue.is_empty() {
                        queues.remove(&priority);
                    }

                    return Some(request);
                }
            }
        }

        None
    }

    /// 获取最高优先级
    pub async fn peek_highest_priority(&self) -> Option<Priority> {
        let queues = self.queues.read().await;

        for priority in [
            Priority::Critical,
            Priority::High,
            Priority::Normal,
            Priority::Low,
        ] {
            if let Some(queue) = queues.get(&priority) {
                if !queue.is_empty() {
                    return Some(priority);
                }
            }
        }

        None
    }

    /// 获取队列大小
    pub fn size(&self) -> usize {
        self.current_size.load(Ordering::Relaxed)
    }

    /// 清空队列
    pub async fn clear(&self) {
        let mut queues = self.queues.write().await;
        let cleared_count = queues.values().map(|q| q.len()).sum::<usize>();

        queues.clear();
        self.current_size.store(0, Ordering::Relaxed);

        warn!("Queue cleared, {} requests discarded", cleared_count);
    }

    /// 获取按优先级分组的队列大小
    pub async fn size_by_priority(&self) -> Vec<(Priority, usize)> {
        let queues = self.queues.read().await;

        queues
            .iter()
            .map(|(priority, queue)| (*priority, queue.len()))
            .collect()
    }
}

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

    #[tokio::test]
    async fn test_queue_creation() {
        let queue = PriorityRequestQueue::new(100);
        assert_eq!(queue.size(), 0);
    }

    #[tokio::test]
    async fn test_enqueue_dequeue() {
        let queue = PriorityRequestQueue::new(100);

        let (tx, _rx) = oneshot::channel();
        let request = QueuedRequest {
            request_id: "test-1".to_string(),
            embed_request: EmbedRequest {
                text: "test".to_string(),
                normalize: Some(true),
            },
            priority: Priority::Normal,
            submitted_at: Instant::now(),
            timeout: Duration::from_secs(30),
            source: RequestSource::Http {
                ip: "127.0.0.1".to_string(),
            },
            response_tx: tx,
        };

        queue.enqueue(request).await.unwrap();
        assert_eq!(queue.size(), 1);

        let dequeued = queue.dequeue().await;
        assert!(dequeued.is_some());
        assert_eq!(queue.size(), 0);
    }

    #[tokio::test]
    async fn test_priority_ordering() {
        let queue = PriorityRequestQueue::new(100);

        // 添加不同优先级的请求
        for (i, priority) in [
            Priority::Low,
            Priority::Critical,
            Priority::Normal,
            Priority::High,
        ]
        .iter()
        .enumerate()
        {
            let (tx, _rx) = oneshot::channel();
            let request = QueuedRequest {
                request_id: format!("test-{}", i),
                embed_request: EmbedRequest {
                    text: "test".to_string(),
                    normalize: Some(true),
                },
                priority: *priority,
                submitted_at: Instant::now(),
                timeout: Duration::from_secs(30),
                source: RequestSource::Http {
                    ip: "127.0.0.1".to_string(),
                },
                response_tx: tx,
            };

            queue.enqueue(request).await.unwrap();
        }

        // 验证出队顺序
        assert_eq!(queue.dequeue().await.unwrap().priority, Priority::Critical);
        assert_eq!(queue.dequeue().await.unwrap().priority, Priority::High);
        assert_eq!(queue.dequeue().await.unwrap().priority, Priority::Normal);
        assert_eq!(queue.dequeue().await.unwrap().priority, Priority::Low);
    }

    #[tokio::test]
    async fn test_queue_full() {
        let queue = PriorityRequestQueue::new(2);

        let (tx1, _rx1) = oneshot::channel();
        let request1 = QueuedRequest {
            request_id: "test-1".to_string(),
            embed_request: EmbedRequest {
                text: "test".to_string(),
                normalize: Some(true),
            },
            priority: Priority::Normal,
            submitted_at: Instant::now(),
            timeout: Duration::from_secs(30),
            source: RequestSource::Http {
                ip: "127.0.0.1".to_string(),
            },
            response_tx: tx1,
        };

        let (tx2, _rx2) = oneshot::channel();
        let request2 = QueuedRequest {
            request_id: "test-2".to_string(),
            embed_request: EmbedRequest {
                text: "test".to_string(),
                normalize: Some(true),
            },
            priority: Priority::Normal,
            submitted_at: Instant::now(),
            timeout: Duration::from_secs(30),
            source: RequestSource::Http {
                ip: "127.0.0.1".to_string(),
            },
            response_tx: tx2,
        };

        queue.enqueue(request1).await.unwrap();
        queue.enqueue(request2).await.unwrap();

        let (tx3, _rx3) = oneshot::channel();
        let request3 = QueuedRequest {
            request_id: "test-3".to_string(),
            embed_request: EmbedRequest {
                text: "test".to_string(),
                normalize: Some(true),
            },
            priority: Priority::Normal,
            submitted_at: Instant::now(),
            timeout: Duration::from_secs(30),
            source: RequestSource::Http {
                ip: "127.0.0.1".to_string(),
            },
            response_tx: tx3,
        };

        let result = queue.enqueue(request3).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_clear() {
        let queue = PriorityRequestQueue::new(100);

        // 添加一些请求
        for i in 0..10 {
            let (tx, _rx) = oneshot::channel();
            let request = QueuedRequest {
                request_id: format!("test-{}", i),
                embed_request: EmbedRequest {
                    text: "test".to_string(),
                    normalize: Some(true),
                },
                priority: Priority::Normal,
                submitted_at: Instant::now(),
                timeout: Duration::from_secs(30),
                source: RequestSource::Http {
                    ip: "127.0.0.1".to_string(),
                },
                response_tx: tx,
            };

            queue.enqueue(request).await.unwrap();
        }

        assert_eq!(queue.size(), 10);

        queue.clear().await;

        assert_eq!(queue.size(), 0);
    }

    #[tokio::test]
    async fn test_aging_prevents_low_priority_starvation() {
        let queue = PriorityRequestQueue::new(100);

        // 入队 Critical 请求(会老化)
        let (tx1, _rx1) = oneshot::channel();
        let critical_req = QueuedRequest {
            request_id: "critical-1".to_string(),
            embed_request: EmbedRequest {
                text: "test".to_string(),
                normalize: Some(true),
            },
            priority: Priority::Critical,
            submitted_at: Instant::now(),
            timeout: Duration::from_secs(60),
            source: RequestSource::Http {
                ip: "127.0.0.1".to_string(),
            },
            response_tx: tx1,
        };
        queue.enqueue(critical_req).await.unwrap();

        // 入队 Low 请求
        let (tx2, _rx2) = oneshot::channel();
        let low_req = QueuedRequest {
            request_id: "low-1".to_string(),
            embed_request: EmbedRequest {
                text: "test".to_string(),
                normalize: Some(true),
            },
            priority: Priority::Low,
            submitted_at: Instant::now(),
            timeout: Duration::from_secs(60),
            source: RequestSource::Http {
                ip: "127.0.0.1".to_string(),
            },
            response_tx: tx2,
        };
        queue.enqueue(low_req).await.unwrap();

        // 等待超过老化阈值(30s)
        tokio::time::sleep(Duration::from_secs(31)).await;

        // dequeue 应先返回 Low(Critical 已老化,跳过)
        let dequeued = queue.dequeue().await.unwrap();
        assert_eq!(
            dequeued.priority,
            Priority::Low,
            "aged Critical should be skipped, Low should be dequeued first"
        );
    }

    // ===== peek_highest_priority tests =====

    #[tokio::test]
    async fn test_peek_highest_priority_empty_queue_returns_none() {
        let queue = PriorityRequestQueue::new(100);
        let result = queue.peek_highest_priority().await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_peek_highest_priority_returns_critical() {
        let queue = PriorityRequestQueue::new(100);
        let (tx, _rx) = oneshot::channel();
        let request = QueuedRequest {
            request_id: "test-1".to_string(),
            embed_request: EmbedRequest {
                text: "test".to_string(),
                normalize: Some(true),
            },
            priority: Priority::Critical,
            submitted_at: Instant::now(),
            timeout: Duration::from_secs(30),
            source: RequestSource::Http {
                ip: "127.0.0.1".to_string(),
            },
            response_tx: tx,
        };
        queue.enqueue(request).await.unwrap();
        let result = queue.peek_highest_priority().await;
        assert_eq!(result, Some(Priority::Critical));
    }

    #[tokio::test]
    async fn test_peek_highest_priority_returns_low() {
        let queue = PriorityRequestQueue::new(100);
        let (tx, _rx) = oneshot::channel();
        let request = QueuedRequest {
            request_id: "test-1".to_string(),
            embed_request: EmbedRequest {
                text: "test".to_string(),
                normalize: Some(true),
            },
            priority: Priority::Low,
            submitted_at: Instant::now(),
            timeout: Duration::from_secs(30),
            source: RequestSource::Http {
                ip: "127.0.0.1".to_string(),
            },
            response_tx: tx,
        };
        queue.enqueue(request).await.unwrap();
        let result = queue.peek_highest_priority().await;
        assert_eq!(result, Some(Priority::Low));
    }

    #[tokio::test]
    async fn test_peek_highest_priority_after_dequeue() {
        let queue = PriorityRequestQueue::new(100);
        for priority in [Priority::High, Priority::Low] {
            let (tx, _rx) = oneshot::channel();
            let request = QueuedRequest {
                request_id: format!("test-{:?}", priority),
                embed_request: EmbedRequest {
                    text: "test".to_string(),
                    normalize: Some(true),
                },
                priority,
                submitted_at: Instant::now(),
                timeout: Duration::from_secs(30),
                source: RequestSource::Http {
                    ip: "127.0.0.1".to_string(),
                },
                response_tx: tx,
            };
            queue.enqueue(request).await.unwrap();
        }
        assert_eq!(queue.peek_highest_priority().await, Some(Priority::High));
        queue.dequeue().await.unwrap();
        assert_eq!(queue.peek_highest_priority().await, Some(Priority::Low));
        queue.dequeue().await.unwrap();
        assert!(queue.peek_highest_priority().await.is_none());
    }

    // ===== size_by_priority tests =====

    #[tokio::test]
    async fn test_size_by_priority_empty_queue() {
        let queue = PriorityRequestQueue::new(100);
        let result = queue.size_by_priority().await;
        assert!(result.is_empty());
    }

    #[tokio::test]
    async fn test_size_by_priority_single_priority() {
        let queue = PriorityRequestQueue::new(100);
        for i in 0..3 {
            let (tx, _rx) = oneshot::channel();
            let request = QueuedRequest {
                request_id: format!("test-{}", i),
                embed_request: EmbedRequest {
                    text: "test".to_string(),
                    normalize: Some(true),
                },
                priority: Priority::Normal,
                submitted_at: Instant::now(),
                timeout: Duration::from_secs(30),
                source: RequestSource::Http {
                    ip: "127.0.0.1".to_string(),
                },
                response_tx: tx,
            };
            queue.enqueue(request).await.unwrap();
        }
        let result = queue.size_by_priority().await;
        assert_eq!(result.len(), 1);
        assert_eq!(result[0], (Priority::Normal, 3));
    }

    #[tokio::test]
    async fn test_size_by_priority_multiple_priorities() {
        let queue = PriorityRequestQueue::new(100);
        let priorities_with_counts = [
            (Priority::Critical, 2),
            (Priority::High, 1),
            (Priority::Low, 3),
        ];
        for (priority, count) in priorities_with_counts {
            for i in 0..count {
                let (tx, _rx) = oneshot::channel();
                let request = QueuedRequest {
                    request_id: format!("test-{:?}-{}", priority, i),
                    embed_request: EmbedRequest {
                        text: "test".to_string(),
                        normalize: Some(true),
                    },
                    priority,
                    submitted_at: Instant::now(),
                    timeout: Duration::from_secs(30),
                    source: RequestSource::Http {
                        ip: "127.0.0.1".to_string(),
                    },
                    response_tx: tx,
                };
                queue.enqueue(request).await.unwrap();
            }
        }
        let result = queue.size_by_priority().await;
        let total: usize = result.iter().map(|(_, c)| c).sum();
        assert_eq!(total, 6);
    }

    // ===== dequeue from empty queue =====

    #[tokio::test]
    async fn test_dequeue_empty_queue_returns_none() {
        let queue = PriorityRequestQueue::new(100);
        let result = queue.dequeue().await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_dequeue_all_then_empty() {
        let queue = PriorityRequestQueue::new(100);
        let (tx, _rx) = oneshot::channel();
        let request = QueuedRequest {
            request_id: "test-1".to_string(),
            embed_request: EmbedRequest {
                text: "test".to_string(),
                normalize: Some(true),
            },
            priority: Priority::Normal,
            submitted_at: Instant::now(),
            timeout: Duration::from_secs(30),
            source: RequestSource::Http {
                ip: "127.0.0.1".to_string(),
            },
            response_tx: tx,
        };
        queue.enqueue(request).await.unwrap();
        assert!(queue.dequeue().await.is_some());
        assert!(queue.dequeue().await.is_none());
        assert_eq!(queue.size(), 0);
    }

    // ===== clear on empty queue =====

    #[tokio::test]
    async fn test_clear_empty_queue() {
        let queue = PriorityRequestQueue::new(100);
        queue.clear().await;
        assert_eq!(queue.size(), 0);
    }

    // ===== queue size tracking after operations =====

    #[tokio::test]
    async fn test_size_reflects_enqueue_and_dequeue() {
        let queue = PriorityRequestQueue::new(100);
        assert_eq!(queue.size(), 0);
        for i in 0..5 {
            let (tx, _rx) = oneshot::channel();
            let request = QueuedRequest {
                request_id: format!("test-{}", i),
                embed_request: EmbedRequest {
                    text: "test".to_string(),
                    normalize: Some(true),
                },
                priority: Priority::Normal,
                submitted_at: Instant::now(),
                timeout: Duration::from_secs(30),
                source: RequestSource::Http {
                    ip: "127.0.0.1".to_string(),
                },
                response_tx: tx,
            };
            queue.enqueue(request).await.unwrap();
        }
        assert_eq!(queue.size(), 5);
        for _ in 0..3 {
            queue.dequeue().await.unwrap();
        }
        assert_eq!(queue.size(), 2);
    }

    #[tokio::test]
    async fn test_enqueue_max_size_zero_always_rejects() {
        let queue = PriorityRequestQueue::new(0);
        let (tx, _rx) = oneshot::channel();
        let request = QueuedRequest {
            request_id: "test-1".to_string(),
            embed_request: EmbedRequest {
                text: "test".to_string(),
                normalize: Some(true),
            },
            priority: Priority::Normal,
            submitted_at: Instant::now(),
            timeout: Duration::from_secs(30),
            source: RequestSource::Http {
                ip: "127.0.0.1".to_string(),
            },
            response_tx: tx,
        };
        let result = queue.enqueue(request).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_aging_does_not_skip_low_priority() {
        let queue = PriorityRequestQueue::new(100);
        let (tx, _rx) = oneshot::channel();
        let low_req = QueuedRequest {
            request_id: "low-1".to_string(),
            embed_request: EmbedRequest {
                text: "test".to_string(),
                normalize: Some(true),
            },
            priority: Priority::Low,
            submitted_at: Instant::now(),
            timeout: Duration::from_secs(60),
            source: RequestSource::Http {
                ip: "127.0.0.1".to_string(),
            },
            response_tx: tx,
        };
        queue.enqueue(low_req).await.unwrap();
        // Low priority does NOT participate in aging skip
        let dequeued = queue.dequeue().await.unwrap();
        assert_eq!(dequeued.priority, Priority::Low);
    }
}