package agentwire import ( "context" "errors" "io" "math" "sync" "github.com/coder/websocket" ) type incoming struct { kind websocket.MessageType payload []byte err error } // Conn owns one bounded read pump so WebSocket Ping/Pong is processed even // while a caller is writing a large hello/reconciliation message. Application // readers see only complete logical messages. Legacy peers retain raw protobuf. type Conn struct { *websocket.Conn maximum uint64 chunked bool cancel context.CancelFunc read chan incoming writeMu sync.Mutex } func Wrap(raw *websocket.Conn, maximum uint64, activity func()) (*Conn, error) { if raw == nil || maximum == 0 || maximum > math.MaxInt64-1 { return nil, ErrMessageTooBig } chunked := raw.Subprotocol() == Subprotocol if chunked { raw.SetReadLimit(PacketBytes) } else { raw.SetReadLimit(int64(maximum)) } ctx, cancel := context.WithCancel(context.Background()) connection := &Conn{Conn: raw, maximum: maximum, chunked: chunked, cancel: cancel, read: make(chan incoming, 1)} go connection.readLoop(ctx, activity) return connection, nil } func (connection *Conn) readLoop(ctx context.Context, activity func()) { defer close(connection.read) decoder := Decoder{Maximum: connection.maximum} for { kind, payload, err := connection.Conn.Read(ctx) if err == nil && kind == websocket.MessageBinary && connection.chunked { payload, err = decoder.Push(payload) if err != nil { code := websocket.StatusPolicyViolation if errors.Is(err, ErrMessageTooBig) { code = websocket.StatusMessageTooBig } _ = connection.Conn.Close(code, err.Error()) } } if err != nil { _ = connection.Conn.CloseNow() select { case connection.read <- incoming{err: err}: case <-ctx.Done(): } return } if activity != nil { activity() } if connection.chunked && kind == websocket.MessageBinary && payload == nil { // Incomplete fragment. continue } select { case connection.read <- incoming{kind: kind, payload: payload}: case <-ctx.Done(): return } } } func (connection *Conn) Read(ctx context.Context) (websocket.MessageType, []byte, error) { select { case frame, ok := <-connection.read: if !ok { return 0, nil, io.EOF } return frame.kind, frame.payload, frame.err case <-ctx.Done(): return 0, nil, ctx.Err() } } // Encode is used by the server's sole queue writer so it can yield to control // messages and check heartbeats between data packets. Each lane stays ordered. func (connection *Conn) Encode(payload []byte, priority bool) (*Encoder, error) { return NewEncoder(payload, connection.maximum, connection.chunked, priority) } func (connection *Conn) WritePacket(ctx context.Context, packet []byte) error { return connection.Conn.Write(ctx, websocket.MessageBinary, packet) } func (connection *Conn) Write(ctx context.Context, kind websocket.MessageType, payload []byte) error { if kind != websocket.MessageBinary { return errors.New("agent transport writes must be binary") } encoder, err := connection.Encode(payload, false) if err != nil { return err } connection.writeMu.Lock() defer connection.writeMu.Unlock() for { packet, last := encoder.Next() if err := connection.WritePacket(ctx, packet); err != nil { _ = connection.CloseNow() return err } if last { return nil } } } func (connection *Conn) Close(code websocket.StatusCode, reason string) error { defer connection.cancel() return connection.Conn.Close(code, reason) } func (connection *Conn) CloseNow() error { connection.cancel() return connection.Conn.CloseNow() }