-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
251 lines (212 loc) · 5.84 KB
/
client.go
File metadata and controls
251 lines (212 loc) · 5.84 KB
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
package httpsqs
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/gomooth/xerror"
)
type client struct {
config *Config
httpClient *http.Client
}
func NewClient(config *Config) IClient {
timeout := config.Timeout
if timeout <= 0 {
timeout = 5 * time.Second
}
return &client{
config: config,
httpClient: &http.Client{
Timeout: timeout,
Transport: &http.Transport{
MaxIdleConnsPerHost: 2,
IdleConnTimeout: 90 * time.Second,
},
},
}
}
func (c *client) Put(ctx context.Context, name, data string) (int64, error) {
values := url.Values{}
values.Set("name", name)
values.Set("opt", "put")
values.Set("data", data)
body, headers, err := c.httpGet(ctx, values, []string{"pos"})
if err != nil {
return 0, xerror.Wrap(err, "httpsqs put failed")
}
switch body {
case "HTTPSQS_PUT_OK":
pos, _ := strconv.Atoi(headers["pos"])
return int64(pos), nil
case "HTTPSQS_PUT_ERROR":
return 0, xerror.New("httpsqs put err")
case "HTTPSQS_PUT_END":
return -1, xerror.New("httpsqs is full")
default:
return 0, xerror.Errorf("httpsqs put failed: %s", body)
}
}
func (c *client) Get(ctx context.Context, name string) (string, int64, error) {
values := url.Values{}
values.Set("name", name)
values.Set("opt", "get")
body, headers, err := c.httpGet(ctx, values, []string{"pos"})
if err != nil {
return "", 0, xerror.Wrap(err, "httpsqs get failed")
}
switch body {
case "HTTPSQS_GET_END": // 没有未取出的消息队列
return "", -1, nil
default:
pos, _ := strconv.Atoi(headers["pos"])
return body, int64(pos), nil
}
}
func (c *client) Status(ctx context.Context, name string) (*Status, error) {
values := url.Values{}
values.Set("name", name)
values.Set("opt", "status_json")
body, _, err := c.httpGet(ctx, values, nil)
if err != nil {
return nil, xerror.Wrap(err, "httpsqs status failed")
}
var res Status
if err := json.Unmarshal([]byte(body), &res); nil != err {
return nil, xerror.Wrapf(err, "httpsqs status failed: response not json: %s", body)
}
return &res, nil
}
func (c *client) View(ctx context.Context, name string, pos int64) (string, error) {
if pos <= 0 || pos > 1000000000 {
return "", xerror.New("input pos error")
}
values := url.Values{}
values.Set("name", name)
values.Set("opt", "view")
values.Set("pos", strconv.Itoa(int(pos)))
body, _, err := c.httpGet(ctx, values, nil)
if err != nil {
return "", xerror.Wrap(err, "httpsqs view failed")
}
return body, nil
}
func (c *client) Reset(ctx context.Context, name string) error {
values := url.Values{}
values.Set("name", name)
values.Set("opt", "reset")
body, _, err := c.httpGet(ctx, values, nil)
if err != nil {
return xerror.Wrap(err, "httpsqs reset failed")
}
switch body {
case "HTTPSQS_RESET_OK":
return nil
default:
return xerror.Errorf("httpsqs reset failed: %s", body)
}
}
func (c *client) SetMaxQueue(ctx context.Context, name string, max int) error {
values := url.Values{}
values.Set("name", name)
values.Set("opt", "maxqueue")
values.Set("num", strconv.Itoa(max))
body, _, err := c.httpGet(ctx, values, nil)
if err != nil {
return xerror.Wrap(err, "httpsqs set max_queue failed")
}
switch body {
case "HTTPSQS_MAXQUEUE_OK":
return nil
case "HTTPSQS_MAXQUEUE_CANCEL":
return xerror.New("httpsqs option cancel")
default:
return xerror.Errorf("httpsqs set max_queue failed: %s", body)
}
}
func (c *client) SetSyncTime(ctx context.Context, name string, duration time.Duration) error {
num := int(duration.Seconds())
if num < 1 || num > 1000000000 {
return xerror.New("input num error")
}
values := url.Values{}
values.Set("name", name)
values.Set("opt", "synctime")
values.Set("num", strconv.Itoa(num))
body, _, err := c.httpGet(ctx, values, nil)
if err != nil {
return xerror.Wrap(err, "httpsqs set sync_time failed")
}
switch body {
case "HTTPSQS_SYNCTIME_OK":
return nil
case "HTTPSQS_SYNCTIME_CANCEL":
return xerror.New("httpsqs option cancel")
default:
return xerror.Errorf("httpsqs set synctime failed: %s", body)
}
}
func (c *client) httpGet(ctx context.Context, values url.Values, parseHeaders []string) (string, map[string]string, error) {
furl := fmt.Sprintf("http://%s/", c.config.Addr)
if len(c.config.Password) > 0 {
values.Set("auth", c.config.Password)
}
var lastErr error
maxAttempts := c.config.MaxRetries + 1
for attempt := 0; attempt < maxAttempts; attempt++ {
if attempt > 0 {
if err := c.waitBackoff(ctx, attempt); err != nil {
return "", nil, err
}
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, furl, nil)
if err != nil {
return "", nil, err
}
req.URL.RawQuery = values.Encode()
resp, err := c.httpClient.Do(req)
if err != nil {
lastErr = err
continue
}
return c.processResponse(resp, parseHeaders)
}
return "", nil, xerror.Wrap(lastErr, "httpsqs request failed after retries")
}
func (c *client) processResponse(resp *http.Response, parseHeaders []string) (string, map[string]string, error) {
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", nil, err
}
body := strings.TrimSpace(string(bodyBytes))
switch body {
case "HTTPSQS_ERROR": // 全局错误
return "", nil, xerror.New("httpsqs global error")
case "HTTPSQS_AUTH_FAILED": // 密码校验失败
return "", nil, xerror.New("httpsqs auth error")
default:
headerResult := make(map[string]string)
for _, header := range parseHeaders {
headerResult[header] = strings.TrimSpace(resp.Header.Get(header))
}
return body, headerResult, nil
}
}
func (c *client) waitBackoff(ctx context.Context, attempt int) error {
backoff := time.Duration(1<<uint(min(attempt-1, 24))) * 200 * time.Millisecond
if backoff > 5*time.Second {
backoff = 5 * time.Second
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(backoff):
return nil
}
}