fcs
2025-04-10 0163870d662dc5b7d69ceff977490ede594f7d82
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
'use strict';
 
var _regenerator = require('babel-runtime/regenerator');
 
var _regenerator2 = _interopRequireDefault(_regenerator);
 
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
 
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
var assert = require('assert');
 
var debug = require('debug')('mns:client');
var httpx = require('httpx');
var kitx = require('kitx');
 
var _require = require('./helper'),
    getEndpoint = _require.getEndpoint,
    toXMLBuffer = _require.toXMLBuffer,
    parseXML = _require.parseXML,
    extract = _require.extract,
    getResponseHeaders = _require.getResponseHeaders,
    getCanonicalizedMNSHeaders = _require.getCanonicalizedMNSHeaders;
 
var Client = function () {
  function Client(accountid, opts) {
    _classCallCheck(this, Client);
 
    assert(accountid, '"accountid" must be passed in');
    this.accountid = accountid;
    assert(opts, 'must pass in "opts"');
    // 兼容
    var accessKeyID = opts.accessKeyId || opts.accessKeyID;
    assert(accessKeyID, 'must pass in "opts.accessKeyID"');
    this.accessKeyID = accessKeyID;
    assert(opts.accessKeySecret, 'must pass in "opts.accessKeySecret"');
    this.accessKeySecret = opts.accessKeySecret;
    assert(opts.region, 'must pass in "opts.region"');
 
    var _getEndpoint = getEndpoint(accountid, opts),
        domain = _getEndpoint.domain,
        endpoint = _getEndpoint.endpoint;
 
    this.endpointDomain = domain;
    this.endpoint = endpoint;
 
    // security token
    this.securityToken = opts.securityToken;
  }
 
  _createClass(Client, [{
    key: 'request',
    value: function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee(method, resource, type, requestBody) {
        var attentions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];
        var opts = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
        var url, headers, response, code, contentType, responseBody, body, responseData, e, message, requestid, hostid, err;
        return _regenerator2.default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                url = `${this.endpoint}${resource}`;
 
                debug('url: %s', url);
                debug('method: %s', method);
                headers = this.buildHeaders(method, requestBody, resource, opts.headers);
 
                debug('request headers: %j', headers);
                debug('request body: %s', requestBody.toString());
                _context.next = 8;
                return httpx.request(url, Object.assign(opts, {
                  method: method,
                  headers: headers,
                  data: requestBody
                }));
 
              case 8:
                response = _context.sent;
 
 
                debug('statusCode %s', response.statusCode);
                debug('response headers: %j', response.headers);
                code = response.statusCode;
                contentType = response.headers['content-type'] || '';
                // const contentLength = response.headers['content-length'];
 
                _context.next = 15;
                return httpx.read(response, 'utf8');
 
              case 15:
                responseBody = _context.sent;
 
                debug('response body: %s', responseBody);
 
                if (!(responseBody && (contentType.startsWith('text/xml') || contentType.startsWith('application/xml')))) {
                  _context.next = 31;
                  break;
                }
 
                _context.next = 20;
                return parseXML(responseBody);
 
              case 20:
                responseData = _context.sent;
 
                if (!responseData.Error) {
                  _context.next = 29;
                  break;
                }
 
                e = responseData.Error;
                message = extract(e.Message);
                requestid = extract(e.RequestId);
                hostid = extract(e.HostId);
                err = new Error(`${method} ${url} failed with ${code}. ` + `requestid: ${requestid}, hostid: ${hostid}, message: ${message}`);
 
                err.name = 'MNS' + extract(e.Code) + err.name;
                throw err;
 
              case 29:
 
                body = {};
                Object.keys(responseData[type]).forEach(function (key) {
                  if (key !== '$') {
                    body[key] = extract(responseData[type][key]);
                  }
                });
 
              case 31:
                return _context.abrupt('return', {
                  code,
                  headers: getResponseHeaders(response.headers, attentions),
                  body: body
                });
 
              case 32:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this);
      }));
 
      function request(_x3, _x4, _x5, _x6) {
        return _ref.apply(this, arguments);
      }
 
      return request;
    }()
  }, {
    key: 'get',
    value: function get(resource, type, opts) {
      return this.request('GET', resource, type, '', [], opts);
    }
  }, {
    key: 'put',
    value: function put(resource, type, body) {
      var attentions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
      var opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
 
      return this.request('PUT', resource, type, body, attentions, opts);
    }
  }, {
    key: 'post',
    value: function post(resource, type, body) {
      return this.request('POST', resource, type, body);
    }
  }, {
    key: 'delete',
    value: function _delete(resource, type, body) {
      return this.request('DELETE', resource, type, body);
    }
  }, {
    key: 'sign',
    value: function sign(verb, headers, resource) {
      var canonicalizedMNSHeaders = getCanonicalizedMNSHeaders(headers);
      var md5 = headers['content-md5'] || '';
      var date = headers['date'];
      var type = headers['content-type'] || '';
 
      var toSignString = `${verb}\n${md5}\n${type}\n${date}\n${canonicalizedMNSHeaders}${resource}`;
      // Signature = base64(hmac-sha1(VERB + "\n"
      //             + CONTENT-MD5 + "\n"
      //             + CONTENT-TYPE + "\n"
      //             + DATE + "\n"
      //             + CanonicalizedMNSHeaders
      //             + CanonicalizedResource))
      var buff = Buffer.from(toSignString, 'utf8');
      var degist = kitx.sha1(buff, this.accessKeySecret, 'binary');
      return Buffer.from(degist, 'binary').toString('base64');
    }
  }, {
    key: 'buildHeaders',
    value: function buildHeaders(method, body, resource, customHeaders) {
      var date = new Date().toGMTString();
 
      var headers = {
        'date': date,
        'host': this.endpointDomain,
        'x-mns-date': date,
        'x-mns-version': '2015-06-06'
      };
 
      if (method !== 'GET' && method !== 'HEAD') {
        var contentType = 'text/xml';
        var digest = kitx.md5(body, 'hex');
        var md5 = Buffer.from(digest, 'utf8').toString('base64');
        Object.assign(headers, {
          'content-length': body.length,
          'content-type': contentType,
          'content-md5': md5
        });
      }
 
      Object.assign(headers, customHeaders);
 
      var signature = this.sign(method, headers, resource);
 
      headers['authorization'] = `MNS ${this.accessKeyID}:${signature}`;
 
      if (this.securityToken) {
        headers['security-token'] = this.securityToken;
      }
 
      return headers;
    }
 
    // Queue
 
  }, {
    key: 'createQueue',
    value: function createQueue(name) {
      var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
 
      var body = toXMLBuffer('Queue', params);
      var url = `/queues/${name}`;
      return this.put(url, 'Queue', body, ['location']);
    }
  }, {
    key: 'deleteQueue',
    value: function deleteQueue(name) {
      return this.delete(`/queues/${name}`, 'Queue', '');
    }
  }, {
    key: 'listQueue',
    value: function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee2(start, limit, prefix) {
        var customHeaders, subType, response;
        return _regenerator2.default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                customHeaders = {};
 
                if (typeof start !== 'undefined') {
                  customHeaders['x-mns-marker'] = start;
                }
 
                if (typeof limit !== 'undefined') {
                  customHeaders['x-mns-ret-number'] = limit;
                }
 
                if (typeof limit !== 'undefined') {
                  customHeaders['x-mns-prefix'] = prefix;
                }
 
                subType = 'Queue';
                _context2.next = 7;
                return this.get('/queues', 'Queues', {
                  headers: customHeaders
                });
 
              case 7:
                response = _context2.sent;
 
                response.body = response.body[subType];
                return _context2.abrupt('return', response);
 
              case 10:
              case 'end':
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));
 
      function listQueue(_x10, _x11, _x12) {
        return _ref2.apply(this, arguments);
      }
 
      return listQueue;
    }()
  }, {
    key: 'getQueueAttributes',
    value: function getQueueAttributes(queueName) {
      return this.get(`/queues/${queueName}`, 'Queue');
    }
  }, {
    key: 'setQueueAttributes',
    value: function setQueueAttributes(queueName) {
      var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
 
      var body = toXMLBuffer('Queue', params);
      var url = `/queues/${queueName}?metaoverride=true`;
      return this.put(url, 'Queue', body);
    }
 
    // Message
 
  }, {
    key: 'sendMessage',
    value: function sendMessage(queueName, params) {
      var url = `/queues/${queueName}/messages`;
      var body = toXMLBuffer('Message', params);
      return this.post(url, 'Message', body);
    }
  }, {
    key: 'batchSendMessage',
    value: function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee3(queueName, params) {
        var url, subType, body, response;
        return _regenerator2.default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                url = `/queues/${queueName}/messages`;
                subType = 'Message';
                body = toXMLBuffer('Messages', params, subType);
                _context3.next = 5;
                return this.post(url, 'Messages', body);
 
              case 5:
                response = _context3.sent;
 
                response.body = response.body[subType];
                return _context3.abrupt('return', response);
 
              case 8:
              case 'end':
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));
 
      function batchSendMessage(_x14, _x15) {
        return _ref3.apply(this, arguments);
      }
 
      return batchSendMessage;
    }()
  }, {
    key: 'receiveMessage',
    value: function receiveMessage(queueName, waitSeconds) {
      var url = `/queues/${queueName}/messages`;
      if (waitSeconds) {
        url += `?waitseconds=${waitSeconds}`;
      }
 
      // 31000 31s +1s max waitSeconds is 30s
      return this.get(url, 'Message', { timeout: 31000 });
    }
  }, {
    key: 'batchReceiveMessage',
    value: function () {
      var _ref4 = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee4(queueName, numOfMessages, waitSeconds) {
        var url, subType, response;
        return _regenerator2.default.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                url = `/queues/${queueName}/messages?numOfMessages=${numOfMessages}`;
 
                if (waitSeconds) {
                  url += `&waitseconds=${waitSeconds}`;
                }
 
                subType = 'Message';
                // 31000 31s +1s max waitSeconds is 30s
 
                _context4.next = 5;
                return this.get(url, 'Messages', { timeout: 31000 });
 
              case 5:
                response = _context4.sent;
 
                response.body = response.body[subType];
                return _context4.abrupt('return', response);
 
              case 8:
              case 'end':
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));
 
      function batchReceiveMessage(_x16, _x17, _x18) {
        return _ref4.apply(this, arguments);
      }
 
      return batchReceiveMessage;
    }()
  }, {
    key: 'peekMessage',
    value: function peekMessage(queueName) {
      return this.get(`/queues/${queueName}/messages?peekonly=true`, 'Message');
    }
  }, {
    key: 'batchPeekMessage',
    value: function () {
      var _ref5 = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee5(queueName, numOfMessages) {
        var url, subType, response;
        return _regenerator2.default.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                url = `/queues/${queueName}/messages?` + `peekonly=true&numOfMessages=${numOfMessages}`;
                subType = 'Message';
                // 31000 31s +1s max waitSeconds is 30s
 
                _context5.next = 4;
                return this.get(url, 'Messages');
 
              case 4:
                response = _context5.sent;
 
                response.body = response.body[subType];
                return _context5.abrupt('return', response);
 
              case 7:
              case 'end':
                return _context5.stop();
            }
          }
        }, _callee5, this);
      }));
 
      function batchPeekMessage(_x19, _x20) {
        return _ref5.apply(this, arguments);
      }
 
      return batchPeekMessage;
    }()
  }, {
    key: 'deleteMessage',
    value: function deleteMessage(queueName, receiptHandle) {
      var url = `/queues/${queueName}/messages?ReceiptHandle=${receiptHandle}`;
      return this.delete(url, 'Message', '');
    }
  }, {
    key: 'batchDeleteMessage',
    value: function () {
      var _ref6 = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee6(queueName, receiptHandles) {
        var body, url, response, subType;
        return _regenerator2.default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                body = toXMLBuffer('ReceiptHandles', receiptHandles, 'ReceiptHandle');
                url = `/queues/${queueName}/messages`;
                _context6.next = 4;
                return this.delete(url, 'Errors', body);
 
              case 4:
                response = _context6.sent;
 
                // 3种情况,普通失败,部分失败,全部成功
                if (response.body) {
                  subType = 'Error';
                  // 部分失败
 
                  response.body = response.body[subType];
                }
                return _context6.abrupt('return', response);
 
              case 7:
              case 'end':
                return _context6.stop();
            }
          }
        }, _callee6, this);
      }));
 
      function batchDeleteMessage(_x21, _x22) {
        return _ref6.apply(this, arguments);
      }
 
      return batchDeleteMessage;
    }()
  }, {
    key: 'changeMessageVisibility',
    value: function changeMessageVisibility(queueName, receiptHandle, visibilityTimeout) {
      var url = `/queues/${queueName}/messages?` + `receiptHandle=${receiptHandle}&visibilityTimeout=${visibilityTimeout}`;
      return this.put(url, 'ChangeVisibility', '');
    }
 
    // Topic
 
  }, {
    key: 'createTopic',
    value: function createTopic(name) {
      var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
 
      var body = toXMLBuffer('Topic', params);
      return this.put(`/topics/${name}`, 'Topic', body, ['location']);
    }
  }, {
    key: 'deleteTopic',
    value: function deleteTopic() {}
  }, {
    key: 'listTopic',
    value: function () {
      var _ref7 = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee7(start, limit, prefix) {
        var customHeaders, subType, response;
        return _regenerator2.default.wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                customHeaders = {};
 
                if (typeof start !== 'undefined') {
                  customHeaders['x-mns-marker'] = start;
                }
 
                if (typeof limit !== 'undefined') {
                  customHeaders['x-mns-ret-number'] = limit;
                }
 
                if (typeof limit !== 'undefined') {
                  customHeaders['x-mns-prefix'] = prefix;
                }
 
                subType = 'Topic';
                _context7.next = 7;
                return this.get('/topics', 'Topics', {
                  headers: customHeaders
                });
 
              case 7:
                response = _context7.sent;
 
                response.body = response.body[subType];
                return _context7.abrupt('return', response);
 
              case 10:
              case 'end':
                return _context7.stop();
            }
          }
        }, _callee7, this);
      }));
 
      function listTopic(_x24, _x25, _x26) {
        return _ref7.apply(this, arguments);
      }
 
      return listTopic;
    }()
  }, {
    key: 'getTopicAttributes',
    value: function getTopicAttributes(name) {
      return this.get(`/topics/${name}`, 'Topic');
    }
  }, {
    key: 'setTopicAttributes',
    value: function setTopicAttributes(name) {
      var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
 
      var body = toXMLBuffer('Topic', params);
      var url = `/topics/${name}?metaoverride=true`;
      return this.put(url, 'Topic', body);
    }
 
    // Subscription
 
  }, {
    key: 'subscribe',
    value: function subscribe() {}
  }, {
    key: 'unsubscribe',
    value: function unsubscribe() {}
  }, {
    key: 'listSubscriptionByTopic',
    value: function listSubscriptionByTopic() {}
  }, {
    key: 'getSubscriptionAttributes',
    value: function getSubscriptionAttributes() {}
  }, {
    key: 'setSubscriptionAttributes',
    value: function setSubscriptionAttributes() {}
 
    // Message
 
  }, {
    key: 'publishMessage',
    value: function publishMessage(topic, params) {
      var url = `/topics/${topic}/messages`;
      var body = toXMLBuffer('Message', params);
      return this.post(url, 'Message', body);
    }
 
    // Notifications
 
  }, {
    key: 'httpEndpoint',
    value: function httpEndpoint() {}
  }]);
 
  return Client;
}();
 
module.exports = Client;