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

//! Tests for confers-based configuration loading (T016).
//!
//! Covers three scenarios required by the spec:
//! 1. Loading `AppConfig` from `config_minimal.toml`
//! 2. Environment variable `VECBOOST_JWT_SECRET` overriding TOML values
//! 3. Hot-reload subscribe callback via `confers::bus::InMemoryBus`

use std::io::Write;

use super::app::test_support::ENV_LOCK;
use super::app_config::AppConfig;

/// Helper: write a minimal TOML config to a temp file and return its path.
fn write_temp_toml(content: &str) -> (tempfile::TempDir, std::path::PathBuf) {
    let dir = tempfile::tempdir().expect("failed to create temp dir");
    let path = dir.path().join("test_config.toml");
    let mut file = std::fs::File::create(&path).expect("failed to create temp config file");
    file.write_all(content.as_bytes())
        .expect("failed to write temp config");
    (dir, path)
}

/// Test 1: Load `AppConfig` from `config_minimal.toml` and verify key fields.
///
/// Verifies that confers correctly deserialises the TOML file into the
/// nested `AppConfig` struct, including server port, model repo, and
/// embedding settings.
#[test]
fn test_confers_load_from_minimal_toml() {
    let toml_content = r#"
[server]
host = "127.0.0.1"
port = 9002
timeout = 30

[model]
model_repo = "BAAI/bge-m3"
use_gpu = false
batch_size = 8
expected_dimension = 1024

[embedding]
default_aggregation = "mean"
similarity_metric = "cosine"
cache_enabled = false
cache_size = 0
max_batch_size = 32

[monitoring]
memory_limit_mb = 512
metrics_enabled = false
log_level = "info"

[rate_limit]
enabled = false

[pipeline]
enabled = false

[audit]
enabled = false
"#;

    let (_dir, path) = write_temp_toml(toml_content);
    let config = AppConfig::load_via_confers_with_path(&path).expect("confers load should succeed");

    // Verify server config loaded from TOML
    assert_eq!(config.server.host, "127.0.0.1");
    assert_eq!(config.server.port, 9002);
    assert_eq!(config.server.timeout, Some(30));

    // Verify model config
    assert_eq!(config.model.model_repo, "BAAI/bge-m3");
    assert!(!config.model.use_gpu);
    assert_eq!(config.model.batch_size, 8);
    assert_eq!(config.model.expected_dimension, Some(1024));

    // Verify embedding config
    assert_eq!(config.embedding.default_aggregation, "mean");
    assert!(!config.embedding.cache_enabled);
    assert_eq!(config.embedding.max_batch_size, 32);

    // Verify rate_limit disabled in minimal config
    assert!(!config.rate_limit.enabled);

    // Verify audit disabled in minimal config
    assert!(!config.audit.enabled);
}

/// Test 2: Environment variable `VECBOOST_JWT_SECRET` overrides TOML value.
///
/// Sets `VECBOOST_JWT_SECRET` to a non-empty value, loads config, and
/// verifies that `auth.jwt_secret` reflects the env var rather than the
/// TOML default (None).
///
/// NOTE: Env vars are process-global; this test may race with parallel tests
/// that also touch `VECBOOST_JWT_SECRET`. The cleanup at the end minimises
/// the window.
#[test]
fn test_confers_env_var_jwt_secret_override() {
    let _guard = ENV_LOCK.lock().expect("env lock poisoned");

    // Ensure clean state before test
    unsafe {
        std::env::remove_var("VECBOOST_JWT_SECRET");
    }

    let toml_content = r#"
[server]
host = "0.0.0.0"
port = 8080

[model]
model_repo = "test/model"
use_gpu = false
batch_size = 1
expected_dimension = 128

[embedding]
default_aggregation = "mean"
similarity_metric = "cosine"
cache_enabled = false
cache_size = 0
max_batch_size = 1

[monitoring]
metrics_enabled = false

[rate_limit]
enabled = false

[pipeline]
enabled = false

[audit]
enabled = false
"#;

    let (_dir, path) = write_temp_toml(toml_content);

    // Load without env var - jwt_secret should be None (default)
    let config_no_env =
        AppConfig::load_via_confers_with_path(&path).expect("confers load should succeed");
    assert!(
        config_no_env.auth.jwt_secret.is_none(),
        "jwt_secret should be None when VECBOOST_JWT_SECRET is not set"
    );

    // Set env var and reload - jwt_secret should be overridden
    let test_secret = "test-jwt-secret-from-env-var-32+chars";
    assert!(
        test_secret.len() >= 32,
        "test secret should be at least 32 chars"
    );
    unsafe {
        std::env::set_var("VECBOOST_JWT_SECRET", test_secret);
    }

    let config_with_env =
        AppConfig::load_via_confers_with_path(&path).expect("confers load should succeed");
    assert_eq!(
        config_with_env.auth.jwt_secret,
        Some(test_secret.to_string()),
        "VECBOOST_JWT_SECRET should override TOML default"
    );

    // Cleanup
    unsafe {
        std::env::remove_var("VECBOOST_JWT_SECRET");
    }
}

/// Test 3: Hot-reload subscribe callback via `confers::bus::InMemoryBus`.
///
/// Verifies the subscribe API: create an `InMemoryBus`, subscribe to
/// config change events, publish a `ConfigChangeEvent`, and verify the
/// subscriber receives it. This models the hot-reload notification flow
/// where a watcher publishes change events and config consumers react.
#[tokio::test]
async fn test_confers_inmemorybus_subscribe_publish() {
    use confers::ConfigBus;
    use confers::bus::{ConfigChangeEvent, InMemoryBus};
    use futures::StreamExt;

    let bus = InMemoryBus::new();

    // Subscribe before publishing to ensure receipt
    let mut stream = bus
        .subscribe()
        .await
        .expect("subscribe should return a stream");

    // Publish a config change event
    let event = ConfigChangeEvent::new(
        "test-instance",
        "file://config.toml",
        vec!["server.port".to_string(), "auth.jwt_secret".to_string()],
        "checksum-abc123",
    );

    bus.publish(event.clone())
        .await
        .expect("publish should succeed");

    // Receive the event from the stream
    let received = tokio::time::timeout(std::time::Duration::from_secs(2), stream.next())
        .await
        .expect("should receive event within timeout")
        .expect("stream should not end");

    // Verify event content
    assert_eq!(received.instance_id, "test-instance");
    assert_eq!(received.source, "file://config.toml");
    assert_eq!(
        received.changed_keys,
        vec!["server.port".to_string(), "auth.jwt_secret".to_string()]
    );
    assert_eq!(received.checksum, "checksum-abc123");
}

/// Test 4: Defaults are applied when config file is missing.
///
/// When `file_optional` is given a non-existent path, confers should fall
/// back to `Default` implementations for all sub-configs.
#[test]
fn test_confers_defaults_when_no_file() {
    let _guard = ENV_LOCK.lock().expect("env lock poisoned");

    // Ensure clean env state
    unsafe {
        std::env::remove_var("VECBOOST_JWT_SECRET");
        std::env::remove_var("VECBOOST_ADMIN_PASSWORD");
    }

    let non_existent = std::path::PathBuf::from("/tmp/vecboost_nonexistent_config_9999.toml");
    let config = AppConfig::load_via_confers_with_path(&non_existent)
        .expect("should load with defaults when file is missing");

    // Verify defaults from app.rs Default impls
    assert_eq!(config.server.host, "0.0.0.0");
    assert_eq!(config.server.port, 3000);
    assert_eq!(config.model.model_repo, "BAAI/bge-m3");
    assert_eq!(config.model.batch_size, 32);
    assert_eq!(config.embedding.default_aggregation, "mean");
    assert!(config.embedding.cache_enabled);
    assert!(!config.auth.enabled);
    assert!(config.auth.jwt_secret.is_none());
}

/// Test 5: TOML values override struct defaults.
///
/// Loads a TOML with non-default values and verifies they take precedence
/// over the `Default` implementations.
#[test]
fn test_confers_toml_overrides_defaults() {
    let toml_content = r#"
[server]
host = "10.0.0.1"
port = 7777
grpc_enabled = true

[model]
model_repo = "custom/repo"
use_gpu = true
batch_size = 64
expected_dimension = 768

[embedding]
default_aggregation = "max"
similarity_metric = "dot"
cache_enabled = true
cache_size = 4096
max_batch_size = 128

[monitoring]
metrics_enabled = true
log_level = "debug"

[rate_limit]
enabled = true

[pipeline]
enabled = true

[audit]
enabled = true
"#;

    let (_dir, path) = write_temp_toml(toml_content);
    let config = AppConfig::load_via_confers_with_path(&path).expect("confers load should succeed");

    // Verify TOML overrode defaults
    assert_eq!(config.server.host, "10.0.0.1");
    assert_eq!(config.server.port, 7777);
    assert!(config.server.grpc_enabled);

    assert_eq!(config.model.model_repo, "custom/repo");
    assert!(config.model.use_gpu);
    assert_eq!(config.model.batch_size, 64);
    assert_eq!(config.model.expected_dimension, Some(768));

    assert_eq!(config.embedding.default_aggregation, "max");
    assert_eq!(config.embedding.similarity_metric, "dot");
    assert_eq!(config.embedding.cache_size, 4096);
    assert_eq!(config.embedding.max_batch_size, 128);

    assert!(config.rate_limit.enabled);
    assert!(config.audit.enabled);
}

/// T029: Regression test for trusted_proxies + max_text_length field defaults.
///
/// Validates that configs omitting these fields fall back to defaults
/// (R-config-001/002 验收点 6), and configs including them load correctly.
#[test]
fn test_trusted_proxies_and_max_text_length_defaults_when_omitted() {
    let _guard = ENV_LOCK.lock().expect("env lock poisoned");
    unsafe {
        std::env::remove_var("VECBOOST_JWT_SECRET");
        std::env::remove_var("VECBOOST_ADMIN_PASSWORD");
    }

    // TOML 配置中省略 trusted_proxies 和 max_text_length 字段
    let toml_content = r#"
[server]
host = "127.0.0.1"
port = 9000

[model]
model_repo = "test/model"
use_gpu = false
batch_size = 8
expected_dimension = 128

[embedding]
default_aggregation = "mean"
similarity_metric = "cosine"
cache_enabled = false
cache_size = 0
max_batch_size = 32
# max_text_length 故意省略,应 fallback 到 default 8192

[monitoring]
metrics_enabled = false

[rate_limit]
enabled = false

[pipeline]
enabled = false

[audit]
enabled = false

[auth]
enabled = false
# trusted_proxies 故意省略,应 fallback 到 default 空 Vec
"#;

    let (_dir, path) = write_temp_toml(toml_content);
    let config = AppConfig::load_via_confers_with_path(&path).expect("confers load should succeed");

    // 验证 fallback 到 default
    assert!(
        config.auth.trusted_proxies.is_empty(),
        "trusted_proxies should default to empty Vec when omitted"
    );
    assert_eq!(
        config.embedding.max_text_length, 8192,
        "max_text_length should default to 8192 when omitted"
    );
}

#[test]
fn test_trusted_proxies_and_max_text_length_loaded_when_present() {
    let _guard = ENV_LOCK.lock().expect("env lock poisoned");
    unsafe {
        std::env::remove_var("VECBOOST_JWT_SECRET");
        std::env::remove_var("VECBOOST_ADMIN_PASSWORD");
    }

    // TOML 配置中显式提供 trusted_proxies 和 max_text_length
    let toml_content = r#"
[server]
host = "127.0.0.1"
port = 9001

[model]
model_repo = "test/model"
use_gpu = false
batch_size = 8
expected_dimension = 128

[embedding]
default_aggregation = "mean"
similarity_metric = "cosine"
cache_enabled = false
cache_size = 0
max_batch_size = 32
max_text_length = 4096

[monitoring]
metrics_enabled = false

[rate_limit]
enabled = false

[pipeline]
enabled = false

[audit]
enabled = false

[auth]
enabled = false
trusted_proxies = ["10.0.0.0/8", "192.168.0.0/16"]
"#;

    let (_dir, path) = write_temp_toml(toml_content);
    let config = AppConfig::load_via_confers_with_path(&path).expect("confers load should succeed");

    // 验证字段被正确加载
    assert_eq!(
        config.auth.trusted_proxies,
        vec!["10.0.0.0/8".to_string(), "192.168.0.0/16".to_string()],
        "trusted_proxies should match TOML values"
    );
    assert_eq!(
        config.embedding.max_text_length, 4096,
        "max_text_length should match TOML value"
    );
}