websocket

package
v1.67.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 10, 2024 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultConnectionInitTimeOut = "15s"

	HeaderSecWebSocketProtocol = "Sec-WebSocket-Protocol"
)
View Source
const (
	GraphQLTransportWSHeartbeatPayload = `{"type":"heartbeat"}`
)

Variables

View Source
var DefaultProtocol = ProtocolGraphQLTransportWS
View Source
var ErrGraphQLWSUnexpectedMessageType = errors.New("unexpected message type")

Functions

func Handle

func Handle(done chan bool, errChan chan error, conn net.Conn, executorPool subscription.ExecutorPool, options ...HandleOptionFunc)

Handle will handle the websocket subscription. It can take optional option functions to customize the handler. behavior. By default, it uses the 'graphql-transport-ws' protocol.

func HandleWithOptions

func HandleWithOptions(done chan bool, errChan chan error, conn net.Conn, executorPool subscription.ExecutorPool, options HandleOptions)

HandleWithOptions will handle the websocket connection. It requires an option struct to define the behavior.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is an actual implementation of the subscription client interface.

func NewClient

func NewClient(logger abstractlogger.Logger, clientConn net.Conn) *Client

NewClient will create a new websocket subscription client.

func (*Client) Disconnect

func (c *Client) Disconnect() error

Disconnect will close the websocket connection.

func (*Client) DisconnectWithReason

func (c *Client) DisconnectWithReason(reason interface{}) error

DisconnectWithReason will close the websocket and provide the close code and reason. It can only consume CloseReason or CompiledCloseReason.

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected will indicate if the websocket connection is still established.

func (*Client) ReadBytesFromClient

func (c *Client) ReadBytesFromClient() ([]byte, error)

ReadBytesFromClient will read a subscription message from the websocket client.

func (*Client) WriteBytesToClient

func (c *Client) WriteBytesToClient(message []byte) error

WriteBytesToClient will write a subscription message to the websocket client.

type CloseReason

type CloseReason ws.Frame

CloseReason is type that is used to provide a close reason to Client.DisconnectWithReason.

func NewCloseReason

func NewCloseReason(code uint16, reason string) CloseReason

NewCloseReason is used to compose a close frame with code and reason message.

type CompiledCloseReason

type CompiledCloseReason []byte

CompiledCloseReason is a pre-compiled close reason to be provided to Client.DisconnectWithReason.

var (
	CompiledCloseReasonNormal CompiledCloseReason = ws.MustCompileFrame(
		ws.NewCloseFrame(ws.NewCloseFrameBody(
			ws.StatusNormalClosure, "Normal Closure",
		)),
	)
	CompiledCloseReasonInternalServerError CompiledCloseReason = ws.MustCompileFrame(
		ws.NewCloseFrame(ws.NewCloseFrameBody(
			ws.StatusInternalServerError, "Internal Server Error",
		)),
	)
)

type GraphQLTransportWSEventHandler

type GraphQLTransportWSEventHandler struct {
	Writer             GraphQLTransportWSMessageWriter
	OnConnectionOpened func()
	// contains filtered or unexported fields
}

GraphQLTransportWSEventHandler can be used to handle subscription events and forward them to a GraphQLTransportWSMessageWriter.

func (*GraphQLTransportWSEventHandler) Emit

func (g *GraphQLTransportWSEventHandler) Emit(eventType subscription.EventType, id string, data []byte, err error)

Emit is an implementation of subscription.EventHandler. It forwards some events to the HandleWriteEvent.

func (*GraphQLTransportWSEventHandler) HandleWriteEvent

func (g *GraphQLTransportWSEventHandler) HandleWriteEvent(messageType GraphQLTransportWSMessageType, id string, data []byte, providedErr error)

HandleWriteEvent forwards messages to the underlying writer.

type GraphQLTransportWSMessage

type GraphQLTransportWSMessage struct {
	Id      string                        `json:"id,omitempty"`
	Type    GraphQLTransportWSMessageType `json:"type"`
	Payload json.RawMessage               `json:"payload,omitempty"`
}

GraphQLTransportWSMessage is a struct that can be (de)serialized to graphql-transport-ws message format.

type GraphQLTransportWSMessageReader

type GraphQLTransportWSMessageReader struct {
	// contains filtered or unexported fields
}

GraphQLTransportWSMessageReader can be used to read graphql-transport-ws messages.

func (*GraphQLTransportWSMessageReader) DeserializeSubscribePayload

DeserializeSubscribePayload deserialized the subscribe payload from a graphql-transport-ws message.

func (*GraphQLTransportWSMessageReader) Read

Read deserializes a byte slice to the GraphQLTransportWSMessage struct.

type GraphQLTransportWSMessageSubscribePayload

type GraphQLTransportWSMessageSubscribePayload struct {
	OperationName string          `json:"operationName,omitempty"`
	Query         string          `json:"query"`
	Variables     json.RawMessage `json:"variables,omitempty"`
	Extensions    json.RawMessage `json:"extensions,omitempty"`
}

GraphQLTransportWSMessageSubscribePayload is a struct that can be (de)serialized to graphql-transport-ws message payload format.

type GraphQLTransportWSMessageType

type GraphQLTransportWSMessageType string

GraphQLTransportWSMessageType is a type that defines graphql-transport-ws message type names.

const (
	GraphQLTransportWSMessageTypeConnectionInit GraphQLTransportWSMessageType = "connection_init"
	GraphQLTransportWSMessageTypeConnectionAck  GraphQLTransportWSMessageType = "connection_ack"
	GraphQLTransportWSMessageTypePing           GraphQLTransportWSMessageType = "ping"
	GraphQLTransportWSMessageTypePong           GraphQLTransportWSMessageType = "pong"
	GraphQLTransportWSMessageTypeSubscribe      GraphQLTransportWSMessageType = "subscribe"
	GraphQLTransportWSMessageTypeNext           GraphQLTransportWSMessageType = "next"
	GraphQLTransportWSMessageTypeError          GraphQLTransportWSMessageType = "error"
	GraphQLTransportWSMessageTypeComplete       GraphQLTransportWSMessageType = "complete"
)

type GraphQLTransportWSMessageWriter

type GraphQLTransportWSMessageWriter struct {
	Client subscription.TransportClient
	// contains filtered or unexported fields
}

GraphQLTransportWSMessageWriter can be used to write graphql-transport-ws messages to a transport client.

func (*GraphQLTransportWSMessageWriter) WriteComplete

func (g *GraphQLTransportWSMessageWriter) WriteComplete(id string) error

WriteComplete writes a message of type 'complete' to the transport client.

func (*GraphQLTransportWSMessageWriter) WriteConnectionAck

func (g *GraphQLTransportWSMessageWriter) WriteConnectionAck() error

WriteConnectionAck writes a message of type 'connection_ack' to the transport client.

func (*GraphQLTransportWSMessageWriter) WriteError

func (g *GraphQLTransportWSMessageWriter) WriteError(id string, graphqlErrors graphql.RequestErrors) error

WriteError writes a message of type 'error' to the transport client including the graphql errors as payload.

func (*GraphQLTransportWSMessageWriter) WriteNext

func (g *GraphQLTransportWSMessageWriter) WriteNext(id string, executionResult []byte) error

WriteNext writes a message of type 'next' to the transport client including the execution result as payload.

func (*GraphQLTransportWSMessageWriter) WritePing

func (g *GraphQLTransportWSMessageWriter) WritePing(payload []byte) error

WritePing writes a message of type 'ping' to the transport client. Payload is optional.

func (*GraphQLTransportWSMessageWriter) WritePong

func (g *GraphQLTransportWSMessageWriter) WritePong(payload []byte) error

WritePong writes a message of type 'pong' to the transport client. Payload is optional.

type GraphQLWSMessage

type GraphQLWSMessage struct {
	Id      string               `json:"id,omitempty"`
	Type    GraphQLWSMessageType `json:"type"`
	Payload json.RawMessage      `json:"payload,omitempty"`
}

GraphQLWSMessage is a struct that can be (de)serialized to graphql-ws message format.

type GraphQLWSMessageReader

type GraphQLWSMessageReader struct {
	// contains filtered or unexported fields
}

GraphQLWSMessageReader can be used to read graphql-ws messages.

func (*GraphQLWSMessageReader) Read

func (g *GraphQLWSMessageReader) Read(data []byte) (*GraphQLWSMessage, error)

Read deserializes a byte slice to the GraphQLWSMessage struct.

type GraphQLWSMessageType

type GraphQLWSMessageType string

GraphQLWSMessageType is a type that defines graphql-ws message type names.

const (
	GraphQLWSMessageTypeConnectionInit      GraphQLWSMessageType = "connection_init"
	GraphQLWSMessageTypeConnectionAck       GraphQLWSMessageType = "connection_ack"
	GraphQLWSMessageTypeConnectionError     GraphQLWSMessageType = "connection_error"
	GraphQLWSMessageTypeConnectionTerminate GraphQLWSMessageType = "connection_terminate"
	GraphQLWSMessageTypeConnectionKeepAlive GraphQLWSMessageType = "ka"
	GraphQLWSMessageTypeStart               GraphQLWSMessageType = "start"
	GraphQLWSMessageTypeStop                GraphQLWSMessageType = "stop"
	GraphQLWSMessageTypeData                GraphQLWSMessageType = "data"
	GraphQLWSMessageTypeError               GraphQLWSMessageType = "error"
	GraphQLWSMessageTypeComplete            GraphQLWSMessageType = "complete"
)

type GraphQLWSMessageWriter

type GraphQLWSMessageWriter struct {
	Client subscription.TransportClient
	// contains filtered or unexported fields
}

GraphQLWSMessageWriter can be used to write graphql-ws messages to a transport client.

func (*GraphQLWSMessageWriter) WriteAck

func (g *GraphQLWSMessageWriter) WriteAck() error

WriteAck writes a message of type 'connection_ack' to the transport client.

func (*GraphQLWSMessageWriter) WriteComplete

func (g *GraphQLWSMessageWriter) WriteComplete(id string) error

WriteComplete writes a message of type 'complete' to the transport client.

func (*GraphQLWSMessageWriter) WriteConnectionError

func (g *GraphQLWSMessageWriter) WriteConnectionError(reason string) error

WriteConnectionError writes a message of type 'connection_error' to the transport client.

func (*GraphQLWSMessageWriter) WriteData

func (g *GraphQLWSMessageWriter) WriteData(id string, responseData []byte) error

WriteData writes a message of type 'data' to the transport client.

func (*GraphQLWSMessageWriter) WriteError

func (g *GraphQLWSMessageWriter) WriteError(id string, errors graphql.RequestErrors) error

WriteError writes a message of type 'error' to the transport client.

func (*GraphQLWSMessageWriter) WriteKeepAlive

func (g *GraphQLWSMessageWriter) WriteKeepAlive() error

WriteKeepAlive writes a message of type 'ka' to the transport client.

func (*GraphQLWSMessageWriter) WriteTerminate

func (g *GraphQLWSMessageWriter) WriteTerminate(reason string) error

WriteTerminate writes a message of type 'connection_terminate' to the transport client.

type GraphQLWSWriteEventHandler

type GraphQLWSWriteEventHandler struct {
	Writer GraphQLWSMessageWriter
	// contains filtered or unexported fields
}

GraphQLWSWriteEventHandler can be used to handle subscription events and forward them to a GraphQLWSMessageWriter.

func (*GraphQLWSWriteEventHandler) Emit

func (g *GraphQLWSWriteEventHandler) Emit(eventType subscription.EventType, id string, data []byte, err error)

Emit is an implementation of subscription.EventHandler. It forwards events to the HandleWriteEvent.

func (*GraphQLWSWriteEventHandler) HandleWriteEvent

func (g *GraphQLWSWriteEventHandler) HandleWriteEvent(messageType GraphQLWSMessageType, id string, data []byte, providedErr error)

HandleWriteEvent forwards messages to the underlying writer.

type HandleOptionFunc

type HandleOptionFunc func(opts *HandleOptions)

HandleOptionFunc can be used to define option functions.

func WithCustomClient

func WithCustomClient(client subscription.TransportClient) HandleOptionFunc

WithCustomClient is a function that set a custom transport client for the websocket handler.

func WithCustomConnectionInitTimeOut

func WithCustomConnectionInitTimeOut(connectionInitTimeOut time.Duration) HandleOptionFunc

WithCustomConnectionInitTimeOut is a function that sets a custom connection init time out.

func WithCustomKeepAliveInterval

func WithCustomKeepAliveInterval(keepAliveInterval time.Duration) HandleOptionFunc

WithCustomKeepAliveInterval is a function that sets a custom keep-alive interval for the websocket handler.

func WithCustomReadErrorTimeOut

func WithCustomReadErrorTimeOut(readErrorTimeOut time.Duration) HandleOptionFunc

WithCustomReadErrorTimeOut is a function that sets a custom read error time out for the websocket handler.

func WithCustomSubscriptionEngine

func WithCustomSubscriptionEngine(subscriptionEngine subscription.Engine) HandleOptionFunc

WithCustomSubscriptionEngine is a function that sets a custom subscription engine for the websocket handler.

func WithCustomSubscriptionUpdateInterval

func WithCustomSubscriptionUpdateInterval(subscriptionUpdateInterval time.Duration) HandleOptionFunc

WithCustomSubscriptionUpdateInterval is a function that sets a custom subscription update interval for the websocket handler.

func WithInitFunc

func WithInitFunc(initFunc InitFunc) HandleOptionFunc

WithInitFunc is a function that sets the init function for the websocket handler.

func WithLogger

func WithLogger(logger abstractlogger.Logger) HandleOptionFunc

WithLogger is a function that sets a logger for the websocket handler.

func WithProtocol

func WithProtocol(protocol Protocol) HandleOptionFunc

WithProtocol is a function that sets the protocol.

func WithProtocolFromRequestHeaders

func WithProtocolFromRequestHeaders(req *http.Request) HandleOptionFunc

WithProtocolFromRequestHeaders is a function that sets the protocol based on the request headers. It fallbacks to the DefaultProtocol if the header can't be found, the value is invalid or no request was provided.

type HandleOptions

type HandleOptions struct {
	Logger                           abstractlogger.Logger
	Protocol                         Protocol
	WebSocketInitFunc                InitFunc
	CustomClient                     subscription.TransportClient
	CustomKeepAliveInterval          time.Duration
	CustomSubscriptionUpdateInterval time.Duration
	CustomConnectionInitTimeOut      time.Duration
	CustomReadErrorTimeOut           time.Duration
	CustomSubscriptionEngine         subscription.Engine
}

HandleOptions can be used to pass options to the websocket handler.

type InitFunc

type InitFunc func(ctx context.Context, initPayload InitPayload) (context.Context, error)

InitFunc is called when the server receives connection init message from the client. This can be used to check initial payload to see whether to accept the websocket connection.

type InitPayload

type InitPayload json.RawMessage

InitPayload is a structure that is parsed from the websocket init message payload.

func (InitPayload) Authorization

func (p InitPayload) Authorization() string

Authorization is a shorthand for getting the Authorization header from the payload.

func (InitPayload) GetString

func (p InitPayload) GetString(key string) string

GetString safely gets a string value from the payload. It returns an empty string if the payload is nil or the value isn't set.

type Protocol

type Protocol string

Protocol defines the protocol names as type.

const (
	ProtocolUndefined          Protocol = ""
	ProtocolGraphQLWS          Protocol = "graphql-ws"
	ProtocolGraphQLTransportWS Protocol = "graphql-transport-ws"
)

type ProtocolGraphQLTransportWSHandler

type ProtocolGraphQLTransportWSHandler struct {
	// contains filtered or unexported fields
}

ProtocolGraphQLTransportWSHandler is able to handle the graphql-transport-ws protocol.

func NewProtocolGraphQLTransportWSHandler

func NewProtocolGraphQLTransportWSHandler(client subscription.TransportClient) (*ProtocolGraphQLTransportWSHandler, error)

NewProtocolGraphQLTransportWSHandler creates a new ProtocolGraphQLTransportWSHandler with default options.

func NewProtocolGraphQLTransportWSHandlerWithOptions

func NewProtocolGraphQLTransportWSHandlerWithOptions(client subscription.TransportClient, opts ProtocolGraphQLTransportWSHandlerOptions) (*ProtocolGraphQLTransportWSHandler, error)

NewProtocolGraphQLTransportWSHandlerWithOptions creates a new ProtocolGraphQLTransportWSHandler. It requires an option struct.

func (*ProtocolGraphQLTransportWSHandler) EventHandler

EventHandler returns the underlying graphql-transport-ws event handler. It's an implementation of subscription.Protocol.

func (*ProtocolGraphQLTransportWSHandler) Handle

Handle will handle the actual graphql-transport-ws protocol messages. It's an implementation of subscription.Protocol.

type ProtocolGraphQLTransportWSHandlerOptions

type ProtocolGraphQLTransportWSHandlerOptions struct {
	Logger                    abstractlogger.Logger
	WebSocketInitFunc         InitFunc
	CustomKeepAliveInterval   time.Duration
	CustomInitTimeOutDuration time.Duration
}

ProtocolGraphQLTransportWSHandlerOptions can be used to provide options to the graphql-transport-ws protocol handler.

type ProtocolGraphQLWSHandler

type ProtocolGraphQLWSHandler struct {
	// contains filtered or unexported fields
}

ProtocolGraphQLWSHandler is able to handle the graphql-ws protocol.

func NewProtocolGraphQLWSHandler

func NewProtocolGraphQLWSHandler(client subscription.TransportClient) (*ProtocolGraphQLWSHandler, error)

NewProtocolGraphQLWSHandler creates a new ProtocolGraphQLWSHandler with default options.

func NewProtocolGraphQLWSHandlerWithOptions

func NewProtocolGraphQLWSHandlerWithOptions(client subscription.TransportClient, opts ProtocolGraphQLWSHandlerOptions) (*ProtocolGraphQLWSHandler, error)

NewProtocolGraphQLWSHandlerWithOptions creates a new ProtocolGraphQLWSHandler. It requires an option struct.

func (*ProtocolGraphQLWSHandler) EventHandler

EventHandler returns the underlying graphql-ws event handler. It's an implementation of subscription.Protocol.

func (*ProtocolGraphQLWSHandler) Handle

func (p *ProtocolGraphQLWSHandler) Handle(ctx context.Context, engine subscription.Engine, data []byte) error

Handle will handle the actual graphql-ws protocol messages. It's an implementation of subscription.Protocol.

type ProtocolGraphQLWSHandlerOptions

type ProtocolGraphQLWSHandlerOptions struct {
	Logger                  abstractlogger.Logger
	WebSocketInitFunc       InitFunc
	CustomKeepAliveInterval time.Duration
}

ProtocolGraphQLWSHandlerOptions can be used to provide options to the graphql-ws protocol handler.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL