2020-01-15 04:56:50 +00:00
|
|
|
// Package gateway handles the Discord gateway (or Websocket) connection, its
|
|
|
|
// events, and everything related to it. This includes logging into the
|
|
|
|
// Websocket.
|
|
|
|
//
|
|
|
|
// This package does not abstract events and function handlers; instead, it
|
|
|
|
// leaves that to the session package. This package exposes only a single Events
|
|
|
|
// channel.
|
2020-01-15 04:43:34 +00:00
|
|
|
package gateway
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-01-19 06:14:46 +00:00
|
|
|
"log"
|
2020-01-15 04:43:34 +00:00
|
|
|
"net/url"
|
2020-02-08 06:17:27 +00:00
|
|
|
"sync"
|
2020-01-15 04:43:34 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/diamondburned/arikawa/api"
|
2020-04-09 02:28:40 +00:00
|
|
|
"github.com/diamondburned/arikawa/utils/httputil"
|
|
|
|
"github.com/diamondburned/arikawa/utils/json"
|
|
|
|
"github.com/diamondburned/arikawa/utils/wsutil"
|
2020-01-15 04:43:34 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
EndpointGateway = api.Endpoint + "gateway"
|
|
|
|
EndpointGatewayBot = api.EndpointGateway + "/bot"
|
|
|
|
|
|
|
|
Version = "6"
|
|
|
|
Encoding = "json"
|
2020-03-16 05:55:45 +00:00
|
|
|
// Compress = "zlib-stream"
|
2020-01-15 04:43:34 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
// WSTimeout is the timeout for connecting and writing to the Websocket,
|
|
|
|
// before Gateway cancels and fails.
|
|
|
|
WSTimeout = wsutil.DefaultTimeout
|
|
|
|
// WSBuffer is the size of the Event channel. This has to be at least 1 to
|
|
|
|
// make space for the first Event: Ready or Resumed.
|
|
|
|
WSBuffer = 10
|
2020-01-15 07:34:18 +00:00
|
|
|
// WSError is the default error handler
|
2020-01-29 03:54:22 +00:00
|
|
|
WSError = func(err error) { log.Println("Gateway error:", err) }
|
2020-01-17 22:29:13 +00:00
|
|
|
// WSExtraReadTimeout is the duration to be added to Hello, as a read
|
|
|
|
// timeout for the websocket.
|
|
|
|
WSExtraReadTimeout = time.Second
|
2020-03-22 22:23:29 +00:00
|
|
|
// WSDebug is used for extra debug logging. This is expected to behave
|
|
|
|
// similarly to log.Println().
|
2020-02-08 06:17:27 +00:00
|
|
|
WSDebug = func(v ...interface{}) {}
|
2020-01-15 04:43:34 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrMissingForResume = errors.New(
|
|
|
|
"missing session ID or sequence for resuming")
|
|
|
|
ErrWSMaxTries = errors.New("max tries reached")
|
|
|
|
)
|
|
|
|
|
|
|
|
func GatewayURL() (string, error) {
|
|
|
|
var Gateway struct {
|
|
|
|
URL string `json:"url"`
|
|
|
|
}
|
|
|
|
|
|
|
|
return Gateway.URL, httputil.DefaultClient.RequestJSON(
|
|
|
|
&Gateway, "GET", EndpointGateway)
|
|
|
|
}
|
|
|
|
|
|
|
|
type Gateway struct {
|
|
|
|
WS *wsutil.Websocket
|
|
|
|
json.Driver
|
|
|
|
|
|
|
|
// Timeout for connecting and writing to the Websocket, uses default
|
|
|
|
// WSTimeout (global).
|
|
|
|
WSTimeout time.Duration
|
|
|
|
|
2020-01-15 04:56:50 +00:00
|
|
|
// All events sent over are pointers to Event structs (structs suffixed with
|
2020-01-19 21:54:16 +00:00
|
|
|
// "Event"). This shouldn't be accessed if the Gateway is created with a
|
|
|
|
// Session.
|
2020-01-15 04:56:50 +00:00
|
|
|
Events chan Event
|
2020-01-15 04:43:34 +00:00
|
|
|
|
2020-01-15 04:56:50 +00:00
|
|
|
SessionID string
|
2020-01-15 04:43:34 +00:00
|
|
|
|
2020-01-15 07:34:18 +00:00
|
|
|
Identifier *Identifier
|
|
|
|
Pacemaker *Pacemaker
|
|
|
|
Sequence *Sequence
|
2020-01-15 04:43:34 +00:00
|
|
|
|
|
|
|
ErrorLog func(err error) // default to log.Println
|
2020-03-01 02:13:58 +00:00
|
|
|
|
2020-04-07 02:36:06 +00:00
|
|
|
// AfterClose is called after each close. Error can be non-nil, as this is
|
|
|
|
// called even when the Gateway is gracefully closed. It's used mainly for
|
|
|
|
// reconnections or any type of connection interruptions.
|
|
|
|
AfterClose func(err error) // noop by default
|
|
|
|
|
2020-01-15 04:43:34 +00:00
|
|
|
// Only use for debugging
|
|
|
|
|
|
|
|
// If this channel is non-nil, all incoming OP packets will also be sent
|
2020-01-15 04:56:50 +00:00
|
|
|
// here. This should be buffered, so to not block the main loop.
|
2020-02-26 06:37:26 +00:00
|
|
|
OP chan *OP
|
2020-01-15 04:43:34 +00:00
|
|
|
|
2020-03-01 02:13:58 +00:00
|
|
|
// Mutex to hold off calls when the WS is not available. Doesn't block if
|
|
|
|
// Start() is not called or Close() is called. Also doesn't block for
|
|
|
|
// Identify or Resume.
|
2020-04-06 19:03:42 +00:00
|
|
|
// available sync.RWMutex
|
2020-03-01 02:13:58 +00:00
|
|
|
|
2020-01-15 04:43:34 +00:00
|
|
|
// Filled by methods, internal use
|
2020-01-20 11:06:20 +00:00
|
|
|
paceDeath chan error
|
2020-02-08 06:17:27 +00:00
|
|
|
waitGroup *sync.WaitGroup
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewGateway starts a new Gateway with the default stdlib JSON driver. For more
|
|
|
|
// information, refer to NewGatewayWithDriver.
|
|
|
|
func NewGateway(token string) (*Gateway, error) {
|
|
|
|
return NewGatewayWithDriver(token, json.Default{})
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewGatewayWithDriver connects to the Gateway and authenticates automatically.
|
|
|
|
func NewGatewayWithDriver(token string, driver json.Driver) (*Gateway, error) {
|
|
|
|
URL, err := GatewayURL()
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "Failed to get gateway endpoint")
|
|
|
|
}
|
|
|
|
|
|
|
|
g := &Gateway{
|
2020-01-15 07:34:18 +00:00
|
|
|
Driver: driver,
|
|
|
|
WSTimeout: WSTimeout,
|
|
|
|
Events: make(chan Event, WSBuffer),
|
|
|
|
Identifier: DefaultIdentifier(token),
|
|
|
|
Sequence: NewSequence(),
|
|
|
|
ErrorLog: WSError,
|
2020-04-07 02:36:06 +00:00
|
|
|
AfterClose: func(error) {},
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Parameters for the gateway
|
2020-04-06 19:03:42 +00:00
|
|
|
param := url.Values{
|
|
|
|
"v": {Version},
|
|
|
|
"encoding": {Encoding},
|
|
|
|
}
|
|
|
|
|
2020-01-15 04:43:34 +00:00
|
|
|
// Append the form to the URL
|
|
|
|
URL += "?" + param.Encode()
|
|
|
|
|
|
|
|
// Create a new undialed Websocket.
|
2020-04-06 19:03:42 +00:00
|
|
|
g.WS = wsutil.NewCustom(wsutil.NewConn(driver), URL)
|
2020-01-15 04:43:34 +00:00
|
|
|
|
|
|
|
// Try and dial it
|
2020-01-17 22:29:13 +00:00
|
|
|
return g, nil
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Close closes the underlying Websocket connection.
|
|
|
|
func (g *Gateway) Close() error {
|
2020-04-06 19:03:42 +00:00
|
|
|
// Check if the WS is already closed:
|
|
|
|
if g.waitGroup == nil && g.paceDeath == nil {
|
|
|
|
WSDebug("Gateway is already closed.")
|
2020-04-07 02:36:06 +00:00
|
|
|
|
|
|
|
g.AfterClose(nil)
|
2020-04-06 19:03:42 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-01-20 11:06:20 +00:00
|
|
|
// If the pacemaker is running:
|
2020-03-07 19:50:30 +00:00
|
|
|
if g.paceDeath != nil {
|
|
|
|
WSDebug("Stopping pacemaker...")
|
|
|
|
|
|
|
|
// Stop the pacemaker and the event handler
|
|
|
|
g.Pacemaker.Stop()
|
2020-01-16 03:28:21 +00:00
|
|
|
|
2020-03-07 19:50:30 +00:00
|
|
|
WSDebug("Stopped pacemaker.")
|
|
|
|
}
|
|
|
|
|
|
|
|
WSDebug("Waiting for WaitGroup to be done.")
|
2020-02-08 06:17:27 +00:00
|
|
|
|
|
|
|
// This should work, since Pacemaker should signal its loop to stop, which
|
|
|
|
// would also exit our event loop. Both would be 2.
|
|
|
|
g.waitGroup.Wait()
|
|
|
|
|
|
|
|
// Mark g.waitGroup as empty:
|
|
|
|
g.waitGroup = nil
|
2020-01-16 03:28:21 +00:00
|
|
|
|
2020-04-12 18:06:43 +00:00
|
|
|
WSDebug("WaitGroup is done. Closing the websocket.")
|
2020-04-09 20:49:12 +00:00
|
|
|
|
2020-04-12 18:06:43 +00:00
|
|
|
err := g.WS.Close()
|
|
|
|
g.AfterClose(err)
|
2020-04-07 02:36:06 +00:00
|
|
|
return err
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
|
2020-04-12 18:06:43 +00:00
|
|
|
// Reconnect tries to reconnect forever. It will resume the connection if
|
|
|
|
// possible. If an Invalid Session is received, it will start a fresh one.
|
|
|
|
func (g *Gateway) Reconnect() {
|
2020-02-08 06:17:27 +00:00
|
|
|
WSDebug("Reconnecting...")
|
|
|
|
|
2020-04-12 18:06:43 +00:00
|
|
|
// Guarantee the gateway is already closed. Ignore its error, as we're
|
|
|
|
// redialing anyway.
|
|
|
|
g.Close()
|
2020-01-29 03:54:22 +00:00
|
|
|
|
2020-04-12 18:06:43 +00:00
|
|
|
for i := 1; ; i++ {
|
2020-02-20 03:36:00 +00:00
|
|
|
WSDebug("Trying to dial, attempt", i)
|
2020-01-17 22:29:13 +00:00
|
|
|
|
2020-02-20 03:36:00 +00:00
|
|
|
// Condition: err == ErrInvalidSession:
|
|
|
|
// If the connection is rate limited (documented behavior):
|
|
|
|
// https://discordapp.com/developers/docs/topics/gateway#rate-limiting
|
2020-01-19 06:34:52 +00:00
|
|
|
|
2020-02-20 03:36:00 +00:00
|
|
|
if err := g.Open(); err != nil && err != ErrInvalidSession {
|
|
|
|
g.ErrorLog(errors.Wrap(err, "Failed to open gateway"))
|
|
|
|
continue
|
2020-01-17 22:29:13 +00:00
|
|
|
}
|
|
|
|
|
2020-02-20 03:36:00 +00:00
|
|
|
WSDebug("Started after attempt:", i)
|
2020-04-12 18:06:43 +00:00
|
|
|
return
|
2020-02-20 03:36:00 +00:00
|
|
|
}
|
|
|
|
}
|
2020-01-17 22:29:13 +00:00
|
|
|
|
2020-04-06 19:03:42 +00:00
|
|
|
// Open connects to the Websocket and authenticate it. You should usually use
|
|
|
|
// this function over Start().
|
2020-02-20 03:36:00 +00:00
|
|
|
func (g *Gateway) Open() error {
|
2020-04-06 19:03:42 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), WSTimeout)
|
|
|
|
defer cancel()
|
2020-02-08 06:17:27 +00:00
|
|
|
|
2020-02-20 03:36:00 +00:00
|
|
|
// Reconnect to the Gateway
|
|
|
|
if err := g.WS.Dial(ctx); err != nil {
|
|
|
|
return errors.Wrap(err, "Failed to reconnect")
|
|
|
|
}
|
2020-01-17 22:29:13 +00:00
|
|
|
|
2020-02-20 03:36:00 +00:00
|
|
|
WSDebug("Trying to start...")
|
2020-01-17 22:29:13 +00:00
|
|
|
|
2020-02-20 03:36:00 +00:00
|
|
|
// Try to resume the connection
|
|
|
|
if err := g.Start(); err != nil {
|
|
|
|
return err
|
2020-01-17 22:29:13 +00:00
|
|
|
}
|
2020-02-20 03:36:00 +00:00
|
|
|
|
|
|
|
// Started successfully, return
|
|
|
|
return nil
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Start authenticates with the websocket, or resume from a dead Websocket
|
2020-04-06 19:03:42 +00:00
|
|
|
// connection. This function doesn't block. You wouldn't usually use this
|
|
|
|
// function, but Open() instead.
|
2020-01-15 04:43:34 +00:00
|
|
|
func (g *Gateway) Start() error {
|
2020-04-06 19:03:42 +00:00
|
|
|
// g.available.Lock()
|
|
|
|
// defer g.available.Unlock()
|
2020-03-01 02:13:58 +00:00
|
|
|
|
2020-01-20 11:06:20 +00:00
|
|
|
if err := g.start(); err != nil {
|
2020-02-08 06:17:27 +00:00
|
|
|
WSDebug("Start failed:", err)
|
2020-04-06 19:03:42 +00:00
|
|
|
|
|
|
|
// Close can be called with the mutex still acquired here, as the
|
|
|
|
// pacemaker hasn't started yet.
|
2020-02-08 06:17:27 +00:00
|
|
|
if err := g.Close(); err != nil {
|
|
|
|
WSDebug("Failed to close after start fail:", err)
|
|
|
|
}
|
2020-01-20 11:06:20 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-04-12 18:06:43 +00:00
|
|
|
// Wait is deprecated. The gateway will reconnect forever. This function will
|
|
|
|
// panic.
|
2020-03-01 02:13:58 +00:00
|
|
|
func (g *Gateway) Wait() error {
|
2020-04-12 18:06:43 +00:00
|
|
|
panic("Wait is deprecated. defer (*Gateway).Close() is required.")
|
2020-03-01 02:13:58 +00:00
|
|
|
}
|
|
|
|
|
2020-01-20 11:06:20 +00:00
|
|
|
func (g *Gateway) start() error {
|
2020-01-15 04:43:34 +00:00
|
|
|
// This is where we'll get our events
|
|
|
|
ch := g.WS.Listen()
|
|
|
|
|
2020-03-16 05:55:45 +00:00
|
|
|
// Make a new WaitGroup for use in background loops:
|
|
|
|
g.waitGroup = new(sync.WaitGroup)
|
|
|
|
|
2020-01-15 04:43:34 +00:00
|
|
|
// Wait for an OP 10 Hello
|
|
|
|
var hello HelloEvent
|
2020-01-15 07:34:18 +00:00
|
|
|
if _, err := AssertEvent(g, <-ch, HelloOP, &hello); err != nil {
|
2020-01-15 04:43:34 +00:00
|
|
|
return errors.Wrap(err, "Error at Hello")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send Discord either the Identify packet (if it's a fresh connection), or
|
|
|
|
// a Resume packet (if it's a dead connection).
|
|
|
|
if g.SessionID == "" {
|
|
|
|
// SessionID is empty, so this is a completely new session.
|
|
|
|
if err := g.Identify(); err != nil {
|
|
|
|
return errors.Wrap(err, "Failed to identify")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if err := g.Resume(); err != nil {
|
|
|
|
return errors.Wrap(err, "Failed to resume")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-06 20:26:00 +00:00
|
|
|
// Expect either READY or RESUMED before continuing.
|
|
|
|
WSDebug("Waiting for either READY or RESUMED.")
|
|
|
|
|
|
|
|
err := WaitForEvent(g, ch, func(op *OP) bool {
|
|
|
|
switch op.EventName {
|
|
|
|
case "READY":
|
|
|
|
WSDebug("Found READY event.")
|
|
|
|
return true
|
|
|
|
case "RESUMED":
|
|
|
|
WSDebug("Found RESUMED event.")
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
})
|
2020-01-19 21:54:16 +00:00
|
|
|
|
2020-04-06 20:26:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "First error")
|
2020-01-19 21:54:16 +00:00
|
|
|
}
|
|
|
|
|
2020-03-07 19:50:30 +00:00
|
|
|
// Start the pacemaker with the heartrate received from Hello, after
|
|
|
|
// initializing everything. This ensures we only heartbeat if the websocket
|
|
|
|
// is authenticated.
|
|
|
|
g.Pacemaker = &Pacemaker{
|
|
|
|
Heartrate: hello.HeartbeatInterval.Duration(),
|
|
|
|
Pace: g.Heartbeat,
|
|
|
|
}
|
|
|
|
// Pacemaker dies here, only when it's fatal.
|
|
|
|
g.paceDeath = g.Pacemaker.StartAsync(g.waitGroup)
|
|
|
|
|
2020-04-12 18:06:43 +00:00
|
|
|
// Start the event handler, which also handles the pacemaker death signal.
|
2020-02-08 06:17:27 +00:00
|
|
|
g.waitGroup.Add(1)
|
2020-01-29 00:01:39 +00:00
|
|
|
go g.handleWS()
|
2020-01-15 04:43:34 +00:00
|
|
|
|
2020-02-08 06:17:27 +00:00
|
|
|
WSDebug("Started successfully.")
|
|
|
|
|
2020-01-15 04:43:34 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleWS uses the Websocket and parses them into g.Events.
|
2020-01-29 00:01:39 +00:00
|
|
|
func (g *Gateway) handleWS() {
|
2020-02-08 06:17:27 +00:00
|
|
|
err := g.eventLoop()
|
2020-04-12 18:06:43 +00:00
|
|
|
g.waitGroup.Done() // mark so Close() can exit.
|
2020-04-12 00:47:09 +00:00
|
|
|
WSDebug("Event loop stopped.")
|
2020-02-08 06:17:27 +00:00
|
|
|
|
|
|
|
if err != nil {
|
2020-03-01 02:13:58 +00:00
|
|
|
g.ErrorLog(err)
|
2020-04-12 18:06:43 +00:00
|
|
|
g.Reconnect()
|
2020-02-08 06:17:27 +00:00
|
|
|
// Reconnect should spawn another eventLoop in its Start function.
|
|
|
|
}
|
|
|
|
}
|
2020-01-15 04:43:34 +00:00
|
|
|
|
2020-02-08 06:17:27 +00:00
|
|
|
func (g *Gateway) eventLoop() error {
|
|
|
|
ch := g.WS.Listen()
|
2020-01-20 11:06:20 +00:00
|
|
|
|
2020-01-15 04:43:34 +00:00
|
|
|
for {
|
|
|
|
select {
|
2020-01-20 09:32:28 +00:00
|
|
|
case err := <-g.paceDeath:
|
2020-02-08 06:17:27 +00:00
|
|
|
// Got a paceDeath, we're exiting from here on out.
|
|
|
|
g.paceDeath = nil // mark
|
|
|
|
|
2020-01-20 11:06:20 +00:00
|
|
|
if err == nil {
|
2020-02-08 06:17:27 +00:00
|
|
|
WSDebug("Pacemaker stopped without errors.")
|
2020-01-20 11:06:20 +00:00
|
|
|
// No error, just exit normally.
|
2020-02-08 06:17:27 +00:00
|
|
|
return nil
|
2020-01-20 11:06:20 +00:00
|
|
|
}
|
|
|
|
|
2020-03-02 00:39:40 +00:00
|
|
|
return errors.Wrap(err, "Pacemaker died, reconnecting")
|
2020-01-19 06:14:46 +00:00
|
|
|
|
2020-01-15 04:43:34 +00:00
|
|
|
case ev := <-ch:
|
|
|
|
// Handle the event
|
2020-04-06 20:26:00 +00:00
|
|
|
if err := HandleEvent(g, ev); err != nil {
|
2020-01-16 03:28:21 +00:00
|
|
|
g.ErrorLog(errors.Wrap(err, "WS handler error"))
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *Gateway) Send(code OPCode, v interface{}) error {
|
2020-03-01 02:13:58 +00:00
|
|
|
return g.send(true, code, v)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *Gateway) send(lock bool, code OPCode, v interface{}) error {
|
2020-01-15 04:43:34 +00:00
|
|
|
var op = OP{
|
|
|
|
Code: code,
|
|
|
|
}
|
|
|
|
|
|
|
|
if v != nil {
|
2020-01-15 07:34:18 +00:00
|
|
|
b, err := g.Driver.Marshal(v)
|
2020-01-15 04:43:34 +00:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "Failed to encode v")
|
|
|
|
}
|
|
|
|
|
|
|
|
op.Data = b
|
|
|
|
}
|
|
|
|
|
2020-01-15 07:34:18 +00:00
|
|
|
b, err := g.Driver.Marshal(op)
|
2020-01-15 04:43:34 +00:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "Failed to encode payload")
|
|
|
|
}
|
|
|
|
|
2020-04-06 19:03:42 +00:00
|
|
|
// if lock {
|
|
|
|
// g.available.RLock()
|
|
|
|
// defer g.available.RUnlock()
|
|
|
|
// }
|
2020-03-01 02:13:58 +00:00
|
|
|
|
2020-04-06 19:03:42 +00:00
|
|
|
// WS should already be thread-safe.
|
|
|
|
return g.WS.Send(b)
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|