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
128 changes: 114 additions & 14 deletions pkgs/chat/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ import (
)

const (
host = "localhost"
port = 23234
host = "localhost"
port = 23234
recipientQueueDepth = 16
)

// sender is the subset of tea.Program used for broadcast. Keeping the
Expand All @@ -35,38 +36,139 @@ type sender interface {
Send(tea.Msg)
}

// recipientQueue serializes delivery to one program. It keeps at most
// recipientQueueDepth messages queued behind the single in-flight Send.
type recipientQueue struct {
program sender
queue chan tea.Msg
stopped chan struct{}
mu sync.Mutex
closed bool
}

func newRecipientQueue(p sender) *recipientQueue {
r := &recipientQueue{
program: p,
queue: make(chan tea.Msg, recipientQueueDepth),
stopped: make(chan struct{}),
}
go r.run()
return r
}

func (r *recipientQueue) enqueue(msg tea.Msg) bool {
r.mu.Lock()
defer r.mu.Unlock()
if r.closed {
return false
}
select {
case r.queue <- msg:
return true
default:
// A stalled recipient is pruned rather than allowing its backlog or
// blocked Send goroutines to grow with room traffic.
r.closed = true
close(r.stopped)
return false
}
}

func (r *recipientQueue) stop() {
r.mu.Lock()
defer r.mu.Unlock()
if !r.closed {
r.closed = true
close(r.stopped)
}
}

func (r *recipientQueue) run() {
for {
select {
case <-r.stopped:
return
default:
}

select {
case <-r.stopped:
return
case msg := <-r.queue:
select {
case <-r.stopped:
return
default:
}
r.program.Send(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
mu sync.RWMutex
progs []sender
mu sync.RWMutex
sendMu sync.Mutex
progs []sender
dispatches map[sender]*recipientQueue
}

// register adds a running program and its ordered delivery worker.
func (a *app) register(p sender) {
a.mu.Lock()
defer a.mu.Unlock()
if a.dispatches == nil {
a.dispatches = make(map[sender]*recipientQueue)
}
if _, exists := a.dispatches[p]; exists {
return
}
a.progs = append(a.progs, p)
a.dispatches[p] = newRecipientQueue(p)
}

// send dispatches a message to all running programs.
// send enqueues a message for each running program in a single broadcast
// order. A recipient can have one in-flight Send and at most
// recipientQueueDepth queued messages; a full queue prunes that recipient.
func (a *app) send(msg tea.Msg) {
a.sendMu.Lock()
defer a.sendMu.Unlock()

a.mu.RLock()
progs := make([]sender, len(a.progs))
copy(progs, a.progs)
progs := append([]sender(nil), a.progs...)
dispatches := make([]*recipientQueue, len(progs))
for i, p := range progs {
dispatches[i] = a.dispatches[p]
}
a.mu.RUnlock()
for _, p := range progs {
go p.Send(msg)
for i, dispatch := range dispatches {
if dispatch == nil || !dispatch.enqueue(msg) {
a.remove(progs[i])
}
}
}

// 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()
var dispatch *recipientQueue
for i, q := range a.progs {
if q == p {
a.progs = append(a.progs[:i], a.progs[i+1:]...)
return
dispatch = a.dispatches[p]
delete(a.dispatches, p)
break
}
}
a.mu.Unlock()
if dispatch != nil {
dispatch.stop()
}
}

func newApp() *app {
Expand Down Expand Up @@ -137,9 +239,7 @@ 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()
a.register(p)
go func() {
p.Wait()
a.remove(p)
Expand Down
Loading
Loading