rch-common 1.0.26

Shared types and utilities for Remote Compilation Helper
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
use super::*;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

static TEST_LOCK: Mutex<()> = Mutex::new(());

struct TestEnv {
    vars: HashMap<&'static str, &'static str>,
}

impl TestEnv {
    fn new(pairs: &[(&'static str, &'static str)]) -> Self {
        let vars = pairs.iter().copied().collect();
        Self { vars }
    }

    fn get(&self, key: &str) -> Option<String> {
        self.vars.get(key).map(|value| (*value).to_string())
    }
}

#[test]
fn rate_limiter_allows_first_update() {
    let limiter = RateLimiter::new(10);
    assert!(limiter.allow());
}

#[test]
fn rate_limiter_blocks_rapid_updates() {
    let limiter = RateLimiter::new(10);
    assert!(limiter.allow());
    assert!(!limiter.allow());
}

#[test]
fn rate_limiter_enforces_interval() {
    let limiter = RateLimiter::new(10);
    let interval = limiter.min_interval_ns();

    assert!(limiter.allow_at(0));
    assert!(!limiter.allow_at(interval / 2));
    assert!(limiter.allow_at(interval));
}

#[test]
fn rate_limiter_reset_allows_again() {
    let limiter = RateLimiter::new(10);
    assert!(limiter.allow());
    assert!(!limiter.allow());
    limiter.reset();
    assert!(limiter.allow());
}

#[test]
fn rate_limiter_thread_safe() {
    let limiter = Arc::new(RateLimiter::new(100));
    let count = Arc::new(AtomicU64::new(0));

    let handles: Vec<_> = (0..8)
        .map(|_| {
            let limiter = Arc::clone(&limiter);
            let count = Arc::clone(&count);
            std::thread::spawn(move || {
                for _ in 0..200 {
                    if limiter.allow() {
                        count.fetch_add(1, Ordering::Relaxed);
                    }
                }
            })
        })
        .collect();

    for handle in handles {
        handle.join().unwrap();
    }

    let total = count.load(Ordering::Relaxed);
    assert!(total > 0);
    assert!(total < 200);
}

#[test]
fn terminal_width_detects_columns_env() {
    let mut state = TerminalState::new();
    let env = TestEnv::new(&[("COLUMNS", "120")]);
    state.refresh_width_with(|key| env.get(key));
    assert_eq!(state.width, 120);
}

#[test]
fn terminal_width_falls_back_on_invalid_env() {
    let mut state = TerminalState::new();
    let env = TestEnv::new(&[("COLUMNS", "0")]);
    state.refresh_width_with(|key| env.get(key));
    assert_eq!(state.width, DEFAULT_TERMINAL_WIDTH);
}

#[test]
fn terminal_truncates_to_width() {
    let mut state = TerminalState::new();
    state.width = 5;
    assert_eq!(state.truncate("1234567"), "12345");
}

#[test]
fn terminal_truncates_zero_width_to_single_char() {
    let mut state = TerminalState::new();
    state.width = 0;
    assert_eq!(state.truncate("abcd"), "a");
}

#[test]
fn cleanup_guard_noop_when_disabled() {
    let guard = CleanupGuard::new(false);
    guard.clear_line();
    guard.hide_cursor();
    guard.show_cursor();
}

#[test]
fn progress_context_nested_counts() {
    let _guard = TEST_LOCK.lock();
    ACTIVE_CONTEXTS.store(0, Ordering::SeqCst);

    let ctx1 = ProgressContext::new_for_test(true);
    assert_eq!(ACTIVE_CONTEXTS.load(Ordering::SeqCst), 1);

    let ctx2 = ProgressContext::new_for_test(true);
    assert_eq!(ACTIVE_CONTEXTS.load(Ordering::SeqCst), 2);

    drop(ctx2);
    assert_eq!(ACTIVE_CONTEXTS.load(Ordering::SeqCst), 1);

    drop(ctx1);
    assert_eq!(ACTIVE_CONTEXTS.load(Ordering::SeqCst), 0);
}

#[test]
fn progress_context_disabled_when_not_tty() {
    let _guard = TEST_LOCK.lock();
    ACTIVE_CONTEXTS.store(0, Ordering::SeqCst);

    let ctx = ProgressContext::new_for_test(false);
    assert!(!ctx.enabled);
    assert_eq!(ACTIVE_CONTEXTS.load(Ordering::SeqCst), 0);
}

#[test]
fn progress_context_render_handles_long_lines() {
    let _guard = TEST_LOCK.lock();
    let mut ctx = ProgressContext::new_for_test(false);
    ctx.render("This should be ignored because context is disabled");
}

#[test]
fn signal_state_flags() {
    let state = SignalState::new();
    assert!(!state.interrupted.load(Ordering::SeqCst));
    assert!(!state.take_resized());

    state.simulate_interrupt();
    state.simulate_resize();

    assert!(state.interrupted.load(Ordering::SeqCst));
    assert!(state.take_resized());
    assert!(!state.take_resized());
}

#[test]
fn progress_context_rate_limit_respects_interval() {
    let _guard = TEST_LOCK.lock();
    let mut ctx = ProgressContext::new_for_test(true);
    ctx.rate_limiter = RateLimiter::new(10);

    ctx.render("first");
    ctx.render("second");
    std::thread::sleep(Duration::from_millis(110));
    ctx.render("third");
}

// ==================== Additional Coverage Tests ====================

#[test]
fn detect_terminal_width_with_valid_columns() {
    let width = detect_terminal_width_with(|key| {
        if key == "COLUMNS" {
            Some("100".to_string())
        } else {
            None
        }
    });
    assert_eq!(width, 100);
}

#[test]
fn detect_terminal_width_with_missing_env() {
    let width = detect_terminal_width_with(|_| None);
    assert_eq!(width, DEFAULT_TERMINAL_WIDTH);
}

#[test]
fn detect_terminal_width_with_invalid_value() {
    let width = detect_terminal_width_with(|key| {
        if key == "COLUMNS" {
            Some("not_a_number".to_string())
        } else {
            None
        }
    });
    assert_eq!(width, DEFAULT_TERMINAL_WIDTH);
}

#[test]
fn detect_terminal_width_with_negative_overflow() {
    // Values that would overflow u16 should fall back to default
    let width = detect_terminal_width_with(|key| {
        if key == "COLUMNS" {
            Some("999999".to_string())
        } else {
            None
        }
    });
    // 999999 overflows u16, so parse fails and we get default
    assert_eq!(width, DEFAULT_TERMINAL_WIDTH);
}

#[test]
fn rate_limiter_min_clamps_to_one() {
    // Creating with 0 should clamp to 1 update per second
    let limiter = RateLimiter::new(0);
    assert_eq!(limiter.min_interval_ns(), 1_000_000_000);
}

#[test]
fn rate_limiter_high_rate() {
    let limiter = RateLimiter::new(1000);
    // At 1000/sec, interval should be 1ms (1_000_000 ns)
    assert_eq!(limiter.min_interval_ns(), 1_000_000);
}

#[test]
fn rate_limiter_allow_after_interval_passes() {
    let limiter = RateLimiter::new(10);
    let interval = limiter.min_interval_ns();

    // First call always allowed
    assert!(limiter.allow_at(0));

    // Just before interval - blocked
    assert!(!limiter.allow_at(interval - 1));

    // Exactly at interval - allowed
    assert!(limiter.allow_at(interval));

    // Double interval from last - allowed
    assert!(limiter.allow_at(interval * 2));
}

#[test]
fn terminal_state_new_has_default_width() {
    let state = TerminalState::new();
    // Width should be detected (usually DEFAULT_TERMINAL_WIDTH in test env)
    assert!(state.width > 0);
}

#[test]
fn terminal_truncate_short_string_unchanged() {
    let mut state = TerminalState::new();
    state.width = 100;
    assert_eq!(state.truncate("short"), "short");
}

#[test]
fn terminal_truncate_exact_width() {
    let mut state = TerminalState::new();
    state.width = 5;
    assert_eq!(state.truncate("12345"), "12345");
}

#[test]
fn terminal_truncate_unicode() {
    let mut state = TerminalState::new();
    state.width = 3;
    // Unicode characters should be truncated by char count, not bytes
    assert_eq!(state.truncate("αβγδ"), "αβγ");
}

#[test]
fn cleanup_guard_enabled_operations() {
    // This test verifies the guard can be created with enabled=true
    // We can't easily verify the actual terminal operations in tests
    let guard = CleanupGuard::new(true);
    // Call methods to verify they don't panic
    guard.clear_line();
    guard.hide_cursor();
    guard.show_cursor();
}

#[test]
fn signal_state_new_has_defaults() {
    let state = SignalState::new();
    assert!(!state.interrupted.load(Ordering::SeqCst));
    assert!(!state.resized.load(Ordering::SeqCst));
}

#[test]
fn signal_state_mark_interrupted() {
    let state = SignalState::new();
    state.mark_interrupted();
    assert!(state.interrupted.load(Ordering::SeqCst));
}

#[test]
fn signal_state_mark_resized() {
    let state = SignalState::new();
    state.mark_resized();
    assert!(state.resized.load(Ordering::SeqCst));
}

#[test]
fn signal_state_take_resized_clears_flag() {
    let state = SignalState::new();
    state.mark_resized();
    assert!(state.take_resized()); // First take returns true
    assert!(!state.take_resized()); // Second take returns false (cleared)
}

#[test]
fn progress_context_clear_when_disabled() {
    let _guard = TEST_LOCK.lock();
    ACTIVE_CONTEXTS.store(0, Ordering::SeqCst);

    let ctx = ProgressContext::new_for_test(false);
    ctx.clear(); // Should be a no-op when disabled
    assert!(!ctx.enabled);
}

#[test]
fn progress_context_clear_when_enabled() {
    let _guard = TEST_LOCK.lock();
    ACTIVE_CONTEXTS.store(0, Ordering::SeqCst);

    let ctx = ProgressContext::new_for_test(true);
    ctx.clear(); // Should attempt to clear line
    assert!(ctx.enabled);
}

#[test]
fn progress_context_render_when_disabled_is_noop() {
    let _guard = TEST_LOCK.lock();
    ACTIVE_CONTEXTS.store(0, Ordering::SeqCst);

    let mut ctx = ProgressContext::new_for_test(false);
    // Render should do nothing when disabled
    ctx.render("test line");
    ctx.render("another line");
    // No panic means success
}

#[test]
fn progress_context_drop_decrements_count() {
    let _guard = TEST_LOCK.lock();
    ACTIVE_CONTEXTS.store(0, Ordering::SeqCst);

    {
        let _ctx = ProgressContext::new_for_test(true);
        assert_eq!(ACTIVE_CONTEXTS.load(Ordering::SeqCst), 1);
    }
    // After drop, count should be back to 0
    assert_eq!(ACTIVE_CONTEXTS.load(Ordering::SeqCst), 0);
}

#[test]
fn progress_context_drop_disabled_no_decrement() {
    let _guard = TEST_LOCK.lock();
    ACTIVE_CONTEXTS.store(5, Ordering::SeqCst);

    {
        let _ctx = ProgressContext::new_for_test(false);
        // Disabled context shouldn't increment
        assert_eq!(ACTIVE_CONTEXTS.load(Ordering::SeqCst), 5);
    }
    // Disabled context shouldn't decrement on drop
    assert_eq!(ACTIVE_CONTEXTS.load(Ordering::SeqCst), 5);

    // Cleanup
    ACTIVE_CONTEXTS.store(0, Ordering::SeqCst);
}

#[test]
fn rate_limiter_now_ns_returns_elapsed() {
    let limiter = RateLimiter::new(10);
    let first = limiter.now_ns();
    std::thread::sleep(Duration::from_millis(10));
    let second = limiter.now_ns();
    // Second should be greater (at least 10ms = 10_000_000 ns later)
    assert!(second > first);
    assert!(second - first >= 9_000_000); // Allow some timing slack
}

#[test]
fn terminal_width_env_empty_string() {
    let width = detect_terminal_width_with(|key| {
        if key == "COLUMNS" {
            Some("".to_string())
        } else {
            None
        }
    });
    assert_eq!(width, DEFAULT_TERMINAL_WIDTH);
}

#[test]
fn terminal_width_env_whitespace() {
    let width = detect_terminal_width_with(|key| {
        if key == "COLUMNS" {
            Some("  80  ".to_string())
        } else {
            None
        }
    });
    // Whitespace around number should fail to parse
    assert_eq!(width, DEFAULT_TERMINAL_WIDTH);
}