package server import ( "context" "sync" "github.com/coder/websocket" "github.com/coder/websocket/wsjson" "git.a-wan.net/alan/pipelines/internal/protocol" ) // connectionQueue bounds the requests read ahead of their handling on one // connection, per lane. The app sends one ordinary request at a time, so // the ordinary lane rarely holds more than a few. const connectionQueue = 256 // isTerminalLaneRequest reports the requests a connection handles on its // terminal lane: what a terminal's keystrokes and size become. They are // quick (a queued write, an ioctl, an output acknowledgement) and ordered // among themselves, and must // never wait behind an ordinary request read before them on the same // connection (an elevation's password check, a chat backend call). func isTerminalLaneRequest(kind string) bool { switch kind { case protocol.TerminalInput, protocol.TerminalResize, protocol.TerminalAck, protocol.ChatShellInput, protocol.ChatShellResize: return true } return false } // readConnectionRequests reads conn's requests until it fails or ctx ends. // Terminal-lane requests are handled in arrival order by lane on a goroutine // of their own; the others are returned, in arrival order, for the // connection's ordinary loop, and the channel closes when reading stops. // Order is kept within each lane, not across them: a client that needs a // terminal request to follow an ordinary one (input after terminal_open) // waits for its reply first. stop ends the reading and waits for the lane // to finish what it took. func readConnectionRequests(ctx context.Context, conn *websocket.Conn, lane func(context.Context, protocol.Message)) (requests <-chan protocol.Message, stop func()) { ctx, cancel := context.WithCancel(ctx) ordinary := make(chan protocol.Message, connectionQueue) terminal := make(chan protocol.Message, connectionQueue) var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() for request := range terminal { lane(ctx, request) } }() go func() { defer wg.Done() defer close(ordinary) defer close(terminal) for { var request protocol.Message if err := wsjson.Read(ctx, conn, &request); err != nil { return } queue := ordinary if isTerminalLaneRequest(request.Type) { queue = terminal } select { case queue <- request: case <-ctx.Done(): return } } }() return ordinary, func() { cancel() wg.Wait() } }