-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
193 lines (159 loc) · 4.54 KB
/
state.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package gateway
import (
"encoding/binary"
"errors"
"fmt"
"github.com/discordpkg/gateway/encoding"
"io"
"net"
"strings"
"sync/atomic"
"time"
"github.com/discordpkg/gateway/closecode"
"github.com/discordpkg/gateway/event"
"github.com/discordpkg/gateway/event/opcode"
)
var ErrRateLimited = errors.New("unable to send message to Discord due to hitting rate limited")
var ErrIdentifyRateLimited = fmt.Errorf("can't send identify command: %w", ErrRateLimited)
type State interface {
fmt.Stringer
Process(payload *Payload, pipe io.Writer) error
}
// StateCloser any state implementing a Close method may overwrite the default behavior of StateCtx.Close
type StateCloser interface {
State
Close(closeWriter io.Writer) error
}
type StateCtx struct {
heartbeatACK atomic.Bool
sequenceNumber atomic.Int64
closed atomic.Bool
client *Client
SessionID string
ResumeGatewayURL string
state State
logger Logger
}
func (ctx *StateCtx) String() string {
return fmt.Sprintf("state-ctx(%s)", ctx.state.String())
}
func (ctx *StateCtx) SetState(state State) {
ctx.logger.Debug("state update: %s", state)
switch state.(type) {
case *ClosedState:
ctx.closed.Store(true)
case *StateCtx:
ctx.logger.Panic("StateCtx can not be an internal state")
}
ctx.state = state
}
func (ctx *StateCtx) CloseCodeHandler(payload *Payload) error {
if payload.CloseCode == 0 {
return nil
}
ctx.logger.Debug("handling close code")
if closecode.CanReconnectAfter(payload.CloseCode) {
ctx.SetState(&ResumableClosedState{ctx})
} else {
ctx.SetState(&ClosedState{})
}
return &DiscordError{
CloseCode: payload.CloseCode,
Reason: strings.Trim(string(payload.Data), "\""),
}
}
func (ctx *StateCtx) SessionIssueHandler(payload *Payload) error {
switch payload.Op {
case opcode.InvalidSession:
var d bool
if err := encoding.Unmarshal(payload.Data, &d); err != nil || !d {
ctx.SetState(&ClosedState{})
} else {
ctx.SetState(&ResumableClosedState{ctx})
}
case opcode.Reconnect:
ctx.SetState(&ResumableClosedState{ctx})
default:
return nil
}
ctx.logger.Debug("found issue with session")
return &DiscordError{
OpCode: payload.Op,
}
}
func (ctx *StateCtx) Process(payload *Payload, pipe io.Writer) error {
if err := ctx.CloseCodeHandler(payload); err != nil {
return err
}
if err := ctx.SessionIssueHandler(payload); err != nil {
return err
}
return ctx.state.Process(payload, pipe)
}
func (ctx *StateCtx) Close(closeWriter io.Writer) error {
if ctx.closed.Load() {
return net.ErrClosed
}
if closer, ok := ctx.state.(StateCloser); ok {
return closer.Close(closeWriter)
}
// if resume details exist we close with an intent of resuming
if ctx.SessionID != "" && ctx.ResumeGatewayURL != "" && ctx.sequenceNumber.Load() > 0 {
return ctx.WriteRestartClose(closeWriter)
}
return ctx.WriteNormalClose(closeWriter)
}
func (ctx *StateCtx) Write(pipe io.Writer, evt event.Type, payload encoding.RawMessage) error {
opc := evt.OpCode()
ctx.logger.Debug("writing '%s' payload: %s", evt, string(payload))
// heartbeat should always be sent.
// Try reserving some calls for heartbeats when you configure your rate limiter.
switch opc {
case opcode.Dispatch, opcode.Invalid:
return errors.New("can not send event type to Discord, it's receive only")
case opcode.Heartbeat:
if ok, timeout := ctx.client.commandRateLimiter.Try(ctx.client.id); !ok {
<-time.After(timeout)
}
case opcode.Identify:
if available, _ := ctx.client.identifyRateLimiter.Try(ctx.client.id); !available {
return ErrIdentifyRateLimited
}
}
packet := Payload{
Op: opc,
Data: payload,
}
data, err := encoding.Marshal(&packet)
if err != nil {
return fmt.Errorf("unable to marshal packet; %w", err)
}
_, err = pipe.Write(data)
return err
}
func (ctx *StateCtx) WriteNormalClose(pipe io.Writer) error {
ctx.SetState(&ClosedState{})
return ctx.writeClose(pipe, closecode.Normal)
}
func (ctx *StateCtx) WriteRestartClose(pipe io.Writer) error {
ctx.SetState(&ResumableClosedState{ctx})
return ctx.writeClose(pipe, closecode.Restarting)
}
func (ctx *StateCtx) writeClose(pipe io.Writer, code closecode.Type) error {
writeIfOpen := func() error {
if ctx.closed.CompareAndSwap(false, true) {
closeCodeBuf := make([]byte, 2)
binary.BigEndian.PutUint16(closeCodeBuf, uint16(code))
_, err := pipe.Write(closeCodeBuf)
return err
}
return net.ErrClosed
}
if err := writeIfOpen(); err != nil {
if !errors.Is(err, net.ErrClosed) && strings.Contains(err.Error(), "use of closed connection") {
return net.ErrClosed
}
return err
}
return nil
}