Files

92 lines
2.5 KiB
Go

package server
import (
"sync"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// terminalClientQueue bounds the frames waiting for one slow connection.
// A full queue drops output frames; the client sees the gap in the next
// frame's offset and reads the retained tail again (terminal_output after).
const terminalClientQueue = 256
// terminalClients delivers terminal_event frames to open connections, in
// order per connection: lifecycle changes to every connection, output only
// to connections subscribed to that terminal (by terminal_open or
// terminal_output). It holds each connection's serialized write function,
// never the socket. The zero value is ready to use.
type terminalClients struct {
mu sync.Mutex
clients map[string]*terminalClient
}
type terminalClient struct {
ch chan protocol.Message
done chan struct{}
subs map[string]bool
}
func (c *terminalClients) attach(clientID string, write func(protocol.Message) error) {
client := &terminalClient{ch: make(chan protocol.Message, terminalClientQueue), done: make(chan struct{}), subs: map[string]bool{}}
c.mu.Lock()
if c.clients == nil {
c.clients = map[string]*terminalClient{}
}
if old := c.clients[clientID]; old != nil {
close(old.done)
}
c.clients[clientID] = client
c.mu.Unlock()
go func() {
for {
select {
case <-client.done:
return
case msg := <-client.ch:
if write(msg) != nil {
return
}
}
}
}()
}
func (c *terminalClients) detach(clientID string) {
c.mu.Lock()
defer c.mu.Unlock()
if client := c.clients[clientID]; client != nil {
close(client.done)
delete(c.clients, clientID)
}
}
// subscribe sends terminalID's output frames to clientID from now on.
func (c *terminalClients) subscribe(clientID, terminalID string) {
c.mu.Lock()
defer c.mu.Unlock()
if client := c.clients[clientID]; client != nil {
client.subs[terminalID] = true
}
}
// publish queues frame for its recipients without blocking: a lifecycle
// change for everyone, output for the terminal's subscribers.
func (c *terminalClients) publish(frame protocol.TerminalEventFrame) {
msg := protocol.Message{Type: protocol.TerminalEvent, TerminalEvent: &frame}
c.mu.Lock()
defer c.mu.Unlock()
for _, client := range c.clients {
if frame.Terminal == nil && !client.subs[frame.TerminalID] {
continue
}
if frame.Terminal != nil && frame.Terminal.Status == protocol.TerminalClosed {
delete(client.subs, frame.TerminalID)
}
select {
case client.ch <- msg:
default:
}
}
}