fix: synchronize canceled input cleanup (#1876)
AI-assisted-by: Codex (GPT 6.1 sol) Co-authored-by: Drew Smirnoff <drew@charm.land> Signed-off-by: Drew Smirnoff <drew@charm.land>
This commit is contained in:
parent
7dd9c4c46e
commit
bc55190481
3 changed files with 275 additions and 17 deletions
227
shutdown_input_test.go
Normal file
227
shutdown_input_test.go
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
package tea
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
)
|
||||
|
||||
type shutdownInputReader struct {
|
||||
cancelable bool
|
||||
cancels int
|
||||
closes int
|
||||
}
|
||||
|
||||
func (*shutdownInputReader) Read([]byte) (int, error) { return 0, io.EOF }
|
||||
func (r *shutdownInputReader) Cancel() bool { r.cancels++; return r.cancelable }
|
||||
func (r *shutdownInputReader) Close() error { r.closes++; return nil }
|
||||
|
||||
func TestShutdownWaitsForCancelableInput(t *testing.T) {
|
||||
for _, kill := range []bool{false, true} {
|
||||
name := "quit"
|
||||
if kill {
|
||||
name = "kill"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
p := NewProgram(&testModel{}, WithOutput(io.Discard))
|
||||
r := &shutdownInputReader{cancelable: true}
|
||||
p.cancelReader = r
|
||||
p.readLoopDone = make(chan struct{})
|
||||
stopped := make(chan struct{})
|
||||
go func() { p.shutdown(kill); close(stopped) }()
|
||||
synctest.Wait()
|
||||
if r.cancels != 1 || r.closes != 0 {
|
||||
t.Errorf("before read loop completion: cancel=%d close=%d", r.cancels, r.closes)
|
||||
}
|
||||
select {
|
||||
case <-stopped:
|
||||
t.Error("shutdown returned before the input loop finished")
|
||||
default:
|
||||
}
|
||||
close(p.readLoopDone)
|
||||
synctest.Wait()
|
||||
<-stopped
|
||||
if r.closes != 1 {
|
||||
t.Errorf("close calls after input completion: got %d, want 1", r.closes)
|
||||
}
|
||||
p.shutdown(kill)
|
||||
if r.cancels != 1 || r.closes != 1 {
|
||||
t.Errorf("repeated shutdown: cancel=%d close=%d", r.cancels, r.closes)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestShutdownDefersCloseAfterInputTimeout(t *testing.T) {
|
||||
for _, kill := range []bool{false, true} {
|
||||
name := "quit"
|
||||
if kill {
|
||||
name = "kill"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
p := NewProgram(&testModel{}, WithOutput(io.Discard))
|
||||
r := &shutdownInputReader{cancelable: true}
|
||||
p.cancelReader = r
|
||||
done := make(chan struct{})
|
||||
p.readLoopDone = done
|
||||
stopped := make(chan struct{})
|
||||
go func() { p.shutdown(kill); close(stopped) }()
|
||||
synctest.Wait()
|
||||
time.Sleep(time.Second)
|
||||
synctest.Wait()
|
||||
select {
|
||||
case <-stopped:
|
||||
default:
|
||||
t.Error("shutdown did not retain its bounded wait")
|
||||
}
|
||||
if r.closes != 0 {
|
||||
t.Errorf("reader closed while its input loop was still active: %d", r.closes)
|
||||
}
|
||||
// Cleanup must retain this reader, not follow a later field assignment.
|
||||
replacement := &shutdownInputReader{}
|
||||
p.cancelReader = replacement
|
||||
p.readLoopDone = make(chan struct{})
|
||||
close(done)
|
||||
synctest.Wait()
|
||||
if r.closes != 1 || replacement.closes != 0 {
|
||||
t.Errorf("close calls: original=%d replacement=%d", r.closes, replacement.closes)
|
||||
}
|
||||
<-stopped
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A reader that shutdown closed must not be closed again when a later run
|
||||
// replaces it: closing a cancel reader closes raw file descriptors, so a
|
||||
// second close can close an unrelated file that reused the number.
|
||||
func TestShutdownClosesInputOnce(t *testing.T) {
|
||||
p := NewProgram(&testModel{}, WithInput(strings.NewReader("")), WithOutput(io.Discard))
|
||||
r := &shutdownInputReader{cancelable: true}
|
||||
p.cancelReader = r
|
||||
p.readLoopDone = make(chan struct{})
|
||||
close(p.readLoopDone)
|
||||
|
||||
p.shutdown(false)
|
||||
if r.closes != 1 {
|
||||
t.Fatalf("shutdown closed the reader %d times, want 1", r.closes)
|
||||
}
|
||||
|
||||
// The next run starts a new reader in place of the closed one.
|
||||
if err := p.initInputReader(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.closes != 1 {
|
||||
t.Errorf("starting a new reader closed the old one again: %d closes", r.closes)
|
||||
}
|
||||
p.shutdownInput()
|
||||
}
|
||||
|
||||
func TestShutdownInputFallbacks(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
reader bool
|
||||
cancelable bool
|
||||
loop bool
|
||||
finished bool
|
||||
}{
|
||||
{name: "no reader"},
|
||||
{name: "uncancelable", reader: true, loop: true},
|
||||
{name: "no input loop", reader: true, cancelable: true},
|
||||
{name: "finished loop", reader: true, cancelable: true, loop: true, finished: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
p := NewProgram(&testModel{}, WithOutput(io.Discard))
|
||||
r := &shutdownInputReader{cancelable: tc.cancelable}
|
||||
if tc.reader {
|
||||
p.cancelReader = r
|
||||
}
|
||||
if tc.loop {
|
||||
p.readLoopDone = make(chan struct{})
|
||||
if tc.finished {
|
||||
close(p.readLoopDone)
|
||||
}
|
||||
}
|
||||
start := time.Now()
|
||||
p.shutdown(true)
|
||||
if time.Since(start) != 0 {
|
||||
t.Error("input fallback unexpectedly waited")
|
||||
}
|
||||
if tc.reader && (r.cancels != 1 || r.closes != 1) {
|
||||
t.Errorf("fallback cleanup: cancel=%d close=%d", r.cancels, r.closes)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type (
|
||||
inputStartedMsg struct{}
|
||||
inputShutdownModel struct{ ready chan struct{} }
|
||||
)
|
||||
|
||||
func (m inputShutdownModel) Init() Cmd { return func() Msg { return inputStartedMsg{} } }
|
||||
func (m inputShutdownModel) Update(msg Msg) (Model, Cmd) {
|
||||
if _, ok := msg.(inputStartedMsg); ok {
|
||||
close(m.ready)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
func (inputShutdownModel) View() View { return NewView("ready") }
|
||||
|
||||
func TestProgramCanceledInput(t *testing.T) {
|
||||
for _, kill := range []bool{false, true} {
|
||||
name := "context"
|
||||
if kill {
|
||||
name = "kill"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
// A real file exercises the native cancelreader rather than its no-op fallback.
|
||||
reader, writer, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reader.Close()
|
||||
defer writer.Close()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
ready := make(chan struct{})
|
||||
p := NewProgram(inputShutdownModel{ready}, WithContext(ctx), WithInput(reader), WithOutput(io.Discard), WithWindowSize(80, 24), WithoutSignalHandler())
|
||||
result := make(chan error, 1)
|
||||
go func() { _, err := p.Run(); result <- err }()
|
||||
select {
|
||||
case <-ready:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("event loop did not start")
|
||||
}
|
||||
if kill {
|
||||
p.Kill()
|
||||
} else {
|
||||
cancel()
|
||||
}
|
||||
select {
|
||||
case err = <-result:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("program did not stop")
|
||||
}
|
||||
if !errors.Is(err, ErrProgramKilled) {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !kill && !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("missing external cancellation: %v", err)
|
||||
}
|
||||
if _, err := reader.Stat(); err != nil {
|
||||
t.Fatalf("borrowed input was closed: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
11
tea.go
11
tea.go
|
|
@ -1383,16 +1383,7 @@ func (p *Program) shutdown(kill bool) {
|
|||
// Wait for all handlers to finish.
|
||||
p.handlers.shutdown()
|
||||
|
||||
// Check if the cancel reader has been setup before waiting and closing.
|
||||
if p.cancelReader != nil {
|
||||
// Wait for input loop to finish.
|
||||
if p.cancelReader.Cancel() {
|
||||
if !kill {
|
||||
p.waitForReadLoop()
|
||||
}
|
||||
}
|
||||
_ = p.cancelReader.Close()
|
||||
}
|
||||
p.shutdownInput()
|
||||
|
||||
if p.renderer != nil {
|
||||
p.stopRenderer(kill)
|
||||
|
|
|
|||
54
tty.go
54
tty.go
|
|
@ -1,6 +1,7 @@
|
|||
package tea
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
|
|
@ -89,28 +90,67 @@ func (p *Program) initInputReader(cancel bool) error {
|
|||
p.inputScanner = drv
|
||||
p.readLoopDone = make(chan struct{})
|
||||
|
||||
go p.readLoop()
|
||||
go p.readLoop(p.ctx, drv, p.readLoopDone, p.errs)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Program) readLoop() {
|
||||
defer close(p.readLoopDone)
|
||||
// readLoop streams input events to the program until ctx is done or reading
|
||||
// fails. It takes the per-run state it uses as arguments rather than reading
|
||||
// it from p: the loop can outlive [Program.shutdown], see
|
||||
// [Program.shutdownInput], and must not race with a later run replacing it.
|
||||
func (p *Program) readLoop(ctx context.Context, scanner *uv.TerminalReader, done chan struct{}, errs chan error) {
|
||||
defer close(done)
|
||||
|
||||
if err := p.inputScanner.StreamEvents(p.ctx, p.msgs); err != nil {
|
||||
if err := scanner.StreamEvents(ctx, p.msgs); err != nil {
|
||||
select {
|
||||
case <-p.ctx.Done():
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case p.errs <- err:
|
||||
case errs <- err:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const inputReadLoopTimeout = 500 * time.Millisecond
|
||||
|
||||
// shutdownInput cancels input before closing the reader's resources. Keep the
|
||||
// bounded shutdown for slow readers, but retain ownership of a reader that is
|
||||
// still in use until its input loop has actually finished.
|
||||
func (p *Program) shutdownInput() {
|
||||
reader := p.cancelReader
|
||||
if reader == nil {
|
||||
return
|
||||
}
|
||||
// The reader is closed below, or later once its input loop finishes.
|
||||
// Forget it so that a later run doesn't close it again: closing it closes
|
||||
// raw file descriptors, and closing one twice can close an unrelated file
|
||||
// that has since reused the number.
|
||||
p.cancelReader = nil
|
||||
|
||||
if reader.Cancel() && p.readLoopDone != nil {
|
||||
done := p.readLoopDone
|
||||
timer := time.NewTimer(inputReadLoopTimeout)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-timer.C:
|
||||
go func() {
|
||||
<-done
|
||||
_ = reader.Close()
|
||||
}()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
_ = reader.Close()
|
||||
}
|
||||
|
||||
// waitForReadLoop waits for the cancelReader to finish its read loop.
|
||||
func (p *Program) waitForReadLoop() {
|
||||
select {
|
||||
case <-p.readLoopDone:
|
||||
case <-time.After(500 * time.Millisecond): //nolint:mnd
|
||||
case <-time.After(inputReadLoopTimeout):
|
||||
// The read loop hangs, which means the input
|
||||
// cancelReader's cancel function has returned true even
|
||||
// though it was not able to cancel the read.
|
||||
|
|
|
|||
Loading…
Reference in a new issue