-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
190 lines (139 loc) · 3.62 KB
/
response.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
package sdbc
import (
"context"
"errors"
"fmt"
"io"
"time"
"nhooyr.io/websocket"
)
const (
logArgID = "id"
)
func (c *Client) subscribe() {
resChan := make(resultChannel[[]byte])
c.waitGroup.Add(1)
go func(resChan resultChannel[[]byte]) {
defer c.waitGroup.Done()
defer close(resChan)
for {
buf, err := c.read(c.connCtx)
if err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return
}
if errors.Is(err, io.EOF) || websocket.CloseStatus(err) != -1 {
c.logger.Info("Websocket closed.")
return
}
c.logger.Error("Could not read from websocket.", "error", err)
continue
}
resChan <- result(buf, nil)
}
}(resChan)
c.handleMessages(resChan)
}
// read reads a single websocket message.
// It will reuse buffers in between calls to avoid allocations.
func (c *Client) read(ctx context.Context) ([]byte, error) {
var err error
defer c.checkWebsocketConn(err)
msgType, reader, err := c.conn.Reader(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get reader: %w", err)
}
if msgType != websocket.MessageText {
return nil, fmt.Errorf("%w, got %v", ErrExpectedTextMessage, msgType)
}
buff := c.buffers.Get()
defer c.buffers.Put(buff)
if _, err = buff.ReadFrom(reader); err != nil {
return nil, fmt.Errorf("failed to read message: %w", err)
}
return buff.Bytes(), nil
}
func (c *Client) handleMessages(resultCh resultChannel[[]byte]) {
for {
select {
case <-c.connCtx.Done():
{
c.logger.DebugContext(c.connCtx, "Context done. Stopping message handler.")
return
}
case result, more := <-resultCh:
{
if !more {
c.logger.DebugContext(c.connCtx, "Result channel closed. Stopping message handler.")
return
}
c.waitGroup.Add(1)
go func() {
defer c.waitGroup.Done()
data, err := result()
if err != nil {
c.logger.ErrorContext(c.connCtx, "Could not get result from channel.", "error", err)
return
}
c.handleMessage(data)
}()
}
}
}
}
func (c *Client) handleMessage(data []byte) {
var res *response
if err := c.jsonUnmarshal(data, &res); err != nil {
c.logger.ErrorContext(c.connCtx, "Could not unmarshal websocket message.", "error", err)
return
}
c.logger.DebugContext(c.connCtx, "Received message.",
"id", res.ID,
"result", string(res.Result),
"error", res.Error,
)
if res.ID == "" {
c.handleLiveQuery(res)
return
}
c.handleResult(res)
}
func (c *Client) handleResult(res *response) {
outCh, ok := c.requests.get(res.ID)
if !ok {
c.logger.ErrorContext(c.connCtx, "Could not find pending request for ID.", logArgID, res.ID)
return
}
var err error
if res.Error != nil {
err = fmt.Errorf("%w: (%d) %s", ErrResultWithError, res.Error.Code, res.Error.Message)
}
select {
case outCh <- &output{data: res.Result, err: err}:
return
case <-c.connCtx.Done():
return
case <-time.After(c.timeout):
c.logger.ErrorContext(c.connCtx, "Timeout while sending result to channel.", logArgID, res.ID)
}
}
func (c *Client) handleLiveQuery(res *response) {
var rawID liveQueryID
if err := c.jsonUnmarshal(res.Result, &rawID); err != nil {
c.logger.ErrorContext(c.connCtx, "Could not unmarshal websocket message.", "error", err)
return
}
outCh, ok := c.liveQueries.get(rawID.ID, false)
if !ok {
c.logger.ErrorContext(c.connCtx, "Could not find live query channel.", logArgID, rawID.ID)
return
}
select {
case outCh <- res.Result:
return
case <-c.connCtx.Done():
return
case <-time.After(c.timeout):
c.logger.ErrorContext(c.connCtx, "Timeout while sending result to channel.", logArgID, res.ID)
}
}