75 lines
2.3 KiB
Go
75 lines
2.3 KiB
Go
package agent
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"net/http"
|
|
|
|
"github.com/coder/websocket"
|
|
"github.com/rvbox/rvbox/internal/agentproto"
|
|
"github.com/rvbox/rvbox/internal/agentwire"
|
|
)
|
|
|
|
var ErrUnexpectedMessage = errors.New("agent transport received a non-binary WebSocket message")
|
|
|
|
type WebSocketTransport struct{ connection *agentwire.Conn }
|
|
|
|
func DialWebSocket(ctx context.Context, address string, client *http.Client) (*WebSocketTransport, error) {
|
|
return DialWebSocketWithLimits(ctx, address, client, agentproto.DefaultLimits())
|
|
}
|
|
|
|
// DialWebSocketWithLimits applies the same message ceiling as envelope
|
|
// validation. The library's 32 KiB default is smaller than ordinary RVBox
|
|
// chunks, dispatches, and reconciliation history.
|
|
func DialWebSocketWithLimits(ctx context.Context, address string, client *http.Client, limits agentproto.Limits) (*WebSocketTransport, error) {
|
|
readLimit := limits.MaxEnvelopeBytes
|
|
if readLimit == 0 {
|
|
readLimit = agentproto.DefaultLimits().MaxEnvelopeBytes
|
|
}
|
|
if readLimit > math.MaxInt64-1 {
|
|
return nil, fmt.Errorf("invalid WebSocket envelope limit: %d", readLimit)
|
|
}
|
|
raw, _, err := websocket.Dial(ctx, address, &websocket.DialOptions{
|
|
HTTPClient: client, CompressionMode: websocket.CompressionDisabled, Subprotocols: []string{agentwire.Subprotocol},
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
connection, err := agentwire.Wrap(raw, readLimit, nil)
|
|
if err != nil {
|
|
_ = raw.CloseNow()
|
|
return nil, err
|
|
}
|
|
return &WebSocketTransport{connection: connection}, nil
|
|
}
|
|
|
|
func (transport *WebSocketTransport) Write(ctx context.Context, payload []byte) error {
|
|
if transport == nil || transport.connection == nil {
|
|
return ErrSessionClosed
|
|
}
|
|
return transport.connection.Write(ctx, websocket.MessageBinary, payload)
|
|
}
|
|
|
|
func (transport *WebSocketTransport) Read(ctx context.Context) ([]byte, error) {
|
|
if transport == nil || transport.connection == nil {
|
|
return nil, ErrSessionClosed
|
|
}
|
|
kind, payload, err := transport.connection.Read(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if kind != websocket.MessageBinary {
|
|
return nil, ErrUnexpectedMessage
|
|
}
|
|
return payload, nil
|
|
}
|
|
|
|
func (transport *WebSocketTransport) Close() error {
|
|
if transport == nil || transport.connection == nil {
|
|
return nil
|
|
}
|
|
return transport.connection.Close(websocket.StatusNormalClosure, "")
|
|
}
|