Skip to content
Closed
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
18 changes: 14 additions & 4 deletions pkgs/chat/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,24 @@ func (a *app) ProgramHandler(s ssh.Session) *tea.Program {
a.mu.Lock()
a.progs = append(a.progs, p)
a.mu.Unlock()
go func() {
p.Wait()
a.remove(p)
}()
// Deregister when the session ends, not via p.Wait(): wish calls
// p.Run() — which initializes the channel Wait receives from — only
// after this handler returns, so an early Wait can block on a nil
// channel forever (and race with Run's initialization). The session
// always outlives the program (wish runs p.Run() synchronously in
// the session handler), so session-end pruning covers every session.
go a.watchSession(s.Context(), p)
Comment thread
dezren39 marked this conversation as resolved.
Resolved

return p
}

// watchSession removes p from the registry once ctx ends. It never touches
// the program itself, so it is safe to start before the program runs.
func (a *app) watchSession(ctx context.Context, p sender) {
<-ctx.Done()
a.remove(p)
}

func main() {
app := newApp()
app.Start()
Expand Down
42 changes: 42 additions & 0 deletions pkgs/chat/main_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"context"
"fmt"
"sync"
"testing"
Expand Down Expand Up @@ -75,6 +76,47 @@ func TestRemoveUnknownIsNoOp(t *testing.T) {
}
}

// TestWatchSessionRemovesOnSessionEnd covers the ProgramHandler waiter
// lifecycle: the watcher is spawned before wish runs the program, so it
// must deregister off the session context — never p.Wait(), whose channel
// Run initializes only after the handler returns.
func TestWatchSessionRemovesOnSessionEnd(t *testing.T) {
a := &app{}
p := &fakeProg{}

a.mu.Lock()
a.progs = append(a.progs, p)
a.mu.Unlock()

ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
a.watchSession(ctx, p)
close(done)
}()

a.mu.RLock()
n := len(a.progs)
a.mu.RUnlock()
if n != 1 {
cancel()
t.Fatalf("registry has %d programs while session is live, want 1", n)
}

cancel()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("watchSession did not return after session context ended")
}

a.mu.RLock()
n = len(a.progs)
a.mu.RUnlock()
if n != 0 {
t.Fatalf("registry has %d programs after session end, want 0", n)
}
}
func TestRegistryConcurrentRegisterSendRemove(t *testing.T) {
a := &app{}
var wg sync.WaitGroup
Expand Down
Loading