serial-mcp 0.4.2

MCP server for serial port communication. 13 tools (open/read/read_line/write/wait_for/subscribe/...), resources, prompts, task cancellation, stdio + streamable-HTTP transports.
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
use std::sync::Arc;
use std::time::{Duration, Instant};

use rmcp::{
    model::{
        LoggingLevel, LoggingMessageNotificationParam, ProgressNotificationParam, ProgressToken,
    },
    service::Peer,
    Json, RoleServer,
};
use tracing::{error, warn};

use crate::codec::{self, Encoding};
use crate::error::SerialError;
use crate::serial::{
    ConnectionConfig, ConnectionManager, DataBits, FlowControl, Parity, SerialConnection, StopBits,
};
use crate::tools::types::*;

pub use crate::limits::{
    MAX_READ_BYTES, MAX_STREAM_CHUNK_BYTES, MAX_TIMEOUT_MS, MAX_WAIT_BYTES, MAX_WRITE_BYTES,
    MIN_POLL_INTERVAL_MS, MIN_READ_BYTES, MIN_STREAM_CHUNK_BYTES, MIN_WAIT_BYTES,
};

pub(crate) const DEFAULT_READ_TIMEOUT_MS: u64 = 1000;

pub fn clamp_or_err(name: &str, value: usize, max: usize) -> Result<usize, String> {
    if value > max {
        Err(format!("{name}={value} exceeds maximum {max}"))
    } else {
        Ok(value)
    }
}

pub fn require_min_or_err(name: &str, value: usize, min: usize) -> Result<usize, String> {
    if value < min {
        Err(format!("{name}={value} is below minimum {min}"))
    } else {
        Ok(value)
    }
}

pub fn clamp_timeout_or_err(name: &str, value: u64, max: u64) -> Result<u64, String> {
    if value > max {
        Err(format!("{name}={value}ms exceeds maximum {max}ms"))
    } else {
        Ok(value)
    }
}

pub fn clamp_poll_interval_or_err(name: &str, value: u64, min: u64) -> Result<u64, String> {
    if value < min {
        Err(format!("{name}={value}ms is below minimum {min}ms"))
    } else {
        Ok(value)
    }
}

// ------------------------------------------------------------------
// Connection lookup
// ------------------------------------------------------------------

pub async fn lookup_connection(
    connections: &Arc<ConnectionManager>,
    id: &str,
) -> Result<Arc<SerialConnection>, String> {
    connections
        .get(id)
        .await
        .map_err(|_| format!("Connection ID {id} not found"))
}

// ------------------------------------------------------------------
// Read helpers
// ------------------------------------------------------------------

/// Outcome of a read call. `timed_out` distinguishes the genuine
/// read-timeout case from a successful read of `bytes`.
pub struct ReadOutcome {
    pub bytes: Vec<u8>,
    pub timed_out: bool,
    pub elapsed_ms: u64,
}

pub async fn read_bytes(
    connection: &SerialConnection,
    max_bytes: usize,
    timeout_ms: Option<u64>,
    ct: &tokio_util::sync::CancellationToken,
    progress_token: Option<ProgressToken>,
    peer: Option<&Peer<RoleServer>>,
) -> Result<ReadOutcome, String> {
    const SETTLE_MS: u64 = 50;

    let effective_timeout = timeout_ms.unwrap_or(DEFAULT_READ_TIMEOUT_MS);
    let deadline = Instant::now() + Duration::from_millis(effective_timeout);
    let read_start = Instant::now();
    let mut buf = vec![0u8; max_bytes];

    let mut last_progress = Instant::now();

    // Read until at least one byte arrives or we time out.
    let first_n = loop {
        let remaining = deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            return Ok(ReadOutcome {
                bytes: Vec::new(),
                timed_out: true,
                elapsed_ms: read_start.elapsed().as_millis() as u64,
            });
        }

        let poll_ms = remaining.as_millis() as u64;
        let poll_ms = poll_ms.clamp(1, 250);

        match tokio::select! {
            _ = ct.cancelled() => return Err("Cancelled".into()),
            res = connection.read(&mut buf, Some(poll_ms)) => res,
        } {
            Ok(n) if n > 0 => break n,
            Ok(_) => {}
            Err(SerialError::ReadTimeout) => {}
            Err(e) => return Err(log_tool_err("read", "Data reading failed", e)),
        }

        if let (Some(token), Some(peer)) = (progress_token.clone(), peer) {
            if last_progress.elapsed() >= Duration::from_millis(250) {
                last_progress = Instant::now();
                let remaining = deadline.saturating_duration_since(Instant::now());
                let elapsed_ms = effective_timeout.saturating_sub(remaining.as_millis() as u64);
                let _ = peer
                    .notify_progress(ProgressNotificationParam {
                        progress_token: token,
                        progress: elapsed_ms as f64,
                        total: Some(effective_timeout as f64),
                        message: Some("waiting for data".into()),
                    })
                    .await;
            }
        }
    };

    let mut total = first_n;
    while total < max_bytes {
        let remaining = deadline
            .saturating_duration_since(Instant::now())
            .as_millis() as u64;
        let settle = remaining.min(SETTLE_MS);
        if settle == 0 {
            break;
        }
        let res = tokio::select! {
            _ = ct.cancelled() => return Err("Cancelled".into()),
            res = connection.read(&mut buf[total..], Some(settle)) => res,
        };
        match res {
            Ok(n) if n > 0 => {
                total += n;
                if let (Some(token), Some(peer)) = (progress_token.clone(), peer) {
                    let remaining = deadline.saturating_duration_since(Instant::now());
                    let elapsed_ms = effective_timeout.saturating_sub(remaining.as_millis() as u64);
                    if last_progress.elapsed() >= Duration::from_millis(250) {
                        last_progress = Instant::now();
                        let _ = peer
                            .notify_progress(ProgressNotificationParam {
                                progress_token: token,
                                progress: elapsed_ms as f64,
                                total: Some(effective_timeout as f64),
                                message: Some(format!("read {total} bytes")),
                            })
                            .await;
                    }
                }
            }
            _ => break,
        }
    }

    buf.truncate(total);
    Ok(ReadOutcome {
        bytes: buf,
        timed_out: false,
        elapsed_ms: read_start.elapsed().as_millis() as u64,
    })
}

pub struct WaitOutcome {
    pub bytes: Vec<u8>,
    pub match_index: Option<usize>,
    pub timed_out: bool,
}

pub async fn read_until_pattern(
    connection: &SerialConnection,
    pattern: &[u8],
    timeout_ms: u64,
    max_bytes: usize,
    ct: &tokio_util::sync::CancellationToken,
    progress_token: Option<ProgressToken>,
    peer: Option<&Peer<RoleServer>>,
) -> Result<WaitOutcome, String> {
    const CHUNK_CAPACITY: usize = 256;
    let deadline = Instant::now() + Duration::from_millis(timeout_ms);
    let mut accumulated: Vec<u8> = Vec::with_capacity(CHUNK_CAPACITY.min(max_bytes));

    let mut last_progress = Instant::now();

    if let (Some(token), Some(peer)) = (progress_token.clone(), peer) {
        let _ = peer
            .notify_progress(ProgressNotificationParam {
                progress_token: token,
                progress: 0.0,
                total: Some(timeout_ms as f64),
                message: Some("wait_for started".to_string()),
            })
            .await;
    }

    loop {
        if ct.is_cancelled() {
            return Err("Cancelled".into());
        }
        if let Some(idx) = find_subslice(&accumulated, pattern) {
            return Ok(WaitOutcome {
                bytes: accumulated,
                match_index: Some(idx),
                timed_out: false,
            });
        }
        if accumulated.len() >= max_bytes {
            return Ok(WaitOutcome {
                bytes: accumulated,
                match_index: None,
                timed_out: false,
            });
        }
        let now = Instant::now();
        if now >= deadline {
            return Ok(WaitOutcome {
                bytes: accumulated,
                match_index: None,
                timed_out: true,
            });
        }

        if let (Some(token), Some(peer)) = (progress_token.clone(), peer) {
            if last_progress.elapsed() >= Duration::from_millis(250) {
                last_progress = Instant::now();
                let remaining = deadline.saturating_duration_since(Instant::now());
                let elapsed_ms = timeout_ms.saturating_sub(remaining.as_millis() as u64);
                let _ = peer
                    .notify_progress(ProgressNotificationParam {
                        progress_token: token,
                        progress: elapsed_ms as f64,
                        total: Some(timeout_ms as f64),
                        message: Some(format!("wait_for {} bytes", accumulated.len())),
                    })
                    .await;
            }
        }

        let remaining_ms = (deadline - now).as_millis() as u64;
        // Poll in short slices so we can emit progress updates even with no data.
        let remaining_ms = remaining_ms.clamp(1, 250);
        let room = (max_bytes - accumulated.len()).min(CHUNK_CAPACITY);
        let mut chunk = vec![0u8; room];
        match tokio::select! {
            _ = ct.cancelled() => return Err("Cancelled".into()),
            res = connection.read(&mut chunk, Some(remaining_ms)) => res,
        } {
            Ok(0) => continue,
            Ok(n) => {
                chunk.truncate(n);
                accumulated.extend_from_slice(&chunk);
            }
            Err(SerialError::ReadTimeout) => {
                // No data arrived during this poll slice; keep waiting until the
                // overall deadline is reached.
                continue;
            }
            Err(e) => return Err(log_tool_err("wait_for", "Read failed during wait", e)),
        }
    }
}

pub(crate) fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || haystack.len() < needle.len() {
        return None;
    }
    haystack
        .windows(needle.len())
        .position(|window| window == needle)
}

// ------------------------------------------------------------------
// Streaming helper
// ------------------------------------------------------------------

pub async fn stream_rx(
    peer: Peer<rmcp::RoleServer>,
    connection: Arc<SerialConnection>,
    encoding: Encoding,
    max_chunk_bytes: usize,
    poll_interval_ms: u64,
) {
    let logger = format!("serial:{}", connection.id());
    let mut buf = vec![0u8; max_chunk_bytes];
    loop {
        match connection.read(&mut buf, Some(poll_interval_ms)).await {
            Ok(0) | Err(SerialError::ReadTimeout) => continue,
            Ok(n) => {
                let chunk = &buf[..n];
                let encoded = match codec::encode(encoding, chunk) {
                    Ok(s) => s,
                    Err(e) => {
                        warn!(
                            "RX encoding error on {}: {encoding} cannot encode {} bytes — dropped",
                            connection.id(),
                            n
                        );
                        // Emit a warning notification so the client is aware of dropped bytes
                        let payload = serde_json::json!({
                            "connection_id": connection.id(),
                            "encoding_error": true,
                            "encoding": encoding.to_string(),
                            "bytes_dropped": n,
                            "reason": e.to_string(),
                        });
                        let param = LoggingMessageNotificationParam {
                            level: LoggingLevel::Warning,
                            logger: Some(logger.clone()),
                            data: payload,
                        };
                        if let Err(e) = peer.notify_logging_message(param).await {
                            error!("RX stream peer disconnected: {}", e);
                            break;
                        }
                        continue;
                    }
                };
                let payload = serde_json::json!({
                    "connection_id": connection.id(),
                    "bytes_read": n,
                    "encoding": encoding.to_string(),
                    "data": encoded,
                });
                let param = LoggingMessageNotificationParam {
                    level: LoggingLevel::Info,
                    logger: Some(logger.clone()),
                    data: payload,
                };
                if let Err(e) = peer.notify_logging_message(param).await {
                    error!("RX stream peer disconnected: {}", e);
                    break;
                }
            }
            Err(e) => {
                error!("RX stream read error on {}: {}", connection.id(), e);
                break;
            }
        }
    }
}

// ------------------------------------------------------------------
// Result builders
// ------------------------------------------------------------------

pub fn build_read_result(
    outcome: ReadOutcome,
    connection_id: String,
    encoding: Encoding,
    requested_timeout_ms: Option<u64>,
) -> Result<Json<ReadResult>, String> {
    let timeout_ms = requested_timeout_ms.unwrap_or(DEFAULT_READ_TIMEOUT_MS);
    if outcome.timed_out {
        return Err(format!(
            "Read timed out after {timeout_ms}ms on {connection_id}"
        ));
    }
    let bytes_read = outcome.bytes.len();
    let elapsed_ms = outcome.elapsed_ms;
    let data = codec::encode(encoding, &outcome.bytes)
        .map_err(|e| format!("Data encoding failed - {e}"))?;
    Ok(Json(ReadResult {
        connection_id,
        bytes_read,
        encoding: encoding.to_string(),
        data,
        timeout_ms,
        elapsed_ms,
    }))
}

// ------------------------------------------------------------------
// Parsers
// ------------------------------------------------------------------

pub fn parse_encoding(raw: &str) -> Result<Encoding, String> {
    raw.parse::<Encoding>()
        .map_err(|e| format!("Unsupported encoding - {e}"))
}

pub fn parse_open_args(args: OpenArgs) -> Result<ConnectionConfig, String> {
    Ok(ConnectionConfig {
        port: args.port,
        baud_rate: args.baud_rate.0,
        data_bits: parse_data_bits(&args.data_bits)?,
        stop_bits: parse_stop_bits(&args.stop_bits)?,
        parity: parse_parity(&args.parity)?,
        flow_control: parse_flow_control(&args.flow_control)?,
    })
}

pub fn parse_data_bits(raw: &str) -> Result<DataBits, String> {
    match raw {
        "5" => Ok(DataBits::Five),
        "6" => Ok(DataBits::Six),
        "7" => Ok(DataBits::Seven),
        "8" => Ok(DataBits::Eight),
        other => Err(format!("Invalid data_bits {other:?} (expected 5/6/7/8)")),
    }
}

pub fn parse_stop_bits(raw: &str) -> Result<StopBits, String> {
    match raw {
        "1" => Ok(StopBits::One),
        "2" => Ok(StopBits::Two),
        other => Err(format!("Invalid stop_bits {other:?} (expected 1/2)")),
    }
}

pub fn parse_parity(raw: &str) -> Result<Parity, String> {
    match raw.to_lowercase().as_str() {
        "none" => Ok(Parity::None),
        "odd" => Ok(Parity::Odd),
        "even" => Ok(Parity::Even),
        other => Err(format!("Invalid parity {other:?} (expected none/odd/even)")),
    }
}

pub fn parse_flow_control(raw: &str) -> Result<FlowControl, String> {
    match raw.to_lowercase().as_str() {
        "none" => Ok(FlowControl::None),
        "software" => Ok(FlowControl::Software),
        "hardware" => Ok(FlowControl::Hardware),
        other => Err(format!(
            "Invalid flow_control {other:?} (expected none/software/hardware)"
        )),
    }
}

// ------------------------------------------------------------------
// Error helper
// ------------------------------------------------------------------

pub fn log_tool_err<E: std::fmt::Display>(op: &str, context: &str, err: E) -> String {
    error!("{op} failed: {err}");
    format!("{context} - {err}")
}

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

    use tokio::io::AsyncWriteExt;

    use crate::serial::test_support::loopback_connection;

    #[test]
    fn open_args_parsed_strictly() {
        let args = OpenArgs {
            port: "/dev/ttyUSB0".into(),
            baud_rate: FlexibleU32(115200),
            data_bits: "8".into(),
            stop_bits: "1".into(),
            parity: "none".into(),
            flow_control: "none".into(),
        };
        let config = parse_open_args(args).unwrap();
        assert_eq!(config.port, "/dev/ttyUSB0");
        assert_eq!(config.baud_rate, 115200);
    }

    #[test]
    fn open_args_reject_invalid_data_bits() {
        let args = OpenArgs {
            port: "X".into(),
            baud_rate: FlexibleU32(9600),
            data_bits: "9".into(),
            stop_bits: "1".into(),
            parity: "none".into(),
            flow_control: "none".into(),
        };
        let err = parse_open_args(args).unwrap_err();
        assert!(err.contains("data_bits"));
    }

    #[test]
    fn open_args_reject_invalid_parity() {
        assert!(parse_parity("weird").is_err());
        assert!(parse_parity("none").is_ok());
        assert!(parse_parity("Even").is_ok());
    }

    #[test]
    fn parse_encoding_rejects_garbage() {
        assert!(parse_encoding("rot13").is_err());
        assert!(parse_encoding("utf-8").is_ok());
    }

    #[test]
    fn build_read_result_timeout_returns_err() {
        let outcome = ReadOutcome {
            bytes: Vec::new(),
            timed_out: true,
            elapsed_ms: 250,
        };
        match build_read_result(outcome, "abc".into(), Encoding::Utf8, Some(250)) {
            Err(err) => {
                assert!(err.contains("timed out"));
                assert!(err.contains("250ms"));
            }
            Ok(_) => panic!("timeout must return Err"),
        }
    }

    #[test]
    fn build_read_result_timeout_uses_default() {
        let outcome = ReadOutcome {
            bytes: Vec::new(),
            timed_out: true,
            elapsed_ms: DEFAULT_READ_TIMEOUT_MS,
        };
        match build_read_result(outcome, "abc".into(), Encoding::Hex, None) {
            Err(err) => {
                assert!(err.contains("timed out"));
                assert!(err.contains(&DEFAULT_READ_TIMEOUT_MS.to_string()));
            }
            Ok(_) => panic!("timeout must return Err"),
        }
    }

    #[test]
    fn build_read_result_data_branch_encodes_hex() {
        let outcome = ReadOutcome {
            bytes: b"Hi".to_vec(),
            timed_out: false,
            elapsed_ms: 42,
        };
        let Json(result) = build_read_result(outcome, "abc".into(), Encoding::Hex, Some(500))
            .expect("data result must build");
        assert_eq!(result.bytes_read, 2);
        assert_eq!(result.encoding, "hex");
        assert_eq!(result.data, "48 69");
        assert_eq!(result.elapsed_ms, 42);
    }

    #[test]
    fn find_subslice_locates_pattern() {
        assert_eq!(find_subslice(b"hello OK> world", b"OK>"), Some(6));
        assert_eq!(find_subslice(b"OK>at-start", b"OK>"), Some(0));
        assert_eq!(find_subslice(b"trailing OK>", b"OK>"), Some(9));
    }

    #[test]
    fn find_subslice_missing_returns_none() {
        assert_eq!(find_subslice(b"hello world", b"OK>"), None);
        assert_eq!(find_subslice(b"", b"x"), None);
    }

    #[test]
    fn find_subslice_empty_needle_returns_none() {
        assert_eq!(find_subslice(b"hello", b""), None);
    }

    #[test]
    fn find_subslice_needle_longer_than_haystack() {
        assert_eq!(find_subslice(b"hi", b"hello"), None);
    }

    #[tokio::test]
    async fn read_until_pattern_matches_when_pattern_arrives() {
        let (conn, mut peer) = loopback_connection("test");
        let writer = tokio::spawn(async move {
            peer.write_all(b"junk before OK> and tail").await.unwrap();
        });
        let ct = tokio_util::sync::CancellationToken::new();
        let outcome = read_until_pattern(&conn, b"OK>", 1_000, 1024, &ct, None, None)
            .await
            .unwrap();
        writer.await.unwrap();
        assert_eq!(outcome.match_index, Some(12));
        assert!(!outcome.timed_out);
        assert!(outcome.bytes.starts_with(b"junk before OK>"));
    }

    #[tokio::test]
    async fn read_until_pattern_times_out_with_no_match() {
        let (conn, mut peer) = loopback_connection("test");
        peer.write_all(b"only noise here").await.unwrap();
        let ct = tokio_util::sync::CancellationToken::new();
        let outcome = read_until_pattern(&conn, b"OK>", 60, 1024, &ct, None, None)
            .await
            .unwrap();
        assert!(outcome.timed_out);
        assert!(outcome.match_index.is_none());
        assert!(outcome.bytes.windows(3).all(|w| w != b"OK>"));
    }

    #[tokio::test]
    async fn read_until_pattern_stops_at_max_bytes() {
        let (conn, mut peer) = loopback_connection("test");
        let blob = vec![b'.'; 600];
        peer.write_all(&blob).await.unwrap();
        let ct = tokio_util::sync::CancellationToken::new();
        let outcome = read_until_pattern(&conn, b"OK>", 1_000, 256, &ct, None, None)
            .await
            .unwrap();
        assert!(!outcome.timed_out);
        assert!(outcome.match_index.is_none());
        assert_eq!(outcome.bytes.len(), 256);
    }

    #[test]
    fn clamp_or_err_rejects_oversized_values() {
        assert!(clamp_or_err("test.max_bytes", 1024 * 1024, MAX_READ_BYTES).is_ok());
        assert!(clamp_or_err("test.max_bytes", 1024 * 1024 + 1, MAX_READ_BYTES).is_err());
        assert!(clamp_or_err("test.max_bytes", usize::MAX, MAX_WRITE_BYTES).is_err());
    }

    #[test]
    fn require_min_or_err_rejects_undersized_values() {
        assert!(require_min_or_err("test.max_bytes", 1, MIN_READ_BYTES).is_ok());
        assert!(require_min_or_err("test.max_bytes", 0, MIN_READ_BYTES).is_err());
    }

    #[test]
    fn clamp_timeout_or_err_rejects_oversized_timeout() {
        assert!(clamp_timeout_or_err("test.timeout_ms", 1000, MAX_TIMEOUT_MS).is_ok());
        assert!(
            clamp_timeout_or_err("test.timeout_ms", MAX_TIMEOUT_MS + 1, MAX_TIMEOUT_MS).is_err()
        );
    }

    #[test]
    fn clamp_poll_interval_or_err_rejects_undersized_interval() {
        assert!(clamp_poll_interval_or_err("test.poll_ms", 10, MIN_POLL_INTERVAL_MS).is_ok());
        assert!(clamp_poll_interval_or_err("test.poll_ms", 9, MIN_POLL_INTERVAL_MS).is_err());
        assert!(clamp_poll_interval_or_err("test.poll_ms", 0, MIN_POLL_INTERVAL_MS).is_err());
    }
}