gateway

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2023 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrWSAlreadyOpen = errors.New("web socket already opened")

ErrWSAlreadyOpen is thrown when you attempt to open a websocket that already is open.

Functions

func CreateEvent

func CreateEvent[T events.EventInterface](
	w *GatewayClient,
	data []byte,
	fn Event[T],
) (*T, error)

Emits an event to a function

+unstable

Types

type Event

type Event[T events.EventInterface] func(w *GatewayClient, ctx *EventContext, evt *T)

type EventContext

type EventContext struct {
	// Raw event data
	Raw []byte
}

type EventHandlers

type EventHandlers struct {
	// An error occurred which meant you couldn't authenticate.
	//
	// <Note that grevolt handles these for you in general, but you can provide additional logic here>
	Error Event[events.Error]

	// The server has authenticated your connection and you will shortly start receiving data.
	Authenticated Event[events.Authenticated]

	// Several events have been sent, process each item of v as its own event.
	//
	// <Note that grevolt handles these for you in general, but you can provide additional logic here>
	Bulk Event[events.Bulk]

	// Ping response from the server.
	//
	// <Note that grevolt handles these for you in general, but you can provide additional logic here>
	Pong Event[events.Pong]

	// Data for use by client, data structures match the API specification
	Ready Event[events.Ready]

	// Message received, the event object has the same schema as the Message object in the API with the addition of an event type.
	Message Event[events.Message]

	// Message edited or otherwise updated.
	MessageUpdate Event[events.MessageUpdate]

	// Message has data being appended to it.
	MessageAppend Event[events.MessageAppend]

	// Message has been deleted.
	MessageDelete Event[events.MessageDelete]

	// A reaction has been added to a message.
	MessageReact Event[events.MessageReact]

	// A reaction has been removed from a message.
	MessageUnreact Event[events.MessageUnreact]

	// A certain reaction has been removed from the message.
	//
	// <the difference between this and MessageUnreact is that
	// this event is sent when a user with manage messages removes
	// a reaction while MessageUnreact is sent when a user removes
	// their own reaction>
	MessageRemoveReaction Event[events.MessageRemoveReaction]

	// Channel created, the event object has the same schema as the Channel object in the API with the addition of an event type.
	ChannelCreate Event[events.ChannelCreate]

	// Channel details updated.
	ChannelUpdate Event[events.ChannelUpdate]

	// Channel has been deleted.
	ChannelDelete Event[events.ChannelDelete]

	// A user has joined the group.
	ChannelGroupJoin Event[events.ChannelGroupJoin]

	// A user has left the group.
	ChannelGroupLeave Event[events.ChannelGroupLeave]

	// A user has started typing in this channel.
	ChannelStartTyping Event[events.ChannelStartTyping]

	// A user has stopped typing in this channel.
	ChannelStopTyping Event[events.ChannelStopTyping]

	// You have acknowledged new messages in this channel up to this message ID.
	//
	// <official docs say the above, but it should be 'A user' instead of 'you'?>
	ChannelAck Event[events.ChannelAck]

	// Server created, the event object has the same schema as the SERVER object in the API with the addition of an event type.
	ServerCreate Event[events.ServerCreate]

	// Server details updated.
	ServerUpdate Event[events.ServerUpdate]

	// Server has been deleted.
	ServerDelete Event[events.ServerDelete]

	// Server member details updated.
	ServerMemberUpdate Event[events.ServerMemberUpdate]

	// A user has joined the group.
	//
	// <this should be server, not group>
	ServerMemberJoin Event[events.ServerMemberJoin]

	// A user has left the group.
	//
	// <this should be server, not group>
	ServerMemberLeave Event[events.ServerMemberLeave]

	// Server role has been updated or created.
	ServerRoleUpdate Event[events.ServerRoleUpdate]

	// Server role has been deleted.
	ServerRoleDelete Event[events.ServerRoleDelete]

	// User has been updated.
	UserUpdate Event[events.UserUpdate]

	// Your relationship with another user has changed.
	UserRelationship Event[events.UserRelationship]

	// Settings updated remotely
	//
	// <undocumented, will likely be available in a future release>
	UserSettingsUpdate Event[events.UserSettingsUpdate]

	// User has been platform banned or deleted their account
	//
	// Clients should remove the following associated data:
	//   - Messages
	//   - DM Channels
	//   - Relationships
	//   - Server Memberships
	//
	// User flags are specified to explain why a wipe is occurring though not all reasons will necessarily ever appear.
	UserPlatformWipe Event[events.UserPlatformWipe]

	// Emoji created, the event object has the same schema as the Emoji object in the API with the addition of an event type.
	EmojiCreate Event[events.EmojiCreate]

	// Emoji has been deleted.
	EmojiDelete Event[events.EmojiDelete]

	// New webhook
	//
	// <undocumented, will likely be available in a future release>
	WebhookCreate Event[events.WebhookCreate]

	// Update existing webhook
	//
	// <undocumented, will likely be available in a future release>
	WebhookUpdate Event[events.WebhookUpdate]

	// Delete existing webhook
	//
	// <undocumented, will likely be available in a future release>
	WebhookDelete Event[events.WebhookDelete]

	// New report
	//
	// <undocumented, will likely be available in a future release>
	ReportCreate Event[events.ReportCreate]

	// Forwarded events from rAuth, currently only session deletion events are forwarded.
	//
	// <this event is special, you likely want AuthDeleteSession and AuthDeleteAllSessions instead>
	Auth Event[events.Auth]

	// A session has been deleted.
	//
	// Eq: Auth->DeleteSession
	Auth_DeleteSession Event[events.Auth_DeleteSession]

	// All sessions for this account have been deleted, optionally excluding a given ID.
	//
	// Eq: Auth->DeleteAllSessions
	Auth_DeleteAllSessions Event[events.Auth_DeleteAllSessions]
}

Event handler for the websocket

See https://github.com/revoltchat/backend/tree/master/crates/quark/src/events for event list

type GatewayCacher

type GatewayCacher struct {
	// Whether to disable websocket-based caching
	Disable bool

	// Disable automatic rest fetching (to handle partial/unfilled cache objects
	// where it is sane to do so)
	DisableAutoRestFetching bool
}

type GatewayClient

type GatewayClient struct {
	sync.Mutex

	// Rest client (required for cache as well as initial setup)
	RestClient *restcli.RestClient

	// Preparation state
	Prepared bool

	// The URL of the WS
	WSUrl string

	// API version
	APIVersion string

	// Timeout for requests
	Timeout time.Duration

	// WS Deadline
	Deadline time.Duration

	// Heartbeat data
	Heartbeat *Heartbeat

	// Logger to use, will be autofilled if not provided
	Logger *zap.Logger

	// Session token for requests
	SessionToken *auth.Token

	// Websocker payload format, either json or msgpack (only these are supported by the client)
	Encoding string

	// The websocket connection
	//
	// +unstable
	WsConn *websocket.Conn

	// Notifications from the WS
	//
	// This is very low level and should not be used unless you know what you are doing
	//
	// +unstable
	NotifyChannel broadcast.BroadcastServer[*NotifyPayload]

	// This channel is fired when status updates are received
	//
	// This is very low level and should not be used unless you know what you are doing
	//
	// +unstable
	StatusChannel broadcast.BroadcastServer[*StatusPayload]

	// Websocket state
	//
	// +unstable
	State WsState

	// Grevolt shared state
	//
	// This is a pointer to the shared state and so can be modified
	//
	// State stores automatically handle concurrency, so you do not need to
	// worry about that.
	SharedState *state.State

	// Event handlers, set these to handle events
	EventHandlers EventHandlers

	// Raw event handlers, set these to handle raw events (as bytes)
	//
	// Useful if you wish to add support for newer events not yet supported
	// by the library
	RawSinkFunc []func(w *GatewayClient, data []byte, typ string)

	// Whether to disable websocket-based caching
	GatewayCache GatewayCacher
}

func (*GatewayClient) BeginTyping

func (w *GatewayClient) BeginTyping(channelID string) error

func (*GatewayClient) Close

func (w *GatewayClient) Close()

func (*GatewayClient) Decode

func (w *GatewayClient) Decode(data []byte, dst any) error

func (*GatewayClient) Encode

func (w *GatewayClient) Encode(data any) ([]byte, error)

func (*GatewayClient) EndTyping

func (w *GatewayClient) EndTyping(channelID string) error

func (*GatewayClient) GatewayURL

func (w *GatewayClient) GatewayURL() string

func (*GatewayClient) HandleAuth

func (w *GatewayClient) HandleAuth(event []byte) error

func (*GatewayClient) HandleBulk

func (w *GatewayClient) HandleBulk(event []byte) error

func (*GatewayClient) HandleEvent

func (w *GatewayClient) HandleEvent(event []byte, typ string)

func (*GatewayClient) Open

func (w *GatewayClient) Open() error

Opens a websocket connection to the gateway

func (*GatewayClient) Prepare

func (w *GatewayClient) Prepare() error

Prepares a websocket client. Use the Open() method on the websocket to open the websocket, this method is more internal

You probably don't want to use this, as it is done for you when calling Open()

func (*GatewayClient) Send

func (w *GatewayClient) Send(data map[string]any) error

func (*GatewayClient) Wait

func (w *GatewayClient) Wait()

Wait for the gateway to close

type Heartbeat

type Heartbeat struct {
	// Last time a ping was sent
	LastHeartbeatSent time.Time

	// Last time a ping was received
	LastHeartbeatAck time.Time

	// Interval
	HeartbeatInterval time.Duration
}

func (*Heartbeat) Latency

func (h *Heartbeat) Latency() time.Duration

Returns the websocket latency

type IOpCode

type IOpCode int

Internal IOpCodes allow for control handling of the WS

This is the primitive for how reading and writing is synchronized

const (
	// Kill the websocket
	KILL_IOpCode IOpCode = iota

	// Restart the websocket
	RESTART_IOpCode IOpCode = iota

	// Authenticate the websocket
	AUTHENTICATE_IOpCode IOpCode = iota

	// An error has occured, this also triggers a restart after
	// logging the error
	ERROR_IOpCode IOpCode = iota

	// A fatal error has occured, this kills the websocket
	// after logging the error
	FATAL_IOpCode IOpCode = iota

	// Send an event to HandleEvent to be handled
	EVENT_IOpCode IOpCode = iota
)

type NotifyEvent

type NotifyEvent struct {
	Data []byte // Event data
	Type string // Event type
}

NotifyEvents are low level events that are fired when the WS receives a eent to be fired. This is highly unstable, you likely want to use the EventHandlers instead.

+unstable

type NotifyPayload

type NotifyPayload struct {
	OpCode IOpCode     // Internal library OpCode
	Error  string      // Whether or not we are sending an error, only applicable to ERROR/FATAL_IOpCode
	Event  NotifyEvent // Event data, only applicable to EVENT_IOpCode
}

NotifyPayload is a payload that is sent to the NotifyChannel

This is used to control the WS, and to send events to the EventHandlers. It is also highly unstable, you likely want to use the EventHandlers instead.

+unstable

type StatusMessage

type StatusMessage int

StatusMessage is a message that is sent to the StatusChannel to allow listening to status updates to the websocket

const (
	// DONE is sent when the websocket is done and all listeners
	// should stop listening and end.
	DONE_StatusMessage StatusMessage = iota

	// WSEND is sent when the websocket has closed (restarts etc can cause this)
	//
	// Heartbeaters should listen for this and stop sending heartbeats when
	// this is received.
	WSEND_StatusMessage StatusMessage = iota
)

type StatusPayload

type StatusPayload struct {
	StatusMessage StatusMessage
}

Status payload, can be used functions such as Wait() etc

+unstable

type WsState

type WsState int

Websocket state, you can use this to monitor the state of the websocket

+unstable

const (
	// The websocket is closed
	WsStateClosed WsState = iota

	// The websocket is opening
	WsStateOpening WsState = iota

	// The websocket is open and receiving events
	WsStateOpen WsState = iota

	// The websocket is closing
	WsStateClosing WsState = iota

	// The websocket is restarting
	WsStateRestarting WsState = iota
)

Directories

Path Synopsis
https://betterprogramming.pub/how-to-broadcast-messages-in-go-using-channels-b68f42bdf32e
https://betterprogramming.pub/how-to-broadcast-messages-in-go-using-channels-b68f42bdf32e

Jump to

Keyboard shortcuts

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