feat(client): implement server-initiated mode with WebSocket support

This commit is contained in:
2026-06-14 12:47:30 +02:00
parent 1054d4b9d0
commit a8c9bdbffb
4 changed files with 246 additions and 47 deletions

View File

@@ -17,6 +17,7 @@ import (
"github.com/Sendspin/sendspin-go/pkg/audio/decode"
"github.com/Sendspin/sendspin-go/pkg/protocol"
"github.com/Sendspin/sendspin-go/pkg/sync"
"github.com/gorilla/websocket"
)
// Time-sync burst parameters. Mirrors sendspin-cpp's TimeBurst defaults and
@@ -109,6 +110,12 @@ type Receiver struct {
// from r.clockSync.ServerMicrosNow so tests can drive the
// timestamp-deferral path with a fake clock.
clockNow func() int64
// closeOnce guards Close so it is idempotent: in server-initiated mode
// a listener may evict a session via CloseConnection (which closes the
// receiver) while Accept's own deferred Close also fires. Without this
// the second close(r.output) panics.
closeOnce stdsync.Once
}
// NewReceiver creates a new Receiver with the given configuration.
@@ -189,17 +196,59 @@ func (r *Receiver) Stats() ReceiverStats {
return stats
}
// Connect establishes a connection to the server, performs initial clock sync,
// and starts background goroutines for connection watching and clock sync.
// Connect establishes a client-initiated connection to the server (dials
// ServerAddr), performs initial clock sync, and starts background goroutines
// for connection watching and clock sync.
func (r *Receiver) Connect() error {
clientConfig, err := r.buildClientConfig()
if err != nil {
return err
}
r.client = protocol.NewClient(clientConfig)
if err := r.client.Connect(); err != nil {
return fmt.Errorf("connection failed: %w", err)
}
log.Printf("Connected to server: %s", r.serverAddr)
return r.startSession()
}
// AcceptConn drives the receiver protocol over an already-established
// WebSocket connection (server-initiated mode: the server discovered this
// player via mDNS and dialed it). The client still sends client/hello first
// per spec, so the handshake and message loop are identical to Connect once
// the socket exists. The caller transfers ownership of conn; Close() (or a
// dropped connection) closes it.
func (r *Receiver) AcceptConn(conn *websocket.Conn) error {
clientConfig, err := r.buildClientConfig()
if err != nil {
return err
}
r.client = protocol.NewClientFromConn(clientConfig, conn)
if err := r.client.Start(); err != nil {
return fmt.Errorf("handshake failed: %w", err)
}
log.Printf("Accepted server-initiated connection from %s", conn.RemoteAddr())
return r.startSession()
}
// buildClientConfig validates required fields and assembles the protocol
// client config (advertised formats, device info, role support) shared by
// both the client-initiated (Connect) and server-initiated (AcceptConn) paths.
func (r *Receiver) buildClientConfig() (protocol.Config, error) {
if r.config.ClientID == "" {
return fmt.Errorf("ReceiverConfig.ClientID is required (resolve via sendspin.ResolveClientID)")
return protocol.Config{}, fmt.Errorf("ReceiverConfig.ClientID is required (resolve via sendspin.ResolveClientID)")
}
supportedFormats := buildSupportedFormats(r.config.PreferredCodec, r.config.MaxSampleRate, r.config.MaxBitDepth)
logAdvertisedFormats(supportedFormats, r.config.MaxSampleRate, r.config.MaxBitDepth)
clientConfig := protocol.Config{
return protocol.Config{
ServerAddr: r.serverAddr,
ClientID: r.config.ClientID,
Name: r.config.PlayerName,
@@ -222,15 +271,13 @@ func (r *Receiver) Connect() error {
VisualizerV1Support: &protocol.VisualizerV1Support{
BufferCapacity: r.config.BufferCapacity,
},
}
}, nil
}
r.client = protocol.NewClient(clientConfig)
if err := r.client.Connect(); err != nil {
return fmt.Errorf("connection failed: %w", err)
}
log.Printf("Connected to server: %s", r.serverAddr)
// startSession marks the receiver connected, runs the initial clock-sync
// burst, and launches the background goroutines. Shared by Connect and
// AcceptConn; r.client must already be started.
func (r *Receiver) startSession() error {
r.connected = true
if err := r.performInitialSync(); err != nil {
@@ -795,29 +842,31 @@ func (r *Receiver) notifyError(err error) {
}
func (r *Receiver) Close() error {
// Send goodbye BEFORE cancelling the context so the message
// reaches the server while the connection is still alive.
if r.client != nil {
r.client.SendGoodbye("shutdown")
}
r.cancel()
if r.client != nil {
r.client.Close()
}
if r.scheduler != nil {
r.scheduler.Stop()
}
if r.decoder != nil {
if err := r.decoder.Close(); err != nil {
log.Printf("Receiver: decoder close error: %v", err)
r.closeOnce.Do(func() {
// Send goodbye BEFORE cancelling the context so the message
// reaches the server while the connection is still alive.
if r.client != nil {
r.client.SendGoodbye("shutdown")
}
}
close(r.output)
r.cancel()
if r.client != nil {
r.client.Close()
}
if r.scheduler != nil {
r.scheduler.Stop()
}
if r.decoder != nil {
if err := r.decoder.Close(); err != nil {
log.Printf("Receiver: decoder close error: %v", err)
}
}
close(r.output)
})
return nil
}