summaryrefslogtreecommitdiff
path: root/lib/textui/progress.go
blob: e7e7ff39c7cdc2d020c445c530778b6f04efbd08 (plain)
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
// Copyright (C) 2022-2023  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package textui

import (
	"context"
	"fmt"
	"time"

	"git.lukeshu.com/go/typedsync"
	"github.com/datawire/dlib/dlog"
)

type Stats interface {
	comparable
	fmt.Stringer
}

// Progress helps display to the user the ongoing progress of a long
// task.
//
// There are few usage requirements to watch out for:
//
//   - .Set() must have been called at least once before you call
//     .Done().  The easiest way to ensure this is to call .Set right
//     after creating the progress, or right before calling .Done().  I
//     advise against counting on a loop to have called .Set() at least
//     once.
type Progress[T Stats] struct {
	ctx      context.Context //nolint:containedctx // captured for separate goroutine
	lvl      dlog.LogLevel
	interval time.Duration

	cancel context.CancelFunc
	done   chan struct{}

	cur     typedsync.Value[T]
	oldStat T
	oldLine string

	// This isn't a functional part, but is useful for helping us
	// to detect misuse.
	lastTick  time.Time
	lastWrite time.Time
}

func NewProgress[T Stats](ctx context.Context, lvl dlog.LogLevel, interval time.Duration) *Progress[T] {
	ctx, cancel := context.WithCancel(ctx)
	ret := &Progress[T]{
		ctx:      ctx,
		lvl:      lvl,
		interval: interval,

		cancel: cancel,
		done:   make(chan struct{}),
	}
	return ret
}

// Set update the Progress.  Rate-limiting prevents this from being
// expensive, or from spamming the user; it is reasonably safe to call
// .Set in a tight inner loop.
//
// It is safe to call Set concurrently.
func (p *Progress[T]) Set(val T) {
	if _, hadOld := p.cur.Swap(val); !hadOld {
		go p.run(val)
	}
}

// Done closes the Progress; it flushes out one last status update (if
// nescessary), and releases resources associated with the Progress.
//
// It is safe to call Done multiple times, or concurrently.
//
// It will panic if Done is called without having called Set at least
// once.
func (p *Progress[T]) Done() {
	p.cancel()
	if _, started := p.cur.Load(); !started {
		panic("textui.Progress: .Done called without ever calling .Set")
	}
	<-p.done
}

func (p *Progress[T]) flush(now time.Time, cur T) {
	// Check how long it's been since we last printed something.
	// If this grows too big, it probably means that either the
	// program deadlocked or that we forgot to call .Done().
	if !p.lastTick.IsZero() && !p.lastWrite.IsZero() {
		tickTimeout := Tunable(1 * time.Minute)
		writeTimeout := Tunable(2 * time.Minute)
		if now.Sub(p.lastTick) < tickTimeout && now.Sub(p.lastWrite) > writeTimeout {
			err := fmt.Errorf("textui.Progress: hang detected: no updates for %v (from %v to %v)",
				writeTimeout, p.lastWrite, now)
			dlog.Error(p.ctx, err)
			panic(err)
		}
	}
	force := p.lastTick.IsZero()
	p.lastTick = now

	// Load the data to print.
	if !force && cur == p.oldStat {
		return
	}
	defer func() { p.oldStat = cur }()

	// Format the data as text.
	line := cur.String()
	if !force && line == p.oldLine {
		return
	}
	defer func() { p.oldLine = line }()

	// Print.
	dlog.Log(p.ctx, p.lvl, line)
	p.lastWrite = now
}

func (p *Progress[T]) run(initVal T) {
	p.flush(time.Now(), initVal)
	ticker := time.NewTicker(p.interval)
	for {
		select {
		case <-p.ctx.Done():
			ticker.Stop()
			val, ok := p.cur.Load()
			if !ok {
				panic("should not happen")
			}
			p.flush(time.Now(), val)
			close(p.done)
			return
		case now := <-ticker.C:
			val, ok := p.cur.Load()
			if !ok {
				panic("should not happen")
			}
			p.flush(now, val)
		}
	}
}