termosaic 0.2.2

Semantic, structured output for human, machine-text, and opaque-byte destinations
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
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
use std::fmt;
use std::io::{self, Write};
use std::num::NonZeroU8;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle, TermLike};

use crate::console_api::DestinationState;
use crate::render::render_text;
use crate::{ConsoleError, HumanText, Stream, Theme, TokenId};

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProgressOptions {
    pub length: Option<u64>,
    pub message_token: TokenId,
    pub message: HumanText,
    pub refresh_hz: NonZeroU8,
}

pub struct ProgressHandle {
    id: u64,
    bar: ProgressBar,
    hidden: bool,
    destination: Arc<DestinationState>,
    theme: Theme,
    errors: Arc<Mutex<Option<io::Error>>>,
    released: bool,
}

impl ProgressHandle {
    pub fn is_hidden(&self) -> bool {
        self.hidden
    }

    pub fn set_message(
        &self,
        token: TokenId,
        message: impl AsRef<str>,
    ) -> Result<(), ConsoleError> {
        let message = HumanText::sanitize(message);
        self.destination.progress.mutate(|| {
            self.bar.set_message(render_progress_message(
                &self.destination,
                &self.theme,
                &token,
                &message,
            ));
            take_error(&self.errors)
        })
    }

    pub fn set_position(&self, position: u64) -> Result<(), ConsoleError> {
        self.destination.progress.mutate(|| {
            self.bar.set_position(position);
            take_error(&self.errors)
        })
    }

    pub fn inc(&self, delta: u64) -> Result<(), ConsoleError> {
        self.destination.progress.mutate(|| {
            self.bar.inc(delta);
            take_error(&self.errors)
        })
    }

    pub fn finish(mut self, token: TokenId, message: impl AsRef<str>) -> Result<(), ConsoleError> {
        let message = HumanText::sanitize(message);
        let result = self.destination.progress.complete(self.id, || {
            self.bar.finish_with_message(render_progress_message(
                &self.destination,
                &self.theme,
                &token,
                &message,
            ));
            take_error(&self.errors)
        });
        self.released = true;
        result
    }

    pub fn clear(mut self) -> Result<(), ConsoleError> {
        let result = self.destination.progress.complete(self.id, || {
            self.bar.finish_and_clear();
            take_error(&self.errors)
        });
        self.released = true;
        result
    }
}

impl Drop for ProgressHandle {
    fn drop(&mut self) {
        if self.released {
            return;
        }
        let _ = self.destination.progress.complete(self.id, || {
            self.bar.finish_and_clear();
            let _ = take_error(&self.errors);
            Ok(())
        });
        self.released = true;
    }
}

#[derive(Clone)]
struct ActiveProgress {
    id: u64,
    bar: ProgressBar,
    errors: Arc<Mutex<Option<io::Error>>>,
}

pub(crate) struct ProgressCoordinator {
    /// Serializes progress construction, mutation, suspension, and teardown.
    ///
    /// The active-slot mutex alone is insufficient. A suspension that clones a
    /// bar before replacement targets the wrong terminal record. This guard
    /// spans the complete backend operation.
    operation: Mutex<()>,
    active: Mutex<Option<ActiveProgress>>,
    has_active: AtomicBool,
    next_id: AtomicU64,
    #[cfg(test)]
    suspension_count: AtomicU64,
}

impl ProgressCoordinator {
    pub(crate) fn new() -> Self {
        Self {
            operation: Mutex::new(()),
            active: Mutex::new(None),
            has_active: AtomicBool::new(false),
            next_id: AtomicU64::new(1),
            #[cfg(test)]
            suspension_count: AtomicU64::new(0),
        }
    }

    fn release_locked(&self, id: u64) {
        let mut active = self
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let matches_id = matches!(active.as_ref(), Some(progress) if progress.id == id);
        if matches_id {
            *active = None;
            self.has_active.store(false, Ordering::Release);
        }
    }

    fn initialize<T>(
        &self,
        build: impl FnOnce(u64) -> Result<(ProgressBar, Arc<Mutex<Option<io::Error>>>, T), ConsoleError>,
    ) -> Result<T, ConsoleError> {
        let _operation = self
            .operation
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if self
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .is_some()
        {
            return Err(ConsoleError::ProgressAlreadyActive);
        }

        // Publish the transition before backend construction while the
        // operation lock is held. A concurrent document write will then wait
        // for construction to finish instead of bypassing suspension.
        self.has_active.store(true, Ordering::Release);

        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let (bar, errors, value) = match build(id) {
            Ok(built) => built,
            Err(error) => {
                self.has_active.store(false, Ordering::Release);
                return Err(error);
            }
        };
        *self
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) =
            Some(ActiveProgress { id, bar, errors });
        Ok(value)
    }

    fn mutate(
        &self,
        operation: impl FnOnce() -> Result<(), ConsoleError>,
    ) -> Result<(), ConsoleError> {
        let _serial = self
            .operation
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        operation()
    }

    fn complete(
        &self,
        id: u64,
        operation: impl FnOnce() -> Result<(), ConsoleError>,
    ) -> Result<(), ConsoleError> {
        let _serial = self
            .operation
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let result = operation();
        self.release_locked(id);
        result
    }

    pub(crate) fn suspend(
        &self,
        operation: impl FnOnce() -> Result<(), ConsoleError>,
    ) -> Result<(), ConsoleError> {
        if !self.has_active.load(Ordering::Acquire) {
            return operation();
        }
        let _serial = self
            .operation
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let active = self
            .active
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .clone();
        let Some(active) = active else {
            return operation();
        };
        #[cfg(test)]
        self.suspension_count.fetch_add(1, Ordering::Relaxed);
        let result = active.bar.suspend(operation);
        let backend_result = take_error(&active.errors);
        match result {
            Err(error) => Err(error),
            Ok(()) => backend_result,
        }
    }

    #[cfg(test)]
    fn take_suspension_count(&self) -> u64 {
        self.suspension_count.swap(0, Ordering::Relaxed)
    }
}

pub(crate) fn start(
    destination: Arc<DestinationState>,
    theme: Theme,
    options: ProgressOptions,
) -> Result<ProgressHandle, ConsoleError> {
    let coordinator = destination.progress.clone();
    coordinator.initialize(|id| {
        let hidden = !destination.options.terminal.interactive_cursor;
        let errors = Arc::new(Mutex::new(None));
        let target = if hidden {
            ProgressDrawTarget::hidden()
        } else {
            let adapter = SinkTermLike {
                sink: destination.sink.clone(),
                width: destination
                    .options
                    .terminal
                    .width
                    .map_or(80, |width| width.get()),
                errors: errors.clone(),
            };
            ProgressDrawTarget::term_like_with_hz(Box::new(adapter), options.refresh_hz.get())
        };
        let bar = ProgressBar::with_draw_target(options.length, target);
        let template = if options.length.is_some() {
            "{spinner} {msg} {pos}/{len}"
        } else {
            "{spinner} {msg}"
        };
        let style = ProgressStyle::with_template(template)
            .map_err(|source| ConsoleError::Write {
                stream: Stream::Stderr,
                source: io::Error::new(io::ErrorKind::InvalidInput, source.to_string()),
            })?
            .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏", "✔"]);
        bar.set_style(style);
        bar.set_message(render_progress_message(
            &destination,
            &theme,
            &options.message_token,
            &options.message,
        ));
        take_error(&errors)?;

        let handle = ProgressHandle {
            id,
            bar: bar.clone(),
            hidden,
            destination,
            theme,
            errors: errors.clone(),
            released: false,
        };
        Ok((bar, errors, handle))
    })
}

fn render_progress_message(
    destination: &DestinationState,
    theme: &Theme,
    token: &TokenId,
    message: &HumanText,
) -> String {
    render_text(
        theme,
        token,
        message.as_str(),
        destination.options.terminal.color_depth,
        destination.color_enabled,
        Stream::Stderr,
    )
}

fn take_error(errors: &Arc<Mutex<Option<io::Error>>>) -> Result<(), ConsoleError> {
    let error = errors
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .take();
    match error {
        Some(source) => Err(ConsoleError::Write {
            stream: Stream::Stderr,
            source,
        }),
        None => Ok(()),
    }
}

struct SinkTermLike {
    sink: Arc<Mutex<Box<dyn Write + Send>>>,
    width: u16,
    errors: Arc<Mutex<Option<io::Error>>>,
}

impl fmt::Debug for SinkTermLike {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SinkTermLike")
            .field("width", &self.width)
            .finish_non_exhaustive()
    }
}

impl SinkTermLike {
    fn write_with(
        &self,
        operation: impl FnOnce(&mut dyn Write) -> io::Result<()>,
    ) -> io::Result<()> {
        let result = {
            let mut sink = self
                .sink
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            operation(sink.as_mut())
        };
        if let Err(error) = &result {
            let mut slot = self
                .errors
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            if slot.is_none() {
                *slot = Some(io::Error::new(error.kind(), error.to_string()));
            }
        }
        result
    }

    fn cursor(&self, count: usize, suffix: char) -> io::Result<()> {
        if count == 0 {
            return Ok(());
        }
        self.write_with(|sink| write!(sink, "\x1b[{count}{suffix}"))
    }
}

impl TermLike for SinkTermLike {
    fn width(&self) -> u16 {
        self.width
    }

    fn move_cursor_up(&self, count: usize) -> io::Result<()> {
        self.cursor(count, 'A')
    }

    fn move_cursor_down(&self, count: usize) -> io::Result<()> {
        self.cursor(count, 'B')
    }

    fn move_cursor_right(&self, count: usize) -> io::Result<()> {
        self.cursor(count, 'C')
    }

    fn move_cursor_left(&self, count: usize) -> io::Result<()> {
        self.cursor(count, 'D')
    }

    fn write_line(&self, value: &str) -> io::Result<()> {
        self.write_with(|sink| {
            sink.write_all(value.as_bytes())?;
            sink.write_all(b"\n")
        })
    }

    fn write_str(&self, value: &str) -> io::Result<()> {
        self.write_with(|sink| sink.write_all(value.as_bytes()))
    }

    fn clear_line(&self) -> io::Result<()> {
        self.write_with(|sink| sink.write_all(b"\r\x1b[2K"))
    }

    fn flush(&self) -> io::Result<()> {
        self.write_with(|sink| sink.flush())
    }
}

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

    use crate::{
        Alignment, Cell, ColorChoice, ColorDepth, Console, ConsoleOptions, DestinationOptions, Doc,
        FixedColumn, FixedTable, FixedTableOptions, OutputClass, Overflow, Span,
        TerminalCapabilities, tokens,
    };

    #[derive(Clone, Default)]
    struct Capture(Arc<Mutex<Vec<u8>>>);

    impl Write for Capture {
        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
            self.0
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .extend_from_slice(bytes);
            Ok(bytes.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    fn hidden_console() -> Console {
        let capabilities = TerminalCapabilities {
            is_terminal: false,
            color_depth: ColorDepth::Ansi16,
            width: NonZeroU16::new(20),
            interactive_cursor: false,
        };
        Console::with_writers(
            Capture::default(),
            Capture::default(),
            ConsoleOptions {
                stdout: DestinationOptions {
                    output_class: OutputClass::Human,
                    color: ColorChoice::Never,
                    terminal: capabilities,
                },
                stderr: DestinationOptions {
                    output_class: OutputClass::Human,
                    color: ColorChoice::Never,
                    terminal: capabilities,
                },
                theme: crate::themes::default(),
            },
        )
        .expect("valid hidden console")
    }

    fn options() -> ProgressOptions {
        ProgressOptions {
            length: Some(10),
            message_token: tokens::PROGRESS,
            message: HumanText::sanitize("working"),
            refresh_hz: NonZeroU8::new(10).expect("nonzero"),
        }
    }

    fn inject_error(errors: &Arc<Mutex<Option<io::Error>>>) {
        *errors
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(io::Error::new(
            io::ErrorKind::BrokenPipe,
            "injected adapter failure",
        ));
    }

    #[test]
    fn every_human_operation_uses_one_whole_progress_suspension() {
        let console = hidden_console();
        let handle = console.stderr_progress(options()).expect("progress");
        let mut writer = console.human(Stream::Stderr).expect("human stderr");

        writer
            .spans(&[Span::new(tokens::TEXT, "span")])
            .expect("spans");
        assert_eq!(console.stderr.progress.take_suspension_count(), 1);
        assert_eq!(console.stderr.take_lock_count(), 1);
        writer
            .line(&[Span::new(tokens::TEXT, "line")])
            .expect("line");
        assert_eq!(console.stderr.progress.take_suspension_count(), 1);
        assert_eq!(console.stderr.take_lock_count(), 1);
        writer.blank_line().expect("blank line");
        assert_eq!(console.stderr.progress.take_suspension_count(), 1);
        assert_eq!(console.stderr.take_lock_count(), 1);
        writer
            .doc(&Doc::concat([
                Doc::text("first"),
                Doc::hard_line(),
                Doc::text("second"),
            ]))
            .expect("document");
        assert_eq!(console.stderr.progress.take_suspension_count(), 1);
        assert_eq!(console.stderr.take_lock_count(), 1);

        let columns = [FixedColumn {
            width: NonZeroU16::new(4).expect("nonzero"),
            alignment: Alignment::Left,
            overflow: Overflow::Clip,
        }];
        let mut table = FixedTable::new(columns, FixedTableOptions::default()).expect("table");
        table.row([Cell::new("one", tokens::TEXT)]);
        table.row([Cell::new("two", tokens::TEXT)]);
        writer.fixed_table(&table).expect("fixed table");
        assert_eq!(console.stderr.progress.take_suspension_count(), 1);
        assert_eq!(console.stderr.take_lock_count(), 1);

        #[cfg(feature = "adaptive-tables")]
        {
            let mut table = crate::AdaptiveTable::new(
                vec![crate::AdaptiveColumn {
                    min_width: NonZeroU16::new(2).expect("nonzero"),
                    max_width: NonZeroU16::new(8).expect("nonzero"),
                    alignment: Alignment::Left,
                }],
                NonZeroU16::new(8).expect("nonzero"),
            )
            .expect("adaptive table");
            table
                .row(vec![Cell::new("adaptive content", tokens::TEXT)])
                .expect("row");
            writer.adaptive_table(&table).expect("adaptive table");
            assert_eq!(console.stderr.progress.take_suspension_count(), 1);
            assert_eq!(console.stderr.take_lock_count(), 1);
        }

        handle.clear().expect("clear");
    }

    #[test]
    fn lifecycle_operations_hold_the_serialization_guard_for_their_full_extent() {
        let coordinator = ProgressCoordinator::new();
        let id = coordinator
            .initialize(|id| {
                assert!(coordinator.operation.try_lock().is_err());
                assert!(
                    coordinator
                        .active
                        .lock()
                        .unwrap_or_else(|poisoned| poisoned.into_inner())
                        .is_none()
                );
                Ok((ProgressBar::hidden(), Arc::new(Mutex::new(None)), id))
            })
            .expect("initialize progress");

        coordinator
            .mutate(|| {
                assert!(coordinator.operation.try_lock().is_err());
                Ok(())
            })
            .expect("mutate progress");
        coordinator
            .suspend(|| {
                assert!(coordinator.operation.try_lock().is_err());
                Ok(())
            })
            .expect("suspend progress");
        coordinator
            .complete(id, || {
                assert!(coordinator.operation.try_lock().is_err());
                Ok(())
            })
            .expect("complete progress");
        assert!(
            coordinator
                .active
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .is_none()
        );
    }

    #[test]
    fn adapter_error_slot_is_drained_on_mutation_suspension_finish_clear_and_drop() {
        let console = hidden_console();
        let handle = console.stderr_progress(options()).expect("progress");
        inject_error(&handle.errors);
        assert!(matches!(
            handle.set_position(1),
            Err(ConsoleError::Write {
                stream: Stream::Stderr,
                ..
            })
        ));
        inject_error(&handle.errors);
        assert!(matches!(
            handle.set_message(tokens::PROGRESS, "updated"),
            Err(ConsoleError::Write {
                stream: Stream::Stderr,
                ..
            })
        ));
        inject_error(&handle.errors);
        assert!(matches!(
            handle.inc(1),
            Err(ConsoleError::Write {
                stream: Stream::Stderr,
                ..
            })
        ));
        handle.inc(1).expect("drained after mutations");

        inject_error(&handle.errors);
        assert!(matches!(
            console
                .human(Stream::Stderr)
                .expect("writer")
                .line(&[Span::new(tokens::TEXT, "diagnostic")]),
            Err(ConsoleError::Write {
                stream: Stream::Stderr,
                ..
            })
        ));
        console
            .human(Stream::Stderr)
            .expect("writer")
            .line(&[Span::new(tokens::TEXT, "recovered")])
            .expect("drained after suspension");

        inject_error(&handle.errors);
        assert!(matches!(
            handle.finish(tokens::STATUS_SUCCESS, "done"),
            Err(ConsoleError::Write {
                stream: Stream::Stderr,
                ..
            })
        ));

        let handle = console.stderr_progress(options()).expect("slot released");
        inject_error(&handle.errors);
        assert!(matches!(
            handle.clear(),
            Err(ConsoleError::Write {
                stream: Stream::Stderr,
                ..
            })
        ));

        let handle = console.stderr_progress(options()).expect("slot released");
        inject_error(&handle.errors);
        drop(handle);
        console
            .stderr_progress(options())
            .expect("drop releases and drains")
            .clear()
            .expect("no stale draw error");
    }
}