Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 38 additions & 3 deletions pkgs/chat/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"

Expand All @@ -26,19 +27,47 @@ const (
port = 23234
)

// app contains a wish server and the list of running programs.
// sender is the subset of tea.Program used for broadcast. Keeping the
// registry behind this interface lets tests exercise pruning and
// synchronization without running real terminal programs.
type sender interface {
Send(tea.Msg)
}

// app contains a wish server and the registry of running programs.
// The registry is guarded by mu: sessions register on connect and are
// pruned when their program ends, so dead sessions neither accumulate
// nor receive fan-out traffic.
type app struct {
*ssh.Server
progs []*tea.Program
mu sync.RWMutex
progs []sender
}

// send dispatches a message to all running programs.
func (a *app) send(msg tea.Msg) {
for _, p := range a.progs {
a.mu.RLock()
progs := make([]sender, len(a.progs))
copy(progs, a.progs)
a.mu.RUnlock()
for _, p := range progs {
go p.Send(msg)
}
}

// remove drops a finished program from the registry. Removing an
// unknown program is a no-op.
func (a *app) remove(p sender) {
a.mu.Lock()
defer a.mu.Unlock()
for i, q := range a.progs {
if q == p {
a.progs = append(a.progs[:i], a.progs[i+1:]...)
return
}
}
}

func newApp() *app {
a := new(app)

Expand Down Expand Up @@ -89,7 +118,13 @@ func (a *app) ProgramHandler(s ssh.Session) *tea.Program {
model.id = s.User()

p := tea.NewProgram(model, tea.WithOutput(s), tea.WithInput(s))
a.mu.Lock()
a.progs = append(a.progs, p)
a.mu.Unlock()
go func() {
p.Wait()
a.remove(p)
Comment on lines +124 to +126

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Synchronize the completion waiter with program startup

If this goroutine runs before Wish starts the program, p.Wait() blocks forever: in the pinned Bubble Tea v0.25.0 implementation, finished is initialized by Run, not NewProgram, and Wait receives directly from that channel. The Wish middleware calls this handler before p.Run(), so there is no initialization ordering guarantee. An early waiter receives from a nil channel permanently, leaking the new goroutine and preventing that session from ever being deregistered; concurrent initialization also introduces a data race. Tie removal to a lifecycle hook with guaranteed startup ordering or to the return of Run.

Useful? React with 👍 / 👎.

}()

return p
}
Expand Down
103 changes: 103 additions & 0 deletions pkgs/chat/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package main

import (
"fmt"
"sync"
"testing"
"time"

tea "github.com/charmbracelet/bubbletea"
)

// fakeProg records every message sent to it. It satisfies sender without
// running a real terminal program.
type fakeProg struct {
mu sync.Mutex
msgs []tea.Msg
}

func (f *fakeProg) Send(msg tea.Msg) {
f.mu.Lock()
defer f.mu.Unlock()
f.msgs = append(f.msgs, msg)
}

func (f *fakeProg) count() int {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.msgs)
}

func waitFor(t *testing.T, what string, cond func() bool) {
t.Helper()
for i := 0; i < 200; i++ {
if cond() {
return
}
time.Sleep(5 * time.Millisecond)
}
t.Fatalf("timed out waiting for %s", what)
}

func TestSendReachesOnlyLivePrograms(t *testing.T) {
a := &app{}
live, dead := &fakeProg{}, &fakeProg{}

a.mu.Lock()
a.progs = append(a.progs, live, dead)
a.mu.Unlock()

a.send(chatMsg{id: "u1", text: "hello"})
waitFor(t, "initial fan-out", func() bool {
return live.count() == 1 && dead.count() == 1
})

a.remove(dead)
if n := len(a.progs); n != 1 {
t.Fatalf("registry has %d programs after remove, want 1", n)
}

a.send(chatMsg{id: "u1", text: "again"})
waitFor(t, "second fan-out", func() bool { return live.count() == 2 })
if got := dead.count(); got != 1 {
t.Fatalf("removed program received %d messages, want 1", got)
}
}

func TestRemoveUnknownIsNoOp(t *testing.T) {
a := &app{}
kept := &fakeProg{}
a.progs = append(a.progs, kept)

a.remove(&fakeProg{})
if n := len(a.progs); n != 1 {
t.Fatalf("registry has %d programs after removing unknown, want 1", n)
}
}

func TestRegistryConcurrentRegisterSendRemove(t *testing.T) {
a := &app{}
var wg sync.WaitGroup
for i := 0; i < 16; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
p := &fakeProg{}
a.mu.Lock()
a.progs = append(a.progs, p)
a.mu.Unlock()
for j := 0; j < 25; j++ {
a.send(chatMsg{id: fmt.Sprint(i), text: "m"})
}
a.remove(p)
}(i)
}
wg.Wait()

a.mu.RLock()
n := len(a.progs)
a.mu.RUnlock()
if n != 0 {
t.Fatalf("registry has %d programs after concurrent use, want 0", n)
}
}