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-04-19 16:17:04 +00:00
|
|
|
"net/http"
|
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-19 16:17:04 +00:00
|
|
|
"github.com/diamondburned/arikawa/discord"
|
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"
|
|
|
|
)
|
|
|
|
|
2020-04-19 16:30:12 +00:00
|
|
|
var (
|
2020-01-15 04:43:34 +00:00
|
|
|
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 (
|
2020-04-19 16:17:04 +00:00
|
|
|
ErrMissingForResume = errors.New("missing session ID or sequence for resuming")
|
|
|
|
ErrWSMaxTries = errors.New("max tries reached")
|
2020-01-15 04:43:34 +00:00
|
|
|
)
|
|
|
|
|
2020-04-19 16:17:04 +00:00
|
|
|
// GatewayBotData contains the GatewayURL as well as extra metadata on how to
|
|
|
|
// shard bots.
|
|
|
|
type GatewayBotData struct {
|
|
|
|
URL string `json:"url"`
|
|
|
|
Shards int `json:"shards,omitempty"`
|
|
|
|
StartLimit *SessionStartLimit `json:"session_start_limit"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// SessionStartLimit is the information on the current session start limit. It's
|
|
|
|
// used in GatewayBotData.
|
|
|
|
type SessionStartLimit struct {
|
|
|
|
Total int `json:"total"`
|
|
|
|
Remaining int `json:"remaining"`
|
|
|
|
ResetAfter discord.Milliseconds `json:"reset_after"`
|
|
|
|
}
|
|
|
|
|
2020-04-19 21:53:53 +00:00
|
|
|
// URL asks Discord for a Websocket URL to the Gateway.
|
|
|
|
func URL() (string, error) {
|
2020-04-19 16:17:04 +00:00
|
|
|
var g GatewayBotData
|
|
|
|
|
2020-04-19 21:53:53 +00:00
|
|
|
return g.URL, httputil.NewClient().RequestJSON(
|
2020-04-19 16:17:04 +00:00
|
|
|
&g, "GET",
|
|
|
|
EndpointGateway,
|
|
|
|
)
|
|
|
|
}
|
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.
|
2020-04-19 21:53:53 +00:00
|
|
|
func BotURL(token string) (*GatewayBotData, error) {
|
2020-04-19 16:17:04 +00:00
|
|
|
var g *GatewayBotData
|
|
|
|
|
2020-04-19 21:53:53 +00:00
|
|
|
return g, httputil.NewClient().RequestJSON(
|
2020-04-19 16:17:04 +00:00
|
|
|
&g, "GET",
|
|
|
|
EndpointGatewayBot,
|
|
|
|
httputil.WithHeaders(http.Header{
|
|
|
|
"Authorization": {token},
|
|
|
|
}),
|
|
|
|
)
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type Gateway struct {
|
2020-04-24 06:34:08 +00:00
|
|
|
WS *wsutil.Websocket
|
2020-01-15 04:43:34 +00:00
|
|
|
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
|
|
|
|
Sequence *Sequence
|
2020-04-24 22:09:05 +00:00
|
|
|
PacerLoop *wsutil.PacemakerLoop
|
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-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-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) {
|
2020-04-19 21:53:53 +00:00
|
|
|
URL, err := URL()
|
2020-01-15 04:43:34 +00:00
|
|
|
if err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return nil, errors.Wrap(err, "failed to get gateway endpoint")
|
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()
|
|
|
|
|
2020-04-24 06:34:08 +00:00
|
|
|
return NewCustomGateway(URL, token), nil
|
2020-04-19 16:17:04 +00:00
|
|
|
}
|
2020-01-15 04:43:34 +00:00
|
|
|
|
2020-04-24 06:34:08 +00:00
|
|
|
func NewCustomGateway(gatewayURL, token string) *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),
|
2020-04-19 16:17:04 +00:00
|
|
|
Identifier: DefaultIdentifier(token),
|
|
|
|
Sequence: NewSequence(),
|
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
|
|
|
}
|
|
|
|
|
|
|
|
// Close closes the underlying Websocket connection.
|
|
|
|
func (g *Gateway) Close() error {
|
2020-04-25 07:13:07 +00:00
|
|
|
wsutil.WSDebug("Trying to close.")
|
|
|
|
|
2020-04-06 19:03:42 +00:00
|
|
|
// Check if the WS is already closed:
|
2020-04-24 22:09:05 +00:00
|
|
|
if g.waitGroup == nil && g.PacerLoop.Stopped() {
|
2020-04-24 06:34:08 +00:00
|
|
|
wsutil.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-04-24 22:09:05 +00:00
|
|
|
if !g.PacerLoop.Stopped() {
|
2020-04-24 06:34:08 +00:00
|
|
|
wsutil.WSDebug("Stopping pacemaker...")
|
2020-03-07 19:50:30 +00:00
|
|
|
|
|
|
|
// Stop the pacemaker and the event handler
|
2020-04-24 22:09:05 +00:00
|
|
|
g.PacerLoop.Stop()
|
2020-01-16 03:28:21 +00:00
|
|
|
|
2020-04-24 06:34:08 +00:00
|
|
|
wsutil.WSDebug("Stopped pacemaker.")
|
2020-03-07 19:50:30 +00:00
|
|
|
}
|
|
|
|
|
2020-04-24 06:34:08 +00:00
|
|
|
wsutil.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-24 06:34:08 +00:00
|
|
|
wsutil.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.
|
2020-04-24 06:34:08 +00:00
|
|
|
func (g *Gateway) Reconnect() error {
|
|
|
|
return g.ReconnectContext(context.Background())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *Gateway) ReconnectContext(ctx context.Context) error {
|
|
|
|
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.
|
|
|
|
g.Close()
|
2020-01-29 03:54:22 +00:00
|
|
|
|
2020-04-12 18:06:43 +00:00
|
|
|
for i := 1; ; i++ {
|
2020-04-24 06:34:08 +00:00
|
|
|
wsutil.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-04-24 06:34:08 +00:00
|
|
|
if err := g.OpenContext(ctx); err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
g.ErrorLog(errors.Wrap(err, "failed to open gateway"))
|
2020-02-20 03:36:00 +00:00
|
|
|
continue
|
2020-01-17 22:29:13 +00:00
|
|
|
}
|
|
|
|
|
2020-04-24 06:34:08 +00:00
|
|
|
wsutil.WSDebug("Started after attempt:", i)
|
|
|
|
return nil
|
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-24 06:34:08 +00:00
|
|
|
return g.OpenContext(context.Background())
|
|
|
|
}
|
2020-02-08 06:17:27 +00:00
|
|
|
|
2020-04-24 06:34:08 +00:00
|
|
|
func (g *Gateway) OpenContext(ctx context.Context) error {
|
2020-02-20 03:36:00 +00:00
|
|
|
// Reconnect to the Gateway
|
|
|
|
if err := g.WS.Dial(ctx); err != nil {
|
2020-05-16 21:14:49 +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
|
|
|
|
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-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
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
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-04-24 22:09:05 +00:00
|
|
|
if _, err := wsutil.AssertEvent(<-ch, HelloOP, &hello); err != nil {
|
2020-05-16 21:14:49 +00:00
|
|
|
return errors.Wrap(err, "error at Hello")
|
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).
|
|
|
|
if g.SessionID == "" {
|
|
|
|
// SessionID is empty, so this is a completely new session.
|
|
|
|
if err := g.Identify(); 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 {
|
|
|
|
if err := g.Resume(); 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-04-24 22:09:05 +00:00
|
|
|
err := wsutil.WaitForEvent(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-04-24 22:09:05 +00:00
|
|
|
// Use the pacemaker loop.
|
|
|
|
g.PacerLoop = wsutil.NewLoop(hello.HeartbeatInterval.Duration(), ch, g)
|
2020-03-07 19:50:30 +00:00
|
|
|
|
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-15 04:43:34 +00:00
|
|
|
|
2020-04-25 07:13:07 +00:00
|
|
|
g.PacerLoop.RunAsync(func(err error) {
|
|
|
|
g.waitGroup.Done() // mark so Close() can exit.
|
|
|
|
wsutil.WSDebug("Event loop stopped with error:", err)
|
2020-02-08 06:17:27 +00:00
|
|
|
|
2020-04-25 07:13:07 +00:00
|
|
|
if err != nil {
|
|
|
|
g.ErrorLog(err)
|
|
|
|
g.Reconnect()
|
|
|
|
}
|
|
|
|
})
|
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
|
|
|
|
|
|
|
func (g *Gateway) Send(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.
|
|
|
|
return g.WS.Send(b)
|
2020-01-15 04:43:34 +00:00
|
|
|
}
|