-
Notifications
You must be signed in to change notification settings - Fork 13
/
blaze.go
269 lines (224 loc) · 6.18 KB
/
blaze.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package mixin
import (
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
"github.com/gorilla/websocket"
)
const (
writeWait = 10 * time.Second
pongWait = 10 * time.Second
pingPeriod = pongWait * 8 / 10
ackBatch = 80
CreateMessageAction = "CREATE_MESSAGE"
AcknowledgeReceiptAction = "ACKNOWLEDGE_MESSAGE_RECEIPT"
)
type BlazeMessage struct {
Id string `json:"id"`
Action string `json:"action"`
Params map[string]interface{} `json:"params,omitempty"`
Data json.RawMessage `json:"data,omitempty"`
Error *Error `json:"error,omitempty"`
}
type MessageView struct {
ConversationID string `json:"conversation_id"`
UserID string `json:"user_id"`
MessageID string `json:"message_id"`
Category string `json:"category"`
Data string `json:"data"`
RepresentativeID string `json:"representative_id"`
QuoteMessageID string `json:"quote_message_id"`
Status string `json:"status"`
Source string `json:"source"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// ack status
ack bool
}
func (m *MessageView) reset() {
m.ack = false
m.RepresentativeID = ""
m.QuoteMessageID = ""
}
// Ack mark messageView as acked
// otherwise sdk will ack this message
func (m *MessageView) Ack() {
m.ack = true
}
type TransferView struct {
Type string `json:"type"`
SnapshotID string `json:"snapshot_id"`
CounterUserID string `json:"counter_user_id"`
AssetID string `json:"asset_id"`
Amount string `json:"amount"`
TraceID string `json:"trace_id"`
Memo string `json:"memo"`
CreatedAt time.Time `json:"created_at"`
}
type SystemConversationPayload struct {
Action string `json:"action"`
ParticipantID string `json:"participant_id"`
UserID string `json:"user_id,omitempty"`
Role string `json:"role,omitempty"`
}
type BlazeListener interface {
OnAckReceipt(ctx context.Context, msg *MessageView, userID string) error
OnMessage(ctx context.Context, msg *MessageView, userID string) error
}
func (c *Client) LoopBlaze(ctx context.Context, listener BlazeListener) error {
conn, err := connectMixinBlaze(c)
if err != nil {
return err
}
defer conn.Close()
b := &blazeHandler{
Client: c,
conn: conn,
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
go tick(ctx, conn)
ackBuffer := make(chan string)
defer close(ackBuffer)
go b.ack(ctx, ackBuffer)
_ = b.SetReadDeadline(time.Now().Add(pongWait))
conn.SetPongHandler(func(string) error {
return b.SetReadDeadline(time.Now().Add(pongWait))
})
if err = writeMessage(conn, "LIST_PENDING_MESSAGES", nil); err != nil {
return fmt.Errorf("write LIST_PENDING_MESSAGES failed: %w", err)
}
var (
blazeMessage BlazeMessage
message MessageView
)
for {
typ, r, err := conn.NextReader()
if err != nil {
return err
}
if typ != websocket.BinaryMessage {
return fmt.Errorf("invalid message type %d", typ)
}
if err := parseBlazeMessage(r, &blazeMessage); err != nil {
return err
}
if blazeMessage.Error != nil {
return err
}
message.reset()
if err := json.Unmarshal(blazeMessage.Data, &message); err != nil {
continue
}
switch blazeMessage.Action {
case CreateMessageAction:
messageID := message.MessageID
if err := listener.OnMessage(ctx, &message, b.ClientID); err != nil {
return err
}
if !message.ack {
ackBuffer <- messageID
}
case AcknowledgeReceiptAction:
if err := listener.OnAckReceipt(ctx, &message, b.ClientID); err != nil {
return err
}
}
if time.Until(b.readDeadline) < time.Second {
// 可能因为收到的消息过多或者消息处理太慢或者 ack 太慢
// 导致没有及时处理 pong frame 而 read deadline 没有刷新
// 这种情况下不应该读超时,在这里重置一下 read deadline
_ = b.SetReadDeadline(time.Now().Add(pongWait))
}
}
}
func connectMixinBlaze(s Signer) (*websocket.Conn, error) {
sig := SignRaw("GET", "/", nil)
token := s.SignToken(sig, newRequestID(), time.Minute)
header := make(http.Header)
header.Add("Authorization", "Bearer "+token)
u := url.URL{Scheme: "wss", Host: blazeHost, Path: "/"}
dialer := &websocket.Dialer{
Subprotocols: []string{"Mixin-Blaze-1"},
ReadBufferSize: 1024,
}
conn, _, err := dialer.Dial(u.String(), header)
if err != nil {
return nil, err
}
// no limit
conn.SetReadLimit(0)
return conn, nil
}
func tick(ctx context.Context, conn *websocket.Conn) {
ticker := time.NewTicker(pingPeriod)
defer func() {
conn.Close()
ticker.Stop()
}()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(writeWait)); err != nil {
return
}
}
}
}
func writeMessage(coon *websocket.Conn, action string, params map[string]interface{}) error {
blazeMessage, err := json.Marshal(BlazeMessage{
Id: newUUID(),
Action: action,
Params: params,
})
if err != nil {
return err
}
if err := writeGzipToConn(coon, blazeMessage); err != nil {
return err
}
return nil
}
func writeGzipToConn(conn *websocket.Conn, msg []byte) error {
if err := conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil {
return err
}
wsWriter, err := conn.NextWriter(websocket.BinaryMessage)
if err != nil {
return err
}
gzWriter, err := gzip.NewWriterLevel(wsWriter, 3)
if err != nil {
return err
}
if _, err := gzWriter.Write(msg); err != nil {
return err
}
if err := gzWriter.Close(); err != nil {
return err
}
return wsWriter.Close()
}
func parseBlazeMessage(r io.Reader, msg *BlazeMessage) error {
gzReader, err := gzip.NewReader(r)
if err != nil {
return err
}
err = json.NewDecoder(gzReader).Decode(msg)
_ = gzReader.Close()
return err
}
type BlazeListenFunc func(ctx context.Context, msg *MessageView, userID string) error
func (f BlazeListenFunc) OnAckReceipt(ctx context.Context, msg *MessageView, userID string) error {
return nil
}
func (f BlazeListenFunc) OnMessage(ctx context.Context, msg *MessageView, userID string) error {
return f(ctx, msg, userID)
}