forked from weikaishio/ali_mns
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
280 lines (227 loc) · 7.18 KB
/
client.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
270
271
272
273
274
275
276
277
278
279
280
package ali_mns
import (
"bytes"
"crypto/md5"
"encoding/base64"
"encoding/xml"
"fmt"
"net/http"
neturl "net/url"
"os"
"strings"
"sync"
"time"
"github.com/gogap/errors"
"github.com/valyala/fasthttp"
)
const (
DefaultQueueQPSLimit int32 = 2000
DefaultTopicQPSLimit int32 = 2000
DefaultDNSTTL int32 = 10
)
const (
GLOBAL_PROXY = "MNS_GLOBAL_PROXY"
)
const (
version = "2015-06-06"
)
const (
DefaultTimeout int64 = 35
)
type Method string
var (
errMapping map[string]errors.ErrCodeTemplate
)
func init() {
initMNSErrors()
}
const (
GET Method = "GET"
PUT = "PUT"
POST = "POST"
DELETE = "DELETE"
)
type MNSClient interface {
Send(method Method, headers map[string]string, message interface{}, resource string) (*fasthttp.Response, error)
SetProxy(url string)
getAccountID() (accountId string)
getRegion() (region string)
}
type aliMNSClient struct {
Timeout int64
url *neturl.URL
credential Credential
accessKeyId string
client *fasthttp.Client
proxyURL string
accountId string
region string
clientLocker sync.Mutex
}
func NewAliMNSClient(inputUrl, accessKeyId, accessKeySecret string) MNSClient {
if inputUrl == "" {
panic("ali-mns: message queue url is empty")
}
credential := NewAliMNSCredential(accessKeySecret)
cli := new(aliMNSClient)
cli.credential = credential
cli.accessKeyId = accessKeyId
var err error
if cli.url, err = neturl.Parse(inputUrl); err != nil {
panic("err parse url")
}
// 1. parse region and accountid
pieces := strings.Split(inputUrl, ".")
if len(pieces) != 5 {
panic("ali-mns: message queue url is invalid")
}
accountIdSlice := strings.Split(pieces[0], "/")
cli.accountId = accountIdSlice[len(accountIdSlice)-1]
regionSlice := strings.Split(pieces[2], "-internal")
cli.region = regionSlice[0]
if globalurl := os.Getenv(GLOBAL_PROXY); globalurl != "" {
cli.proxyURL = globalurl
}
// 2. now init http client
cli.initFastHttpClient()
return cli
}
func (p aliMNSClient) getAccountID() (accountId string) {
return p.accountId
}
func (p aliMNSClient) getRegion() (region string) {
return p.region
}
func (p *aliMNSClient) SetProxy(url string) {
if url == p.proxyURL {
return
}
p.proxyURL = url
}
func (p *aliMNSClient) initFastHttpClient() {
p.clientLocker.Lock()
defer p.clientLocker.Unlock()
timeoutInt := DefaultTimeout
if p.Timeout > 0 {
timeoutInt = p.Timeout
}
timeout := time.Second * time.Duration(timeoutInt)
p.client = &fasthttp.Client{ReadTimeout: timeout, WriteTimeout: timeout}
}
func (p *aliMNSClient) proxy(req *http.Request) (*neturl.URL, error) {
if p.proxyURL != "" {
return neturl.Parse(p.proxyURL)
}
return nil, nil
}
func (p *aliMNSClient) authorization(method Method, headers map[string]string, resource string) (authHeader string, err error) {
if signature, e := p.credential.Signature(method, headers, resource); e != nil {
return "", e
} else {
authHeader = fmt.Sprintf("MNS %s:%s", p.accessKeyId, signature)
}
return
}
func (p *aliMNSClient) Send(method Method, headers map[string]string, message interface{}, resource string) (*fasthttp.Response, error) {
var xmlContent []byte
var err error
if message == nil {
xmlContent = []byte{}
} else {
switch m := message.(type) {
case []byte:
{
xmlContent = m
}
default:
if bXml, e := xml.Marshal(message); e != nil {
err = ERR_MARSHAL_MESSAGE_FAILED.New(errors.Params{"err": e})
return nil, err
} else {
xmlContent = bXml
}
}
}
xmlMD5 := md5.Sum(xmlContent)
strMd5 := fmt.Sprintf("%x", xmlMD5)
if headers == nil {
headers = make(map[string]string)
}
headers[MQ_VERSION] = version
headers[CONTENT_TYPE] = "application/xml"
headers[CONTENT_MD5] = base64.StdEncoding.EncodeToString([]byte(strMd5))
headers[DATE] = time.Now().UTC().Format(http.TimeFormat)
if authHeader, e := p.authorization(method, headers, fmt.Sprintf("/%s", resource)); e != nil {
err = ERR_GENERAL_AUTH_HEADER_FAILED.New(errors.Params{"err": e})
return nil, err
} else {
headers[AUTHORIZATION] = authHeader
}
var buffer bytes.Buffer
buffer.WriteString(p.url.String())
buffer.WriteString("/")
buffer.WriteString(resource)
url := buffer.String()
// 莫名的lock 加这个是为了啥 想不通。。 推拉模式 加lock 这是直接限流请求了
// p.clientLocker.Lock()
// defer p.clientLocker.Unlock()
req := fasthttp.AcquireRequest()
req.SetRequestURI(url)
req.Header.SetMethod(string(method))
req.SetBody(xmlContent)
for header, value := range headers {
req.Header.Set(header, value)
}
resp := fasthttp.AcquireResponse()
if err = p.client.Do(req, resp); err != nil {
err = ERR_SEND_REQUEST_FAILED.New(errors.Params{"err": err})
return nil, err
}
return resp, nil
}
func initMNSErrors() {
errMapping = map[string]errors.ErrCodeTemplate{
"AccessDenied": ERR_MNS_ACCESS_DENIED,
"InvalidAccessKeyId": ERR_MNS_INVALID_ACCESS_KEY_ID,
"InternalError": ERR_MNS_INTERNAL_ERROR,
"InvalidAuthorizationHeader": ERR_MNS_INVALID_AUTHORIZATION_HEADER,
"InvalidDateHeader": ERR_MNS_INVALID_DATE_HEADER,
"InvalidArgument": ERR_MNS_INVALID_ARGUMENT,
"InvalidDegist": ERR_MNS_INVALID_DEGIST,
"InvalidRequestURL": ERR_MNS_INVALID_REQUEST_URL,
"InvalidQueryString": ERR_MNS_INVALID_QUERY_STRING,
"MalformedXML": ERR_MNS_MALFORMED_XML,
"MissingAuthorizationHeader": ERR_MNS_MISSING_AUTHORIZATION_HEADER,
"MissingDateHeader": ERR_MNS_MISSING_DATE_HEADER,
"MissingVersionHeader": ERR_MNS_MISSING_VERSION_HEADER,
"MissingReceiptHandle": ERR_MNS_MISSING_RECEIPT_HANDLE,
"MissingVisibilityTimeout": ERR_MNS_MISSING_VISIBILITY_TIMEOUT,
"MessageNotExist": ERR_MNS_MESSAGE_NOT_EXIST,
"QueueAlreadyExist": ERR_MNS_QUEUE_ALREADY_EXIST,
"QueueDeletedRecently": ERR_MNS_QUEUE_DELETED_RECENTLY,
"InvalidQueueName": ERR_MNS_INVALID_QUEUE_NAME,
"QueueNameLengthError": ERR_MNS_QUEUE_NAME_LENGTH_ERROR,
"QueueNotExist": ERR_MNS_QUEUE_NOT_EXIST,
"ReceiptHandleError": ERR_MNS_RECEIPT_HANDLE_ERROR,
"SignatureDoesNotMatch": ERR_MNS_SIGNATURE_DOES_NOT_MATCH,
"TimeExpired": ERR_MNS_TIME_EXPIRED,
"QpsLimitExceeded": ERR_MNS_QPS_LIMIT_EXCEEDED,
"TopicAlreadyExist": ERR_MNS_TOPIC_ALREADY_EXIST,
"TopicNameLengthError": ERR_MNS_TOPIC_NAME_LENGTH_ERROR,
"TopicNotExist": ERR_MNS_TOPIC_NOT_EXIST,
"SubscriptionNameLengthError": ERR_MNS_SUBSRIPTION_NAME_LENGTH_ERROR,
"TopicNameInvalid": ERR_MNS_INVALID_TOPIC_NAME,
"SubsriptionNameInvalid": ERR_MNS_INVALID_SUBSCRIPTION_NAME,
"SubscriptionAlreadyExist": ERR_MNS_SUBSCRIPTION_ALREADY_EXIST,
"EndpointInvalid": ERR_MNS_INVALID_ENDPOINT,
"SubscriberNotExist": ERR_MNS_SUBSCRIBER_NOT_EXIST,
}
}
func ParseError(resp ErrorResponse, resource string) (err error) {
if errCodeTemplate, exist := errMapping[resp.Code]; exist {
err = errCodeTemplate.New(errors.Params{"resp": resp, "resource": resource})
} else {
err = ERR_MNS_UNKNOWN_CODE.New(errors.Params{"resp": resp, "resource": resource})
}
return
}