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"
|
|
|
|
"net/url"
|
2021-04-03 01:05:27 +00:00
|
|
|
"strings"
|
2020-02-08 06:17:27 +00:00
|
|
|
"sync"
|
2020-01-15 04:43:34 +00:00
|
|
|
"time"
|
|
|
|
|
2021-06-02 02:53:19 +00:00
|
|
|
"github.com/diamondburned/arikawa/v3/api"
|
|
|
|
"github.com/diamondburned/arikawa/v3/internal/moreatomic"
|
|
|
|
"github.com/diamondburned/arikawa/v3/utils/json"
|
|
|
|
"github.com/diamondburned/arikawa/v3/utils/wsutil"
|
2021-04-07 18:38:26 +00:00
|
|
|
"github.com/gorilla/websocket"
|
2020-01-15 04:43:34 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
2020-04-19 16:30:12 +00:00
|
|
|
var (
|
2020-10-30 18:24:10 +00:00
|
|
|
Version = api.Version
|
2020-01-15 04:43:34 +00:00
|
|
|
Encoding = "json"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2020-04-19 16:17:04 +00:00
|
|
|
ErrMissingForResume = errors.New("missing session ID or sequence for resuming")
|
2021-04-07 18:38:26 +00:00
|
|
|
ErrWSMaxTries = errors.New(
|
|
|
|
"could not connect to the Discord gateway before reaching the timeout")
|
|
|
|
ErrClosed = errors.New("the gateway is closed and cannot reconnect")
|
2020-01-15 04:43:34 +00:00
|
|
|
)
|
|
|
|
|
2021-04-07 18:38:26 +00:00
|
|
|
// see
|
|
|
|
// https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-close-event-codes
|
|
|
|
const errCodeShardingRequired = 4011
|
|
|
|
|
2020-04-19 21:53:53 +00:00
|
|
|
// URL asks Discord for a Websocket URL to the Gateway.
|
|
|
|
func URL() (string, error) {
|
2021-06-10 23:48:32 +00:00
|
|
|
return api.GatewayURL()
|
2020-04-19 16:17:04 +00:00
|
|
|
}
|
2020-01-15 04:43:34 +00:00
|
|
|
|
2020-04-19 21:53:53 +00:00
|
|
|
// BotURL fetches the Gateway URL along with extra metadata. The token
|
2020-04-19 16:17:04 +00:00
|
|
|
// passed in will NOT be prefixed with Bot.
|
2021-06-10 23:48:32 +00:00
|
|
|
func BotURL(token string) (*api.BotData, error) {
|
|
|
|
return api.NewClient(token).BotURL()
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddGatewayParams appends into the given URL string the gateway URL
|
|
|
|
// parameters.
|
|
|
|
func AddGatewayParams(baseURL string) string {
|
|
|
|
param := url.Values{
|
|
|
|
"v": {Version},
|
|
|
|
"encoding": {Encoding},
|
|
|
|
}
|
|
|
|
|
|
|
|
return baseURL + "?" + param.Encode()
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type Gateway struct {
|
2020-11-29 01:22:03 +00:00
|
|
|
WS *wsutil.Websocket
|
|
|
|
|
|
|
|
// WSTimeout is a timeout for an arbitrary action. An example of this is the
|
|
|
|
// timeout for Start and the timeout for sending each Gateway command
|
|
|
|
// independently.
|
2020-01-15 04:43:34 +00:00
|
|
|
WSTimeout time.Duration
|
2021-04-07 18:38:26 +00:00
|
|
|
|
|
|
|
// ReconnectAttempts are the amount of attempts made to Reconnect, before
|
|
|
|
// aborting. If this set to 0, unlimited attempts will be made.
|
|
|
|
ReconnectAttempts uint
|
2020-01-15 04:43:34 +00:00
|
|
|
|
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-12-31 08:35:37 +00:00
|
|
|
sessionMu sync.RWMutex
|
|
|
|
sessionID string
|
2020-01-15 04:43:34 +00:00
|
|
|
|
2020-01-15 07:34:18 +00:00
|
|
|
Identifier *Identifier
|
2020-11-29 01:22:03 +00:00
|
|
|
Sequence *moreatomic.Int64
|
2020-08-20 03:48:55 +00:00
|
|
|
|
|
|
|
PacerLoop wsutil.PacemakerLoop
|
2020-01-15 04:43:34 +00:00
|
|
|
|
|
|
|
ErrorLog func(err error) // default to log.Println
|
2020-10-30 20:41:04 +00:00
|
|
|
// FatalErrorCallback is called, if the Gateway exits fatally. At the point
|
|
|
|
// of calling, the gateway will be already closed.
|
|
|
|
//
|
|
|
|
// Currently this will only be called, if the ReconnectTimeout was changed
|
|
|
|
// to a definite timeout, and connection could not be established during
|
|
|
|
// that time.
|
|
|
|
// err will be ErrWSMaxTries in that case.
|
|
|
|
//
|
|
|
|
// Defaults to noop.
|
|
|
|
FatalErrorCallback func(err error)
|
2020-03-01 02:13:58 +00:00
|
|
|
|
2021-04-07 18:38:26 +00:00
|
|
|
// AfterClose is called after each close or pause. It is used mainly for
|
2020-04-07 02:36:06 +00:00
|
|
|
// reconnections or any type of connection interruptions.
|
2021-04-07 18:38:26 +00:00
|
|
|
//
|
|
|
|
// Constructors will use a no-op function by default.
|
|
|
|
AfterClose func(err error)
|
2020-04-07 02:36:06 +00:00
|
|
|
|
2021-06-10 23:48:32 +00:00
|
|
|
onShardingRequired func()
|
2021-04-07 18:38:26 +00:00
|
|
|
|
2021-06-10 23:48:32 +00:00
|
|
|
waitGroup sync.WaitGroup
|
|
|
|
closed chan struct{}
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
// NewGatewayWithIntents creates a new Gateway with the given intents and the
|
|
|
|
// default stdlib JSON driver. Refer to NewGatewayWithDriver and AddIntents.
|
|
|
|
func NewGatewayWithIntents(token string, intents ...Intents) (*Gateway, error) {
|
|
|
|
g, err := NewGateway(token)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, intent := range intents {
|
2020-10-29 05:49:18 +00:00
|
|
|
g.AddIntents(intent)
|
2020-07-11 19:50:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return g, nil
|
|
|
|
}
|
|
|
|
|
2021-04-03 01:05:27 +00:00
|
|
|
// NewGateway creates a new Gateway to the default Discord server.
|
2020-01-15 04:43:34 +00:00
|
|
|
func NewGateway(token string) (*Gateway, error) {
|
2021-04-03 01:05:27 +00:00
|
|
|
return NewIdentifiedGateway(DefaultIdentifier(token))
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewIdentifiedGateway creates a new Gateway with the given gateway identifier
|
|
|
|
// and the default everything. Sharded bots should prefer this function for the
|
|
|
|
// shared identifier.
|
|
|
|
func NewIdentifiedGateway(id *Identifier) (*Gateway, error) {
|
|
|
|
var gatewayURL string
|
2021-06-10 23:48:32 +00:00
|
|
|
var botData *api.BotData
|
2021-04-03 01:05:27 +00:00
|
|
|
var err error
|
|
|
|
|
|
|
|
if strings.HasPrefix(id.Token, "Bot ") {
|
|
|
|
botData, err = BotURL(id.Token)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to get bot data")
|
|
|
|
}
|
|
|
|
gatewayURL = botData.URL
|
|
|
|
|
|
|
|
} else {
|
|
|
|
gatewayURL, err = URL()
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to get gateway endpoint")
|
|
|
|
}
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
|
2021-06-10 23:48:32 +00:00
|
|
|
gatewayURL = AddGatewayParams(gatewayURL)
|
2021-04-03 01:05:27 +00:00
|
|
|
gateway := NewCustomIdentifiedGateway(gatewayURL, id)
|
|
|
|
|
|
|
|
// Use the supplied connect rate limit, if any.
|
|
|
|
if botData != nil && botData.StartLimit != nil {
|
|
|
|
resetAt := time.Now().Add(botData.StartLimit.ResetAfter.Duration())
|
|
|
|
limiter := gateway.Identifier.IdentifyGlobalLimit
|
|
|
|
|
|
|
|
// Update the burst to be the current given time and reset it back to
|
|
|
|
// the default when the given time is reached.
|
|
|
|
limiter.SetBurst(botData.StartLimit.Remaining)
|
|
|
|
limiter.SetBurstAt(resetAt, botData.StartLimit.Total)
|
2020-01-15 04:43:34 +00:00
|
|
|
|
2021-04-03 01:05:27 +00:00
|
|
|
// Update the maximum number of identify requests allowed per 5s.
|
|
|
|
gateway.Identifier.IdentifyShortLimit.SetBurst(botData.StartLimit.MaxConcurrency)
|
|
|
|
}
|
|
|
|
|
|
|
|
return gateway, nil
|
2020-04-19 16:17:04 +00:00
|
|
|
}
|
2020-01-15 04:43:34 +00:00
|
|
|
|
2021-04-03 01:05:27 +00:00
|
|
|
// NewCustomGateway creates a new Gateway with a custom gateway URL and a new
|
|
|
|
// Identifier. Most bots connecting to the official server should not use these
|
|
|
|
// custom functions.
|
2020-04-24 06:34:08 +00:00
|
|
|
func NewCustomGateway(gatewayURL, token string) *Gateway {
|
2021-04-03 01:05:27 +00:00
|
|
|
return NewCustomIdentifiedGateway(gatewayURL, DefaultIdentifier(token))
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewCustomIdentifiedGateway creates a new Gateway with a custom gateway URL
|
|
|
|
// and a pre-existing Identifier. Refer to NewCustomGateway.
|
|
|
|
func NewCustomIdentifiedGateway(gatewayURL string, id *Identifier) *Gateway {
|
2020-04-19 16:17:04 +00:00
|
|
|
return &Gateway{
|
2020-04-24 22:30:15 +00:00
|
|
|
WS: wsutil.NewCustom(wsutil.NewConn(), gatewayURL),
|
|
|
|
WSTimeout: wsutil.WSTimeout,
|
|
|
|
|
2020-04-24 06:34:08 +00:00
|
|
|
Events: make(chan Event, wsutil.WSBuffer),
|
2021-04-03 01:05:27 +00:00
|
|
|
Identifier: id,
|
2020-11-29 01:22:03 +00:00
|
|
|
Sequence: moreatomic.NewInt64(0),
|
2020-04-24 22:30:15 +00:00
|
|
|
|
2020-04-24 06:34:08 +00:00
|
|
|
ErrorLog: wsutil.WSError,
|
2020-04-19 16:17:04 +00:00
|
|
|
AfterClose: func(error) {},
|
|
|
|
}
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
|
2020-10-29 05:49:18 +00:00
|
|
|
// AddIntents adds a Gateway Intent before connecting to the Gateway. As such,
|
|
|
|
// this function will only work before Open() is called.
|
|
|
|
func (g *Gateway) AddIntents(i Intents) {
|
2020-07-11 19:50:32 +00:00
|
|
|
g.Identifier.Intents |= i
|
|
|
|
}
|
|
|
|
|
2020-11-19 18:43:31 +00:00
|
|
|
// HasIntents reports if the Gateway has the passed Intents.
|
2020-12-08 19:46:49 +00:00
|
|
|
//
|
|
|
|
// If no intents are set, i.e. if using a user account HasIntents will always
|
|
|
|
// return true.
|
2020-11-19 18:43:31 +00:00
|
|
|
func (g *Gateway) HasIntents(intents Intents) bool {
|
2020-12-08 19:46:49 +00:00
|
|
|
if g.Identifier.Intents == 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2020-11-19 18:43:31 +00:00
|
|
|
return g.Identifier.Intents.Has(intents)
|
|
|
|
}
|
|
|
|
|
2021-04-07 18:38:26 +00:00
|
|
|
// Close closes the underlying Websocket connection, invalidating the session
|
2021-05-29 19:39:03 +00:00
|
|
|
// ID.
|
2021-04-07 18:38:26 +00:00
|
|
|
//
|
2021-05-29 19:39:03 +00:00
|
|
|
// It will send a closing frame before ending the connection, closing it
|
|
|
|
// gracefully. This will cause the bot to appear as offline instantly.
|
2020-10-30 18:02:37 +00:00
|
|
|
func (g *Gateway) Close() error {
|
2021-04-07 18:38:26 +00:00
|
|
|
return g.close(true)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Pause pauses the Gateway connection, by ending the connection without
|
|
|
|
// sending a closing frame. This allows the connection to be resumed at a later
|
|
|
|
// point, by calling Reconnect or ReconnectCtx.
|
|
|
|
func (g *Gateway) Pause() error {
|
|
|
|
return g.close(false)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *Gateway) close(graceful bool) (err error) {
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("Trying to close. Pacemaker check skipped.")
|
|
|
|
wsutil.WSDebug("Closing the Websocket...")
|
2020-03-07 19:50:30 +00:00
|
|
|
|
2021-04-07 18:38:26 +00:00
|
|
|
if graceful {
|
|
|
|
err = g.WS.CloseGracefully()
|
|
|
|
} else {
|
|
|
|
err = g.WS.Close()
|
|
|
|
}
|
|
|
|
|
2020-10-30 18:02:37 +00:00
|
|
|
if errors.Is(err, wsutil.ErrWebsocketClosed) {
|
|
|
|
wsutil.WSDebug("Websocket already closed.")
|
|
|
|
return nil
|
2020-03-07 19:50:30 +00:00
|
|
|
}
|
|
|
|
|
2021-01-01 07:48:29 +00:00
|
|
|
// Explicitly signal the pacemaker loop to stop. We should do this in case
|
|
|
|
// the Start function exited before it could bind the event channel into the
|
|
|
|
// loop.
|
|
|
|
g.PacerLoop.Stop()
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("Websocket closed; error:", err)
|
2020-02-08 06:17:27 +00:00
|
|
|
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("Waiting for the Pacemaker loop to exit.")
|
2020-02-08 06:17:27 +00:00
|
|
|
g.waitGroup.Wait()
|
2020-10-30 18:02:37 +00:00
|
|
|
wsutil.WSDebug("Pacemaker loop exited.")
|
|
|
|
|
|
|
|
g.AfterClose(err)
|
|
|
|
wsutil.WSDebug("AfterClose callback finished.")
|
2020-02-08 06:17:27 +00:00
|
|
|
|
2021-04-07 18:38:26 +00:00
|
|
|
if graceful {
|
|
|
|
// If a Reconnect is in progress, signal to cancel.
|
|
|
|
close(g.closed)
|
2020-01-15 04:43:34 +00:00
|
|
|
|
2021-04-07 18:38:26 +00:00
|
|
|
// Delete our session id, as we just invalidated it.
|
|
|
|
g.sessionMu.Lock()
|
|
|
|
g.sessionID = ""
|
|
|
|
g.sessionMu.Unlock()
|
2021-01-30 04:25:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-12-31 08:35:37 +00:00
|
|
|
// SessionID returns the session ID received after Ready. This function is
|
|
|
|
// concurrently safe.
|
|
|
|
func (g *Gateway) SessionID() string {
|
|
|
|
g.sessionMu.RLock()
|
|
|
|
defer g.sessionMu.RUnlock()
|
|
|
|
|
|
|
|
return g.sessionID
|
|
|
|
}
|
|
|
|
|
2021-06-14 20:56:25 +00:00
|
|
|
// UseSessionID overrides the internal session ID for the one the user provides.
|
|
|
|
func (g *Gateway) UseSessionID(sessionID string) {
|
|
|
|
g.sessionMu.Lock()
|
|
|
|
defer g.sessionMu.Unlock()
|
|
|
|
|
|
|
|
g.sessionID = sessionID
|
|
|
|
}
|
|
|
|
|
2021-06-10 23:48:32 +00:00
|
|
|
// OnShardingRequired sets the function to be called if Discord closes with
|
|
|
|
// error code 4011 aka Sharding Required. When called, the Gateway will already
|
|
|
|
// be closed, and can (after increasing the number of shards) be reopened using
|
|
|
|
// Open. Reconnect or ReconnectCtx, however, will not be available as the
|
|
|
|
// session is invalidated.
|
|
|
|
//
|
|
|
|
// The gateway will completely halt what it's doing in the background when this
|
|
|
|
// callback is called.
|
|
|
|
func (g *Gateway) OnShardingRequired(fn func()) {
|
|
|
|
g.onShardingRequired = fn
|
|
|
|
}
|
|
|
|
|
2021-05-29 19:39:03 +00:00
|
|
|
// Reconnect tries to reconnect to the Gateway until the ReconnectAttempts are
|
|
|
|
// reached.
|
2020-07-15 23:32:53 +00:00
|
|
|
func (g *Gateway) Reconnect() {
|
2021-05-29 19:39:03 +00:00
|
|
|
g.ReconnectCtx(context.Background())
|
2020-04-24 06:34:08 +00:00
|
|
|
}
|
|
|
|
|
2021-04-07 18:38:26 +00:00
|
|
|
// ReconnectCtx attempts to Reconnect until context expires.
|
2020-10-30 20:41:04 +00:00
|
|
|
// If the context expires FatalErrorCallback will be called with ErrWSMaxTries,
|
|
|
|
// and the last error returned by Open will be returned.
|
2020-07-29 23:29:01 +00:00
|
|
|
func (g *Gateway) ReconnectCtx(ctx context.Context) (err error) {
|
2020-04-24 06:34:08 +00:00
|
|
|
wsutil.WSDebug("Reconnecting...")
|
2020-02-08 06:17:27 +00:00
|
|
|
|
2020-04-12 18:06:43 +00:00
|
|
|
// Guarantee the gateway is already closed. Ignore its error, as we're
|
|
|
|
// redialing anyway.
|
2021-04-07 18:38:26 +00:00
|
|
|
g.Pause()
|
2020-01-29 03:54:22 +00:00
|
|
|
|
2021-04-07 18:38:26 +00:00
|
|
|
for try := uint(1); g.ReconnectAttempts == 0 || g.ReconnectAttempts >= try; try++ {
|
2020-07-29 23:29:01 +00:00
|
|
|
select {
|
2021-04-07 18:38:26 +00:00
|
|
|
case <-g.closed:
|
|
|
|
g.ErrorLog(ErrClosed)
|
|
|
|
return ErrClosed
|
2020-07-29 23:29:01 +00:00
|
|
|
case <-ctx.Done():
|
2021-04-07 18:38:26 +00:00
|
|
|
wsutil.WSDebug("Unable to Reconnect after", try, "attempts, aborting")
|
2020-10-30 20:41:04 +00:00
|
|
|
g.FatalErrorCallback(ErrWSMaxTries)
|
2020-07-29 23:29:01 +00:00
|
|
|
return err
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
2021-04-07 18:38:26 +00:00
|
|
|
wsutil.WSDebug("Trying to dial, attempt", try)
|
2020-01-17 22:29:13 +00:00
|
|
|
|
2021-04-07 18:38:26 +00:00
|
|
|
// if we encounter an error, make sure we return it, and not nil
|
2021-06-10 23:48:32 +00:00
|
|
|
if oerr := g.Open(ctx); oerr != nil {
|
2021-04-07 18:38:26 +00:00
|
|
|
err = oerr
|
|
|
|
g.ErrorLog(oerr)
|
2020-01-19 06:34:52 +00:00
|
|
|
|
2021-04-07 18:38:26 +00:00
|
|
|
wait := time.Duration(4+2*try) * time.Second
|
|
|
|
if wait > 60*time.Second {
|
|
|
|
wait = 60 * time.Second
|
|
|
|
}
|
|
|
|
|
|
|
|
time.Sleep(wait)
|
2020-07-29 23:29:01 +00:00
|
|
|
continue
|
2020-01-17 22:29:13 +00:00
|
|
|
}
|
|
|
|
|
2021-04-07 18:38:26 +00:00
|
|
|
wsutil.WSDebug("Started after attempt:", try)
|
|
|
|
return nil
|
2020-02-20 03:36:00 +00:00
|
|
|
}
|
2021-04-07 18:38:26 +00:00
|
|
|
|
|
|
|
wsutil.WSDebug("Unable to Reconnect after", g.ReconnectAttempts, "attempts, aborting")
|
|
|
|
return err
|
2020-02-20 03:36:00 +00:00
|
|
|
}
|
2020-01-17 22:29:13 +00:00
|
|
|
|
2021-06-10 23:48:32 +00:00
|
|
|
// Open connects to the Websocket and authenticates it. You should usually use
|
|
|
|
// this function over Start(). The given context provides cancellation and
|
|
|
|
// timeout.
|
|
|
|
func (g *Gateway) Open(ctx context.Context) error {
|
2020-07-11 19:50:32 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), g.WSTimeout)
|
|
|
|
defer cancel()
|
|
|
|
|
2020-02-20 03:36:00 +00:00
|
|
|
// Reconnect to the Gateway
|
|
|
|
if err := g.WS.Dial(ctx); err != nil {
|
2021-04-07 18:38:26 +00:00
|
|
|
return errors.Wrap(err, "failed to Reconnect")
|
2020-02-20 03:36:00 +00:00
|
|
|
}
|
2020-01-17 22:29:13 +00:00
|
|
|
|
2020-04-24 06:34:08 +00:00
|
|
|
wsutil.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
|
2020-07-11 19:50:32 +00:00
|
|
|
if err := g.StartCtx(ctx); err != nil {
|
2020-02-20 03:36:00 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
// Start calls StartCtx with a background context. You wouldn't usually use this
|
2020-04-06 19:03:42 +00:00
|
|
|
// function, but Open() instead.
|
2020-01-15 04:43:34 +00:00
|
|
|
func (g *Gateway) Start() error {
|
2020-07-11 19:50:32 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), g.WSTimeout)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
return g.StartCtx(ctx)
|
|
|
|
}
|
2020-03-01 02:13:58 +00:00
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
// StartCtx authenticates with the websocket, or resume from a dead Websocket
|
|
|
|
// connection. You wouldn't usually use this function, but OpenCtx() instead.
|
|
|
|
func (g *Gateway) StartCtx(ctx context.Context) error {
|
2021-04-07 18:38:26 +00:00
|
|
|
g.closed = make(chan struct{})
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
if err := g.start(ctx); err != nil {
|
2020-04-24 06:34:08 +00:00
|
|
|
wsutil.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 {
|
2020-04-24 06:34:08 +00:00
|
|
|
wsutil.WSDebug("Failed to close after start fail:", err)
|
2020-02-08 06:17:27 +00:00
|
|
|
}
|
2020-01-20 11:06:20 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-07-11 19:50:32 +00:00
|
|
|
|
2020-01-20 11:06:20 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
func (g *Gateway) start(ctx context.Context) error {
|
2020-01-15 04:43:34 +00:00
|
|
|
// This is where we'll get our events
|
|
|
|
ch := g.WS.Listen()
|
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
// Create a new Hello event and wait for it.
|
2020-01-15 04:43:34 +00:00
|
|
|
var hello HelloEvent
|
2020-07-11 19:50:32 +00:00
|
|
|
// Wait for an OP 10 Hello.
|
|
|
|
select {
|
|
|
|
case e, ok := <-ch:
|
|
|
|
if !ok {
|
|
|
|
return errors.New("unexpected ws close while waiting for Hello")
|
|
|
|
}
|
|
|
|
if _, err := wsutil.AssertEvent(e, HelloOP, &hello); err != nil {
|
|
|
|
return errors.Wrap(err, "error at Hello")
|
|
|
|
}
|
|
|
|
case <-ctx.Done():
|
|
|
|
return errors.Wrap(ctx.Err(), "failed to wait for Hello event")
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
|
2020-10-31 22:52:55 +00:00
|
|
|
wsutil.WSDebug("Hello received; duration:", hello.HeartbeatInterval)
|
|
|
|
|
2020-12-31 08:35:37 +00:00
|
|
|
// Start the event handler, which also handles the pacemaker death signal.
|
|
|
|
g.waitGroup.Add(1)
|
|
|
|
|
|
|
|
// Use the pacemaker loop.
|
|
|
|
g.PacerLoop.StartBeating(hello.HeartbeatInterval.Duration(), g, func(err error) {
|
|
|
|
g.waitGroup.Done() // mark so Close() can exit.
|
|
|
|
wsutil.WSDebug("Event loop stopped with error:", err)
|
|
|
|
|
2021-06-10 23:48:32 +00:00
|
|
|
if err != nil && g.onShardingRequired != nil {
|
|
|
|
// If Discord signals us sharding is required, do not attempt to
|
|
|
|
// Reconnect, unless we don't know what to do. Instead invalidate
|
|
|
|
// our session ID, as we cannot resume, call OnShardingRequired, and
|
|
|
|
// exit.
|
|
|
|
var cerr *websocket.CloseError
|
|
|
|
if errors.As(err, &cerr) && cerr.Code == errCodeShardingRequired {
|
|
|
|
g.ErrorLog(cerr)
|
|
|
|
g.UseSessionID("")
|
|
|
|
g.onShardingRequired()
|
|
|
|
return
|
|
|
|
}
|
2021-04-07 18:38:26 +00:00
|
|
|
}
|
|
|
|
|
2021-01-01 07:01:38 +00:00
|
|
|
// Bail if there is no error or if the error is an explicit close, as
|
|
|
|
// there might be an ongoing reconnection.
|
|
|
|
if err == nil || errors.Is(err, wsutil.ErrWebsocketClosed) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-04-07 18:38:26 +00:00
|
|
|
// Only attempt to Reconnect if we have a session ID at all. We may not
|
2020-12-31 08:35:37 +00:00
|
|
|
// have one if we haven't even connected successfully once.
|
2021-01-01 07:01:38 +00:00
|
|
|
if g.SessionID() != "" {
|
2020-12-31 08:35:37 +00:00
|
|
|
g.ErrorLog(err)
|
|
|
|
g.Reconnect()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2020-01-15 04:43:34 +00:00
|
|
|
// Send Discord either the Identify packet (if it's a fresh connection), or
|
|
|
|
// a Resume packet (if it's a dead connection).
|
2020-12-31 08:35:37 +00:00
|
|
|
if g.SessionID() == "" {
|
2020-01-15 04:43:34 +00:00
|
|
|
// SessionID is empty, so this is a completely new session.
|
2020-07-11 19:50:32 +00:00
|
|
|
if err := g.IdentifyCtx(ctx); err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to identify")
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
} else {
|
2020-07-11 19:50:32 +00:00
|
|
|
if err := g.ResumeCtx(ctx); err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to resume")
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-06 20:26:00 +00:00
|
|
|
// Expect either READY or RESUMED before continuing.
|
2020-04-24 06:34:08 +00:00
|
|
|
wsutil.WSDebug("Waiting for either READY or RESUMED.")
|
2020-04-06 20:26:00 +00:00
|
|
|
|
2020-04-19 16:17:04 +00:00
|
|
|
// WaitForEvent should
|
2020-07-11 19:50:32 +00:00
|
|
|
err := wsutil.WaitForEvent(ctx, g, ch, func(op *wsutil.OP) bool {
|
2020-04-06 20:26:00 +00:00
|
|
|
switch op.EventName {
|
|
|
|
case "READY":
|
2020-04-24 06:34:08 +00:00
|
|
|
wsutil.WSDebug("Found READY event.")
|
2020-04-06 20:26:00 +00:00
|
|
|
return true
|
|
|
|
case "RESUMED":
|
2020-04-24 06:34:08 +00:00
|
|
|
wsutil.WSDebug("Found RESUMED event.")
|
2020-04-06 20:26:00 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
})
|
2020-01-19 21:54:16 +00:00
|
|
|
|
2020-04-06 20:26:00 +00:00
|
|
|
if err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "first error")
|
2020-01-19 21:54:16 +00:00
|
|
|
}
|
|
|
|
|
2020-12-31 08:35:37 +00:00
|
|
|
// Bind the event channel to the pacemaker loop.
|
|
|
|
g.PacerLoop.SetEventChannel(ch)
|
2020-01-15 04:43:34 +00:00
|
|
|
|
2020-04-25 07:13:07 +00:00
|
|
|
wsutil.WSDebug("Started successfully.")
|
2020-02-08 06:17:27 +00:00
|
|
|
|
2020-04-25 07:13:07 +00:00
|
|
|
return nil
|
2020-02-08 06:17:27 +00:00
|
|
|
}
|
2020-01-15 04:43:34 +00:00
|
|
|
|
2020-07-11 19:50:32 +00:00
|
|
|
// SendCtx is a low-level function to send an OP payload to the Gateway. Most
|
|
|
|
// users shouldn't touch this, unless they know what they're doing.
|
|
|
|
func (g *Gateway) SendCtx(ctx context.Context, code OPCode, v interface{}) error {
|
2020-04-24 22:09:05 +00:00
|
|
|
var op = wsutil.OP{
|
2020-01-15 04:43:34 +00:00
|
|
|
Code: code,
|
|
|
|
}
|
|
|
|
|
|
|
|
if v != nil {
|
2020-04-24 06:34:08 +00:00
|
|
|
b, err := json.Marshal(v)
|
2020-01-15 04:43:34 +00:00
|
|
|
if err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to encode v")
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
op.Data = b
|
|
|
|
}
|
|
|
|
|
2020-04-24 06:34:08 +00:00
|
|
|
b, err := json.Marshal(op)
|
2020-01-15 04:43:34 +00:00
|
|
|
if err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "failed to encode payload")
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
|
2020-04-06 19:03:42 +00:00
|
|
|
// WS should already be thread-safe.
|
2020-07-11 19:50:32 +00:00
|
|
|
return g.WS.SendCtx(ctx, b)
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|