chore: merge pull request #1376 from desertwitch/stacked-patches
Before adoption: this commit came in with the history the project adopted, so no landing records it.
(v1-0/3) tea.go: all fixes combined (for convenience/CI)
authored by Ayman Bagabas · committed by GitHub · parents 5a360c9, e24d6b2 · Browse files · 4 files·+346 added−28 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+346 added−28 removed
- other:+346 added−28 removed
Provenance
- Commit
915f65d- Tree
18a4c5f- Author
Ayman Bagabas <ayman.bagabas@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
5a360c9- Parent 2
e24d6b2
4 files changed+346 added−28 removed
modified:options_test.go+11 added
1 package tea2 3 import (4 "bytes"5+ "context"6 "os"7 "sync/atomic"8 "testing"9 )41 unmodified lines51 t.Errorf("expected filter to be set")52 }53 })54 55+ t.Run("external context", func(t *testing.T) {56+ extCtx, extCancel := context.WithCancel(context.Background())57+ defer extCancel()58+59+ p := NewProgram(nil, WithContext(extCtx))60+ if p.externalCtx != extCtx || p.externalCtx == context.Background() {61+ t.Errorf("expected passed in external context, got default (nil)")62+ }63+ })64+65 t.Run("input options", func(t *testing.T) {66 exercise := func(t *testing.T, opt ProgramOption, expect inputType) {67 p := NewProgram(nil, opt)68 if p.inputType != expect {75 unmodified linesmodified:options.go+1 added-1 removed
17 unmodified lines18 // useful if you want to cancel the execution from outside. When a Program gets19 // cancelled it will exit with an error ErrProgramKilled.20 func WithContext(ctx context.Context) ProgramOption {21 return func(p *Program) {22- p.ctx = ctx22+ p.externalCtx = ctx23 }24 }25 26 // WithOutput sets the output which, by default, is stdout. In most cases you226 unmodified linesmodified:tea_test.go+246 added-2 removed
2 unmodified lines3 import (4 "bytes"5 "context"6 "errors"7+ "sync"8 "sync/atomic"9 "testing"10 "time"11 )12 13+type ctxImplodeMsg struct {14+ cancel context.CancelFunc15+}16+17 type incrementMsg struct{}18 19+type panicMsg struct{}20+21 type testModel struct {22 executed atomic.Value23 counter atomic.Value24 }2 unmodified lines27 return nil28 }29 30 func (m *testModel) Update(msg Msg) (Model, Cmd) {24- switch msg.(type) {31+ switch msg := msg.(type) {32+ case ctxImplodeMsg:33+ msg.cancel()34+ time.Sleep(100 * time.Millisecond)35+36 case incrementMsg:37 i := m.counter.Load()38 if i == nil {39 m.counter.Store(1)2 unmodified lines42 }43 44 case KeyMsg:45 return m, Quit46+47+ case panicMsg:48+ panic("testing panic behavior")49 }50 51 return m, nil52 }41 unmodified lines94 t.Fatal(err)95 }96 }97 98+func TestTeaWaitQuit(t *testing.T) {99+ var buf bytes.Buffer100+ var in bytes.Buffer101+102+ progStarted := make(chan struct{})103+ waitStarted := make(chan struct{})104+ errChan := make(chan error, 1)105+106+ m := &testModel{}107+ p := NewProgram(m, WithInput(&in), WithOutput(&buf))108+109+ go func() {110+ _, err := p.Run()111+ errChan <- err112+ }()113+114+ go func() {115+ for {116+ time.Sleep(time.Millisecond)117+ if m.executed.Load() != nil {118+ close(progStarted)119+120+ <-waitStarted121+ time.Sleep(50 * time.Millisecond)122+ p.Quit()123+124+ return125+ }126+ }127+ }()128+129+ <-progStarted130+131+ var wg sync.WaitGroup132+ for i := 0; i < 5; i++ {133+ wg.Add(1)134+ go func() {135+ p.Wait()136+ wg.Done()137+ }()138+ }139+ close(waitStarted)140+ wg.Wait()141+142+ err := <-errChan143+ if err != nil {144+ t.Fatalf("Expected nil, got %v", err)145+ }146+}147+148+func TestTeaWaitKill(t *testing.T) {149+ var buf bytes.Buffer150+ var in bytes.Buffer151+152+ progStarted := make(chan struct{})153+ waitStarted := make(chan struct{})154+ errChan := make(chan error, 1)155+156+ m := &testModel{}157+ p := NewProgram(m, WithInput(&in), WithOutput(&buf))158+159+ go func() {160+ _, err := p.Run()161+ errChan <- err162+ }()163+164+ go func() {165+ for {166+ time.Sleep(time.Millisecond)167+ if m.executed.Load() != nil {168+ close(progStarted)169+170+ <-waitStarted171+ time.Sleep(50 * time.Millisecond)172+ p.Kill()173+174+ return175+ }176+ }177+ }()178+179+ <-progStarted180+181+ var wg sync.WaitGroup182+ for i := 0; i < 5; i++ {183+ wg.Add(1)184+ go func() {185+ p.Wait()186+ wg.Done()187+ }()188+ }189+ close(waitStarted)190+ wg.Wait()191+192+ err := <-errChan193+ if !errors.Is(err, ErrProgramKilled) {194+ t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)195+ }196+}197+198 func TestTeaWithFilter(t *testing.T) {199 testTeaWithFilter(t, 0)200 testTeaWithFilter(t, 1)201 testTeaWithFilter(t, 2)49 unmodified lines251 }252 }253 }()254 255+ _, err := p.Run()256+141- if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) {257+ if !errors.Is(err, ErrProgramKilled) {258 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)259 }260+261+ if errors.Is(err, context.Canceled) {262+ // The end user should not know about the program's internal context state.263+ // The program should only report external context cancellation as a context error.264+ t.Fatalf("Internal context cancellation was reported as context error!")265+ }266 }267 268 func TestTeaContext(t *testing.T) {269 ctx, cancel := context.WithCancel(context.Background())11 unmodified lines281 }282 }283 }()284 285+ _, err := p.Run()286+287+ if !errors.Is(err, ErrProgramKilled) {288+ t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)289+ }290+291+ if !errors.Is(err, context.Canceled) {292+ // The end user should know that their passed in context caused the kill.293+ t.Fatalf("Expected %v, got %v", context.Canceled, err)294+ }295+}296+297+func TestTeaContextImplodeDeadlock(t *testing.T) {298+ ctx, cancel := context.WithCancel(context.Background())299+ var buf bytes.Buffer300+ var in bytes.Buffer301+302+ m := &testModel{}303+ p := NewProgram(m, WithContext(ctx), WithInput(&in), WithOutput(&buf))304+ go func() {305+ for {306+ time.Sleep(time.Millisecond)307+ if m.executed.Load() != nil {308+ p.Send(ctxImplodeMsg{cancel: cancel})309+ return310+ }311+ }312+ }()313+314 if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) {315 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)316 }317 }318 319+func TestTeaContextBatchDeadlock(t *testing.T) {320+ ctx, cancel := context.WithCancel(context.Background())321+ var buf bytes.Buffer322+ var in bytes.Buffer323+324+ inc := func() Msg {325+ cancel()326+ return incrementMsg{}327+ }328+329+ m := &testModel{}330+ p := NewProgram(m, WithContext(ctx), WithInput(&in), WithOutput(&buf))331+ go func() {332+ for {333+ time.Sleep(time.Millisecond)334+ if m.executed.Load() != nil {335+ batch := make(BatchMsg, 100)336+ for i := range batch {337+ batch[i] = inc338+ }339+ p.Send(batch)340+ return341+ }342+ }343+ }()344+345+ if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) {346+ t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)347+ }348+}349+350 func TestTeaBatchMsg(t *testing.T) {351 var buf bytes.Buffer352 var in bytes.Buffer353 94 unmodified lines448 449 m := &testModel{}450 NewProgram(m, WithInput(&in), WithOutput(&buf))451 }452+453+func TestTeaPanic(t *testing.T) {454+ var buf bytes.Buffer455+ var in bytes.Buffer456+457+ m := &testModel{}458+ p := NewProgram(m, WithInput(&in), WithOutput(&buf))459+ go func() {460+ for {461+ time.Sleep(time.Millisecond)462+ if m.executed.Load() != nil {463+ p.Send(panicMsg{})464+ return465+ }466+ }467+ }()468+469+ _, err := p.Run()470+471+ if !errors.Is(err, ErrProgramPanic) {472+ t.Fatalf("Expected %v, got %v", ErrProgramPanic, err)473+ }474+475+ if !errors.Is(err, ErrProgramKilled) {476+ t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)477+ }478+}479+480+func TestTeaGoroutinePanic(t *testing.T) {481+ var buf bytes.Buffer482+ var in bytes.Buffer483+484+ panicCmd := func() Msg {485+ panic("testing goroutine panic behavior")486+ }487+488+ m := &testModel{}489+ p := NewProgram(m, WithInput(&in), WithOutput(&buf))490+ go func() {491+ for {492+ time.Sleep(time.Millisecond)493+ if m.executed.Load() != nil {494+ batch := make(BatchMsg, 10)495+ for i := range batch {496+ batch[i] = panicCmd497+ }498+ p.Send(batch)499+ return500+ }501+ }502+ }()503+504+ _, err := p.Run()505+506+ if !errors.Is(err, ErrProgramPanic) {507+ t.Fatalf("Expected %v, got %v", ErrProgramPanic, err)508+ }509+510+ if !errors.Is(err, ErrProgramKilled) {511+ t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)512+ }513+}modified:tea.go+88 added-25 removed
25 unmodified lines26 "github.com/muesli/cancelreader"27 "golang.org/x/sync/errgroup"28 )29 30+// ErrProgramPanic is returned by [Program.Run] when the program recovers from a panic.31+var ErrProgramPanic = errors.New("program experienced a panic")32+33 // ErrProgramKilled is returned by [Program.Run] when the program gets killed.34 var ErrProgramKilled = errors.New("program was killed")35 36 // ErrInterrupted is returned by [Program.Run] when the program get a SIGINT112 unmodified lines149 startupTitle string150 151 inputType inputType152 153+ // externalCtx is a context that was passed in via WithContext, otherwise defaulting154+ // to ctx.Background() (in case it was not), the internal context is derived from it.155+ externalCtx context.Context156+157+ // ctx is the programs's internal context for signalling internal teardown.158+ // It is built and derived from the externalCtx in NewProgram().159 ctx context.Context160 cancel context.CancelFunc161 162 msgs chan Msg88 unmodified lines251 }252 253 // A context can be provided with a ProgramOption, but if none was provided254 // we'll use the default background context.246- if p.ctx == nil {247- p.ctx = context.Background()255+ if p.externalCtx == nil {256+ p.externalCtx = context.Background()257 }258 // Initialize context and teardown channel.250- p.ctx, p.cancel = context.WithCancel(p.ctx)259+ p.ctx, p.cancel = context.WithCancel(p.externalCtx)260 261 // if no output was set, set it to stdout262 if p.output == nil {263 p.output = os.Stdout90 unmodified lines354 // until Cmd returns.355 go func() {356 // Recover from panics.357 if !p.startupOptions.has(withoutCatchPanics) {349- defer p.recoverFromPanic()358+ defer func() {359+ if r := recover(); r != nil {360+ p.recoverFromGoPanic(r)361+ }362+ }()363 }364 365 msg := cmd() // this can be long.366 p.Send(msg)105 unmodified lines472 p.exec(msg.cmd, msg.fn)473 474 case BatchMsg:475 for _, cmd := range msg {463- cmds <- cmd476+ select {477+ case <-p.ctx.Done():478+ return model, nil479+ case cmds <- cmd:480+ }481 }482 continue483 484 case sequenceMsg:37 unmodified lines522 }523 524 var cmd Cmd525 model, cmd = model.Update(msg) // run update526+527+ select {528+ case <-p.ctx.Done():529+ return model, nil509- cmds <- cmd // process command (if any)530+ case cmds <- cmd: // process command (if any)531+ }532+533 p.renderer.write(model.View()) // send view to renderer534 }535 }536 }537 538 // Run initializes the program and runs its event loops, blocking until it gets539 // terminated by either [Program.Quit], [Program.Kill], or its signal handler.540 // Returns the final model.518-func (p *Program) Run() (Model, error) {541+func (p *Program) Run() (returnModel Model, returnErr error) {542 p.handlers = channelHandlers{}543 cmds := make(chan Cmd)521- p.errs = make(chan error)522- p.finished = make(chan struct{}, 1)544+ p.errs = make(chan error, 1)545 546+ p.finished = make(chan struct{})547+ defer func() {548+ close(p.finished)549+ }()550+551 defer p.cancel()552 553 switch p.inputType {554 case defaultInput:39 unmodified lines594 }595 596 // Recover from panics.597 if !p.startupOptions.has(withoutCatchPanics) {571- defer p.recoverFromPanic()598+ defer func() {599+ if r := recover(); r != nil {600+ returnErr = fmt.Errorf("%w: %w", ErrProgramKilled, ErrProgramPanic)601+ p.recoverFromPanic(r)602+ }603+ }()604 }605 606 // If no renderer is set use the standard one.607 if p.renderer == nil {68 unmodified lines676 p.handlers.add(p.handleCommands(cmds))677 678 // Run event loop, handle updates and draw.679 model, err := p.eventLoop(model, cmds)648- killed := p.ctx.Err() != nil || err != nil649- if killed && err == nil {650- err = fmt.Errorf("%w: %s", ErrProgramKilled, p.ctx.Err())680+681+ if err == nil && len(p.errs) > 0 {682+ err = <-p.errs // Drain a leftover error in case eventLoop crashed683 }652- if err == nil {684+685+ killed := p.externalCtx.Err() != nil || p.ctx.Err() != nil || err != nil686+ if killed {687+ if err == nil && p.externalCtx.Err() != nil {688+ // Return also as context error the cancellation of an external context.689+ // This is the context the user knows about and should be able to act on.690+ err = fmt.Errorf("%w: %w", ErrProgramKilled, p.externalCtx.Err())691+ } else if err == nil && p.ctx.Err() != nil {692+ // Return only that the program was killed (not the internal mechanism).693+ // The user does not know or need to care about the internal program context.694+ err = ErrProgramKilled695+ } else {696+ // Return that the program was killed and also the error that caused it.697+ err = fmt.Errorf("%w: %w", ErrProgramKilled, err)698+ }699+ } else {700+ // Graceful shutdown of the program (not killed):701 // Ensure we rendered the final state of the model.702 p.renderer.write(model.View())703 }704 46 unmodified lines751 func (p *Program) Quit() {752 p.Send(Quit())753 }754 707-// Kill stops the program immediately and restores the former terminal state.755+// Kill signals the program to stop immediately and restore the former terminal state.756 // The final render that you would normally see when quitting will be skipped.757 // [program.Run] returns a [ErrProgramKilled] error.758 func (p *Program) Kill() {711- p.shutdown(true)759+ p.cancel()760 }761 762 // Wait waits/blocks until the underlying Program finished shutting down.763 func (p *Program) Wait() {764 <-p.finished765 }766 767 // shutdown performs operations to free up resources and restore the terminal720-// to its original state.768+// to its original state. It is called once at the end of the program's lifetime.769+//770+// This method should not be called to signal the program to be killed/shutdown.771+// Doing so can lead to race conditions with the eventual call at the program's end.772+// As alternatives, the [Quit] or [Kill] convenience methods should be used instead.773 func (p *Program) shutdown(kill bool) {774 p.cancel()775 776 // Wait for all handlers to finish.18 unmodified lines795 }796 }797 798 _ = p.restoreTerminalState()747- if !kill {748- p.finished <- struct{}{}749- }799 }800 801 // recoverFromPanic recovers from a panic, prints the stack trace, and restores802 // the terminal to a usable state.754-func (p *Program) recoverFromPanic() {755- if r := recover(); r != nil {756- p.shutdown(true)757- fmt.Printf("Caught panic:\n\n%s\n\nRestoring terminal...\n\n", r)758- debug.PrintStack()803+func (p *Program) recoverFromPanic(r interface{}) {804+ select {805+ case p.errs <- ErrProgramPanic:806+ default:807 }808+ p.shutdown(true) // Ok to call here, p.Run() cannot do it anymore.809+ fmt.Printf("Caught panic:\n\n%s\n\nRestoring terminal...\n\n", r)810+ debug.PrintStack()811 }812 813+// recoverFromGoPanic recovers from a goroutine panic, prints a stack trace and814+// signals for the program to be killed and terminal restored to a usable state.815+func (p *Program) recoverFromGoPanic(r interface{}) {816+ select {817+ case p.errs <- ErrProgramPanic:818+ default:819+ }820+ p.cancel()821+ fmt.Printf("Caught goroutine panic:\n\n%s\n\nRestoring terminal...\n\n", r)822+ debug.PrintStack()823+}824+825 // ReleaseTerminal restores the original terminal state and cancels the input826 // reader. You can return control to the Program with RestoreTerminal.827 func (p *Program) ReleaseTerminal() error {828 atomic.StoreUint32(&p.ignoreSignals, 1)76 unmodified lines