rypsok 0.10.0

Headless meta-search service for AI agents, served over the Model Context Protocol
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
//! Tests of `rypsok check` (RFC 020, DAT-1, DAT-2, D-6, D-20, D-21). Every
//! test names the requirement it verifies.

use super::*;
use crate::mcp::http::HttpSettings;

/// A scratch directory per test, removed at the end.
struct Dir(std::path::PathBuf);

impl Dir {
    fn new(name: &str) -> Self {
        let path = std::env::temp_dir().join(format!("rypsok-check-{name}-{}", std::process::id()));
        std::fs::create_dir_all(&path).unwrap();
        Dir(path)
    }

    /// A file with mode 0600 holding `content`; its path as TOML text.
    fn file(&self, name: &str, content: &str) -> String {
        let path = self.0.join(name);
        std::fs::write(&path, content).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
        }
        path.to_str().unwrap().replace('\\', "/")
    }
}

impl Drop for Dir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// The report of a configuration text: parse, validate, build.
///
/// The figures of the memory estimate depend on the allocator of the build
/// that runs, so the tests pin them for a named build: this one is musl,
/// whose figures they were written for (`report_for` names another).
fn report_of(text: &str) -> Result<Report, ConfigError> {
    report_for(text, EstimateBasis::Musl)
}

fn report_for(text: &str, basis: EstimateBasis) -> Result<Report, ConfigError> {
    let config = Config::parse(text)?;
    config.validate()?;
    build_for(&config, &ConfigSource::Defaults, basis)
}

fn all_lines(report: &Report) -> String {
    report
        .lines
        .iter()
        .chain(&report.warnings)
        .cloned()
        .collect::<Vec<_>>()
        .join("\n")
}

const TOKEN_40: &str = "0123456789abcdefghijABCDEFGHIJ0123456789";

/// REQ-OPS-001 (RFC 020, DAT-1): `check` resolves the callers' tokens as
/// `serve --transport http` does, and fails with the same message: an
/// unset variable, an unreadable file and a token below the minimum are
/// exit 1 in `check` too; a good token passes; a file without callers
/// resolves nothing.
#[test]
fn req_ops_001_check_resolves_the_callers_like_serve() {
    let dir = Dir::new("callers");
    let short = dir.file("short.token", "12345");
    let good = dir.file("good.token", TOKEN_40);
    let missing = dir
        .0
        .join("missing.token")
        .to_str()
        .unwrap()
        .replace('\\', "/");
    let callers = |source: &str| {
        format!("config_version = 1\n[[service.http.auth.callers]]\nid = \"alpha\"\n{source}\n")
    };
    for (name, text) in [
        (
            "an unset variable",
            callers("token_env = \"RYPSOK_TEST_CHECK_NO_SUCH_VARIABLE\""),
        ),
        (
            "a token of 5 bytes",
            callers(&format!("token_file = \"{short}\"")),
        ),
        (
            "an unreadable file",
            callers(&format!("token_file = \"{missing}\"")),
        ),
    ] {
        let config = Config::parse(&text).unwrap();
        config.validate().unwrap();
        let serve = HttpSettings::from_config(&config).unwrap_err();
        let check = report_of(&text)
            .err()
            .unwrap_or_else(|| panic!("{name}: accepted"));
        assert_eq!(check.problems, serve.problems, "{name}");
        assert!(
            check.problems[0].starts_with("service.http.auth.callers[0]: "),
            "{name}: {check}"
        );
    }
    let ok = report_of(&callers(&format!("token_file = \"{good}\""))).unwrap();
    assert!(
        ok.lines.iter().any(|l| l.contains("callers=1")),
        "{}",
        all_lines(&ok)
    );
    // Without callers nothing is resolved.
    assert!(report_of("config_version = 1\n").is_ok());
}

/// REQ-OPS-001 (RFC 020, DAT-2): `check` prints a line for every section.
/// The values are the effective ones (a changed value shows), and the
/// defaults show too.
#[test]
fn req_ops_001_check_prints_every_section() {
    let dir = Dir::new("sections");
    let token = dir.file("token", TOKEN_40);
    let text = format!(
        "config_version = 1\n\
         [service.http]\nbind = \"127.0.0.1:9001\"\nlegacy_revisions = false\nmax_connections = 11\nmax_request_bytes = 8192\nidle_timeout_s = 90\nmax_streams = 7\nrequest_timeout_s = 40\nmax_sessions = 33\n\
         [[service.http.auth.callers]]\nid = \"alpha\"\ntoken_file = \"{token}\"\n\
         [[service.http.auth.callers]]\nid = \"beta\"\ntoken_file = \"{token}\"\n\
         [fetch]\nports = [80, 443]\nmax_bytes = 1048576\nmax_chars = 4000\nmax_chars_ceiling = 9000\nrobots_txt = true\nfollow_cross_host_redirects = false\n\
         [egress]\nallow = [\"198.51.100.7\", \"example.org\"]\ndeny = [\"203.0.113.0/24\"]\nallow_http = false\n\
         [privacy]\nsecret_detection = \"mask\"\n\
         [logging]\nlevel = \"debug\"\nlog_queries = false\n\
         [cache]\nenabled = true\nmax_entries = 50\nttl_s = 120\n\
         [scraping]\nenabled = false\n\
         [resilience]\nfailures_to_open = 4\nfirst_cooldown_s = 20\nmax_cooldown_s = 300\n\
         [limits]\nfetches_in_flight = 3\nparsing_in_flight = 1\n"
    );
    let report = report_of(&text).unwrap();
    let line = |start: &str| -> String {
        let found: Vec<&String> = report
            .lines
            .iter()
            .filter(|l| l.starts_with(start))
            .collect();
        assert_eq!(
            found.len(),
            1,
            "{start}: {found:?} in\n{}",
            all_lines(&report)
        );
        found[0].clone()
    };
    for (start, wanted) in [
        (
            "rypsok: service.http:",
            "bind=127.0.0.1:9001 callers=2 legacy_revisions=false max_connections=11 max_request_bytes=8192 idle_timeout_s=90 max_streams=7 request_timeout_s=40 max_sessions=33",
        ),
        (
            "rypsok: fetch:",
            "ports=80,443 max_bytes=1048576 max_chars=4000 (ceiling 9000) deadline_ms=10000 max_redirects=5 robots_txt=true follow_cross_host_redirects=false",
        ),
        (
            "rypsok: egress:",
            "allow_rules=2 deny_rules=1 allow_http=false strict_mode=false proxy=none",
        ),
        ("rypsok: privacy:", "secret_detection=mask"),
        ("rypsok: logging:", "level=debug log_queries=false"),
        (
            "rypsok: cache:",
            "enabled=true max_entries=50 ttl_s=120 max_entry_bytes=32768",
        ),
        ("rypsok: scraping:", "enabled=false"),
        (
            "rypsok: resilience:",
            "failures_to_open=4 first_cooldown_s=20 max_cooldown_s=300",
        ),
        (
            "rypsok: limits:",
            "outbound_in_flight=32 per_engine_in_flight=2 fetches_in_flight=3 parsing_in_flight=1 strict_mode_urls=10000 robots_cache_entries=1000",
        ),
    ] {
        let found = line(start);
        assert!(
            found.contains(wanted),
            "{start}\n  wanted: {wanted}\n  got:    {found}"
        );
    }
    // The defaults, with the proxy and strict mode switched on.
    let defaults = report_of(
        "config_version = 1\n[fetch]\nstrict_mode = true\n[egress]\nproxy = \"http://proxy.example:3128\"\n",
    )
    .unwrap();
    let egress = defaults
        .lines
        .iter()
        .find(|l| l.starts_with("rypsok: egress:"))
        .unwrap();
    assert!(egress.contains("strict_mode=true proxy=set"), "{egress}");
}

/// REQ-SEC-020 and REQ-PRIV-004 (RFC 020, DAT-2): nothing secret is in
/// the output: no token, no API key, no text of a rule, no proxy address
/// (it may carry a password).
#[test]
fn req_sec_020_check_never_prints_a_secret() {
    let dir = Dir::new("secrets");
    let token = dir.file("token", "TOKENVALUE-0123456789abcdefghijklmnopqrstuv");
    let key = dir.file("key", "APIKEYVALUE-zyxwvutsrqponmlkjihgfedcba9876543210");
    let text = format!(
        "config_version = 1\n\
         [[service.http.auth.callers]]\nid = \"alpha\"\ntoken_file = \"{token}\"\n\
         [egress]\nallow = [\"198.51.100.0/24\", \"secret-host.example\"]\ndeny = [\"203.0.113.77\"]\nproxy = \"http://user:PROXYPASSWORD@proxy.example:3128\"\n\
         [engines.b]\ntype = \"brave\"\ncategories = [\"general\"]\napi_key_file = \"{key}\"\n"
    );
    let report = report_of(&text).unwrap();
    let output = all_lines(&report);
    for secret in [
        "TOKENVALUE",
        "APIKEYVALUE",
        "PROXYPASSWORD",
        "proxy.example",
        "198.51.100.0",
        "secret-host.example",
        "203.0.113.77",
    ] {
        assert!(!output.contains(secret), "`{secret}` in:\n{output}");
    }
    assert!(output.contains("callers=1"), "{output}");
    assert!(output.contains("credential found"), "{output}");
}

/// The warning lines of a configuration text.
fn warnings_of(text: &str) -> Vec<String> {
    report_of(text).unwrap().warnings
}

/// REQ-OPS-001 (RFC 020, D-6): one configuration per warning, and the exact
/// line. Each is `rypsok: warning: <key>: <what happens>; <the safer
/// setting>`; the exit code stays 0 (the report is `Ok`).
#[test]
fn req_ops_001_each_risky_setting_has_its_warning() {
    let dir = Dir::new("warnings");
    let token = dir.file("token", TOKEN_40);
    let cases: &[(&str, String, &str)] = &[
        (
            "an allow rule wider than /16",
            "config_version = 1\n[egress]\nallow = [\"10.0.0.0/8\"]\n".to_owned(),
            "rypsok: warning: egress.allow[0]: the rule admits a network wider than /16 (IPv4) or /32 (IPv6), which can include private networks and metadata addresses; list hosts or a narrower network",
        ),
        (
            "an allow rule for every address",
            "config_version = 1\n[egress]\nallow = [\"example.org\", \"0.0.0.0/0\"]\n".to_owned(),
            "rypsok: warning: egress.allow[1]: the rule admits a network wider than /16 (IPv4) or /32 (IPv6), which can include private networks and metadata addresses; list hosts or a narrower network",
        ),
        (
            "an IPv6 allow rule wider than /32",
            "config_version = 1\n[egress]\nallow = [\"fc00::/7\"]\n".to_owned(),
            "rypsok: warning: egress.allow[0]: the rule admits a network wider than /16 (IPv4) or /32 (IPv6), which can include private networks and metadata addresses; list hosts or a narrower network",
        ),
        (
            "secret detection off",
            "config_version = 1\n[privacy]\nsecret_detection = \"off\"\n".to_owned(),
            "rypsok: warning: privacy.secret_detection: \"off\" sends queries and URLs without the credential check; use \"refuse\", the default",
        ),
        (
            "a plaintext listener off loopback",
            format!("config_version = 1\n[service.http]\nbind = \"192.0.2.10:8737\"\n[[service.http.auth.callers]]\nid = \"alpha\"\ntoken_file = \"{token}\"\n"),
            "rypsok: warning: service.http.bind: the listener speaks plain HTTP and this bind is not loopback, so tokens and traffic cross the network unencrypted; bind loopback behind a TLS-terminating proxy",
        ),
        (
            "queries in the log",
            "config_version = 1\n[logging]\nlog_queries = true\n".to_owned(),
            "rypsok: warning: logging.log_queries: query text is written to the debug log; set it to false",
        ),
        (
            "robots.txt off",
            "config_version = 1\n[fetch]\nrobots_txt = false\n".to_owned(),
            "rypsok: warning: fetch.robots_txt: false fetches pages without reading robots.txt; set it to true",
        ),
        (
            "plain http",
            "config_version = 1\n[egress]\nallow_http = true\n".to_owned(),
            "rypsok: warning: egress.allow_http: plain http URLs are fetched as they are, without the https retry; set it to false",
        ),
        (
            "cross-host redirects",
            "config_version = 1\n[fetch]\nfollow_cross_host_redirects = true\n".to_owned(),
            "rypsok: warning: fetch.follow_cross_host_redirects: a redirect to another host is followed, so a page can lead a fetch to a host the caller did not name; set it to false",
        ),
        (
            "a scraping engine",
            "config_version = 1\n[scraping]\nenabled = true\n[engines.ddg]\ntype = \"duckduckgo\"\ncategories = [\"general\"]\n".to_owned(),
            "rypsok: warning: engines.ddg: scraping engine of type \"duckduckgo\" reads a human-facing page under the provider's terms and breaks when the page changes; prefer an engine with an API",
        ),
        (
            "a cache with no storable engine",
            "config_version = 1\n[cache]\nenabled = true\n[engines.d]\ntype = \"duckduckgo\"\ncategories = [\"general\"]\nenabled = true\n[scraping]\nenabled = true\n[engines.wikipedia]\ntype = \"wikipedia\"\ncategories = [\"general\"]\nenabled = false\n[engines.brave]\ntype = \"brave\"\ncategories = [\"general\"]\napi_key_env = \"X\"\nenabled = false\n".to_owned(),
            "rypsok: warning: cache.enabled: no enabled engine allows its results to be stored, so the cache holds nothing and only keeps queries in memory; turn the cache off or enable an engine that allows storage",
        ),
        (
            "more parses than the unit holds",
            "config_version = 1\n[limits]\nparsing_in_flight = 16\n".to_owned(),
            "rypsok: warning: memory: the worst case is about 640 MiB, above the 256 MiB of the documented unit (an estimate for the musl build); lower fetch.max_bytes, limits.fetches_in_flight, limits.parsing_in_flight or service.http.max_sessions",
        ),
    ];
    let mut wrong = Vec::new();
    for (name, text, wanted) in cases {
        let warnings = warnings_of(text);
        if !warnings.iter().any(|w| w == wanted) {
            wrong.push(format!("{name}: wanted\n    {wanted}\n  got {warnings:#?}"));
        }
    }
    assert!(
        wrong.is_empty(),
        "{} wrong:\n{}",
        wrong.len(),
        wrong.join("\n")
    );
}

/// REQ-OPS-001 (RFC 020, D-6): settings that are not risky give no warning:
/// the defaults, `legacy_revisions` either way, narrow allow rules and host
/// names, a loopback bind with callers, a cache with a storable engine, and
/// a worst case at the new ceilings.
#[test]
fn req_ops_001_safe_settings_give_no_warning() {
    let dir = Dir::new("quiet");
    let token = dir.file("token", TOKEN_40);
    for (name, text) in [
        ("the defaults", "config_version = 1\n".to_owned()),
        ("no file", String::new()),
        (
            "legacy revisions off",
            "config_version = 1\n[service.http]\nlegacy_revisions = false\n".to_owned(),
        ),
        (
            "legacy revisions on",
            "config_version = 1\n[service.http]\nlegacy_revisions = true\n".to_owned(),
        ),
        (
            "narrow rules",
            "config_version = 1\n[egress]\nallow = [\"10.1.0.0/16\", \"198.51.100.7\", \"docs.rs\", \"*.example.org\", \"2001:db8::/32\"]\ndeny = [\"0.0.0.0/0\"]\n".to_owned(),
        ),
        (
            "loopback with callers",
            format!("config_version = 1\n[[service.http.auth.callers]]\nid = \"alpha\"\ntoken_file = \"{token}\"\n"),
        ),
        (
            "a cache with Wikipedia",
            "config_version = 1\n[cache]\nenabled = true\n".to_owned(),
        ),
        (
            "the new max_bytes ceiling with the defaults (194 MiB)",
            "config_version = 1\n[fetch]\nmax_bytes = 10485760\n".to_owned(),
        ),
        (
            "the new max_sessions ceiling with the defaults (227 MiB)",
            "config_version = 1\n[service.http]\nmax_sessions = 2048\n".to_owned(),
        ),
    ] {
        let text = if name == "no file" { "config_version = 1\n".to_owned() } else { text };
        assert_eq!(warnings_of(&text), Vec::<String>::new(), "{name}");
    }
}

/// REQ-PERF-003 (RFC 020, D-20, D-21): each new ceiling fits the unit
/// alone, both together (299 MiB) do not, and `check` says so.
#[test]
fn req_perf_003_both_new_ceilings_together_exceed_the_unit() {
    let both = warnings_of(
        "config_version = 1\n[fetch]\nmax_bytes = 10485760\n[service.http]\nmax_sessions = 2048\n",
    );
    assert_eq!(both.len(), 1, "{both:?}");
    assert!(both[0].contains("about 299 MiB"), "{both:?}");
}

/// REQ-PERF-003 (RFC 020, D-20, D-21): `check` prints the memory estimate;
/// the defaults give 122 MiB, the new `max_bytes` ceiling stays under the
/// unit, and the line shows its parts.
#[test]
fn req_perf_003_check_prints_the_memory_estimate() {
    let line = |text: &str| -> String {
        report_of(text)
            .unwrap()
            .lines
            .into_iter()
            .find(|l| l.starts_with("rypsok: memory:"))
            .expect("a memory line")
    };
    assert_eq!(
        line("config_version = 1\n"),
        "rypsok: memory: worst case about 122 MiB (base 13 + bodies 20 + parses 74 + sessions 15 + cache 0 MiB; an estimate for the musl build)"
    );
    let ceiling = line("config_version = 1\n[fetch]\nmax_bytes = 10485760\n");
    assert!(ceiling.contains("about 194 MiB"), "{ceiling}");
    let cached = line("config_version = 1\n[cache]\nenabled = true\n");
    assert!(cached.contains("cache 32 MiB"), "{cached}");
    assert!(
        report_of("config_version = 1\n[fetch]\nmax_bytes = 10485760\n")
            .unwrap()
            .warnings
            .is_empty()
    );
}

/// A string shaped like a key, built at run time.
fn pasted_key() -> String {
    ["BSAx9f", "K2mQ7v", "Lp3ZtR", "8wYc"].concat()
}

/// REQ-SEC-020 (RFC 020, L1 of the 020l review): a secret pasted into
/// `api_key_env` or `token_env` does not come back in what `check` prints or
/// in the error it fails with (`serve` writes the same message to the log);
/// a proper variable name is still named.
#[test]
fn req_sec_020_check_does_not_repeat_a_secret_pasted_as_a_variable_name() {
    let pasted = pasted_key();
    let engine = format!(
        "config_version = 1\n[engines.b]\ntype = \"brave\"\ncategories = [\"general\"]\napi_key_env = \"{pasted}\"\n"
    );
    let report = report_of(&engine).unwrap();
    let output = all_lines(&report);
    assert!(!output.contains(&pasted), "{output}");
    assert!(
        output.contains("engine b: type=brave enabled=true categories=general preference=100 inactive: the value is not the name of an environment variable (it is not shown)"),
        "{output}"
    );
    // A caller: the error `serve` stops with.
    let caller = format!(
        "config_version = 1\n[[service.http.auth.callers]]\nid = \"alpha\"\ntoken_env = \"{pasted}\"\n"
    );
    let error = report_of(&caller).err().expect("refused");
    let text = error.to_string();
    assert!(!text.contains(&pasted), "{text}");
    assert_eq!(
        error.problems,
        vec![
            "service.http.auth.callers[0]: the value is not the name of an environment variable (it is not shown); this key names a variable that holds the secret, such as BRAVE_API_KEY, it does not hold the secret"
        ]
    );
    // A proper name is still named.
    let proper = report_of(
        "config_version = 1\n[[service.http.auth.callers]]\nid = \"alpha\"\ntoken_env = \"RYPSOK_TEST_CHECK_UNSET_TOKEN\"\n",
    )
    .err()
    .expect("refused");
    assert_eq!(
        proper.problems,
        vec![
            "service.http.auth.callers[0]: environment variable RYPSOK_TEST_CHECK_UNSET_TOKEN is unset or empty"
        ]
    );
}

/// REQ-PERF-003 (RFC 020, L2 of the 020l review): sessions exist only for
/// the handshake-based revisions, so their share of the estimate is counted
/// only while `legacy_revisions` is on. Off, the line says `sessions 0`, the
/// total drops by the share, and a configuration that fits only without
/// them is not warned about memory it cannot use.
#[test]
fn req_perf_003_sessions_count_only_with_legacy_revisions() {
    let line = |text: &str| -> String {
        report_of(text)
            .unwrap()
            .lines
            .into_iter()
            .find(|l| l.starts_with("rypsok: memory:"))
            .unwrap()
    };
    assert!(
        line("config_version = 1\n").contains(
            "about 122 MiB (base 13 + bodies 20 + parses 74 + sessions 15 + cache 0 MiB;"
        )
    );
    let off = line("config_version = 1\n[service.http]\nlegacy_revisions = false\n");
    assert!(
        off.contains("about 107 MiB (base 13 + bodies 20 + parses 74 + sessions 0 + cache 0 MiB;"),
        "{off}"
    );
    // The two ceilings together are 299 MiB with sessions and 179 without.
    let both =
        "config_version = 1\n[fetch]\nmax_bytes = 10485760\n[service.http]\nmax_sessions = 2048\n";
    assert_eq!(warnings_of(both).len(), 1);
    let without = format!("{both}legacy_revisions = false\n");
    assert_eq!(warnings_of(&without), Vec::<String>::new());
    assert!(
        line(&without).contains("about 179 MiB"),
        "{}",
        line(&without)
    );
}

/// REQ-OPS-001 (RFC 020, D-9): `check` prints the two keys that LIM-S12 and
/// LIM-O1 became: the connect timeout of an engine request in the `search`
/// line and the shutdown time in the `service` line, with the effective
/// values.
#[test]
fn req_ops_001_check_prints_the_connect_timeout_and_the_shutdown_time() {
    let report = all_lines(
        &report_of(
            "config_version = 1\n[search]\nconnect_timeout_ms = 250\n[service]\nshutdown_ms = 700\n",
        )
        .unwrap(),
    );
    assert!(report.contains("connect_timeout_ms=250"), "{report}");
    assert!(report.contains("shutdown_ms=700"), "{report}");
}

/// REQ-PERF-003 (RFC 020, 020x, F-4): `check` prints the figure of the build
/// it runs as and says which build that is. The glibc figures are higher.
#[test]
fn req_perf_003_check_names_the_build_of_the_estimate() {
    let line = |text: &str, basis| -> String {
        report_for(text, basis)
            .unwrap()
            .lines
            .into_iter()
            .find(|l| l.starts_with("rypsok: memory:"))
            .expect("a memory line")
    };
    assert_eq!(
        line("config_version = 1\n", EstimateBasis::Glibc),
        "rypsok: memory: worst case about 197 MiB (base 14 + bodies 20 + parses 148 + sessions 15 + cache 0 MiB; an estimate for the glibc build)"
    );
    // At the ceiling of fetch.max_bytes a glibc build is above the unit and
    // is told so; a musl build is not (the measurement peaked at 269 to 302
    // MiB against 173 to 175).
    let ceiling = "config_version = 1\n[fetch]\nmax_bytes = 10485760\n";
    let glibc = report_for(ceiling, EstimateBasis::Glibc).unwrap().warnings;
    assert_eq!(glibc.len(), 1, "{glibc:?}");
    assert!(glibc[0].contains("about 323 MiB"), "{glibc:?}");
    assert!(
        glibc[0].contains("(an estimate for the glibc build)"),
        "{glibc:?}"
    );
    assert!(
        report_for(ceiling, EstimateBasis::Musl)
            .unwrap()
            .warnings
            .is_empty()
    );
}

/// REQ-PERF-003 (RFC 020, 020x): on a platform that was not measured the
/// estimate is printed with the note and no warning is given against the
/// Linux unit, however large the figure.
#[test]
fn req_perf_003_an_unmeasured_platform_gets_the_note_and_no_warning() {
    let huge = "config_version = 1\n[limits]\nparsing_in_flight = 16\n";
    let report = report_for(huge, EstimateBasis::NotMeasured).unwrap();
    let line = report
        .lines
        .iter()
        .find(|l| l.starts_with("rypsok: memory:"))
        .unwrap();
    assert!(
        line.ends_with("MiB; measured on Linux; not measured for this platform)"),
        "{line}"
    );
    assert!(report.warnings.is_empty(), "{:?}", report.warnings);
}

/// REQ-PERF-003 (RFC 020, 020x): the command itself uses the basis of the
/// build that runs it.
#[test]
fn req_perf_003_the_command_uses_the_basis_of_its_own_build() {
    let config = Config::parse("config_version = 1\n").unwrap();
    config.validate().unwrap();
    let report = build(&config, &ConfigSource::Defaults).unwrap();
    let line = report
        .lines
        .iter()
        .find(|l| l.starts_with("rypsok: memory:"))
        .unwrap();
    assert!(
        line.ends_with(&format!("{})", EstimateBasis::current().label())),
        "{line}"
    );
}

/// REQ-OPS-001 and REQ-AGG-003 (RFC 021, D2): `check` prints each tool's
/// maximum call time on a line of its own, after the rate-limits line, with
/// the effective values: LIM-S7 (the search deadline plus 300 ms) and LIM-F5
/// (the fetch deadline plus 1000 ms). `engine_status` has no maximum and the
/// line says it reads memory only.
#[test]
fn req_ops_001_check_prints_the_call_maxima() {
    let line_of = |text: &str| -> (usize, usize, String) {
        let report = report_of(text).unwrap();
        let at = report
            .lines
            .iter()
            .position(|l| l.starts_with("rypsok: tool call maxima in ms:"))
            .unwrap_or_else(|| panic!("no maxima line in\n{}", all_lines(&report)));
        let rates = report
            .lines
            .iter()
            .position(|l| l.starts_with("rypsok: tool rate limits per minute:"))
            .unwrap();
        (rates, at, report.lines[at].clone())
    };
    let (rates, at, line) = line_of("config_version = 1\n");
    assert_eq!(at, rates + 1, "right after the rate-limits line");
    assert_eq!(
        line,
        "rypsok: tool call maxima in ms: web_search=2800 web_fetch=11000; engine_status reads memory only"
    );
    let (_, _, changed) =
        line_of("config_version = 1\n[search]\ndeadline_ms = 4000\n[fetch]\ndeadline_ms = 20000\n");
    assert_eq!(
        changed,
        "rypsok: tool call maxima in ms: web_search=4300 web_fetch=21000; engine_status reads memory only"
    );
}