cshenfu
2024-06-27 58aa6e282bb343503be3cb198948328ea3ed7b79
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
'use strict';
 
const assert = require('assert');
 
const httpx = require('httpx');
const kitx = require('kitx');
const JSON = require('json-bigint');
 
const helper = require('./helper');
 
function firstLetterUpper(str) {
  return str.slice(0, 1).toUpperCase() + str.slice(1);
}
 
function formatParams(params) {
  var keys = Object.keys(params);
  var newParams = {};
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    newParams[firstLetterUpper(key)] = params[key];
  }
  return newParams;
}
 
 
function timestamp() {
  var date = new Date();
  var YYYY = date.getUTCFullYear();
  var MM = kitx.pad2(date.getUTCMonth() + 1);
  var DD = kitx.pad2(date.getUTCDate());
  var HH = kitx.pad2(date.getUTCHours());
  var mm = kitx.pad2(date.getUTCMinutes());
  var ss = kitx.pad2(date.getUTCSeconds());
  // 删除掉毫秒部分
  return `${YYYY}-${MM}-${DD}T${HH}:${mm}:${ss}Z`;
}
 
function encode(str) {
  var result = encodeURIComponent(str);
 
  return result.replace(/!/g, '%21')
    .replace(/'/g, '%27')
    .replace(/\(/g, '%28')
    .replace(/\)/g, '%29')
    .replace(/\*/g, '%2A');
}
 
function replaceRepeatList(target, key, repeat) {
  for (var i = 0; i < repeat.length; i++) {
    var item = repeat[i];
 
    if (Array.isArray(item)) {
      replaceRepeatList(target, `${key}.${i + 1}`, item);
    } else if (item && typeof item === 'object') {
      const keys = Object.keys(item);
      for (var j = 0; j < keys.length; j++) {
        if (Array.isArray(item[keys[j]])) {
          replaceRepeatList(target, `${key}.${i + 1}.${keys[j]}`, item[keys[j]]);
        } else {
          target[`${key}.${i + 1}.${keys[j]}`] = item[keys[j]];
        }
      }
    } else {
      target[`${key}.${i + 1}`] = item;
    }
  }
}
 
function flatParams(params) {
  var target = {};
  var keys = Object.keys(params);
  for (let i = 0; i < keys.length; i++) {
    var key = keys[i];
    var value = params[key];
    if (Array.isArray(value)) {
      replaceRepeatList(target, key, value);
    } else {
      target[key] = value;
    }
  }
  return target;
}
 
function normalize(params) {
  var list = [];
  var flated = flatParams(params);
  var keys = Object.keys(flated).sort();
  for (let i = 0; i < keys.length; i++) {
    var key = keys[i];
    var value = flated[key];
    list.push([encode(key), encode(value)]); //push []
  }
  return list;
}
 
function canonicalize(normalized) {
  var fields = [];
  for (var i = 0; i < normalized.length; i++) {
    var [key, value] = normalized[i];
    fields.push(key + '=' + value);
  }
  return fields.join('&');
}
 
class RPCClient {
  constructor(config, verbose) {
    assert(config, 'must pass "config"');
    assert(config.endpoint, 'must pass "config.endpoint"');
    if (!config.endpoint.startsWith('https://') &&
      !config.endpoint.startsWith('http://')) {
      throw new Error(`"config.endpoint" must starts with 'https://' or 'http://'.`);
    }
    assert(config.apiVersion, 'must pass "config.apiVersion"');
    assert(config.accessKeyId, 'must pass "config.accessKeyId"');
    var accessKeySecret = config.secretAccessKey || config.accessKeySecret;
    assert(accessKeySecret, 'must pass "config.accessKeySecret"');
 
    if (config.endpoint.endsWith('/')) {
      config.endpoint = config.endpoint.slice(0, -1);
    }
 
    this.endpoint = config.endpoint;
    this.apiVersion = config.apiVersion;
    this.accessKeyId = config.accessKeyId;
    this.accessKeySecret = accessKeySecret;
    this.securityToken = config.securityToken;
    this.verbose = verbose === true;
    // 非 codes 里的值,将抛出异常
    this.codes = new Set([200, '200', 'OK', 'Success', 'success']);
    if (config.codes) {
      // 合并 codes
      for (var elem of config.codes) {
        this.codes.add(elem);
      }
    }
 
    this.opts = config.opts || {};
 
    var httpModule = this.endpoint.startsWith('https://')
      ? require('https') : require('http');
    this.keepAliveAgent = new httpModule.Agent({
      keepAlive: true,
      keepAliveMsecs: 3000
    });
  }
 
  async request(action, params = {}, opts = {}) {
    // 1. compose params and opts
    opts = Object.assign({
      headers: {
        'x-sdk-client': helper.DEFAULT_CLIENT,
        'user-agent': helper.DEFAULT_UA,
        'x-acs-action': action,
        'x-acs-version': this.apiVersion
      }
    }, this.opts, opts);
 
    // format action until formatAction is false
    if (opts.formatAction !== false) {
      action = firstLetterUpper(action);
    }
 
    // format params until formatParams is false
    if (opts.formatParams !== false) {
      params = formatParams(params);
    }
    const defaults = this._buildParams();
    params = Object.assign({Action: action}, defaults, params);
 
    // 2. caculate signature
    const method = (opts.method || 'GET').toUpperCase();
    const normalized = normalize(params);
    const canonicalized = canonicalize(normalized);
    // 2.1 get string to sign
    const stringToSign = `${method}&${encode('/')}&${encode(canonicalized)}`;
    // 2.2 get signature
    const key = this.accessKeySecret + '&';
    const signature = kitx.sha1(stringToSign, key, 'base64');
    // add signature
    normalized.push(['Signature', encode(signature)]);
    // 3. generate final url
    const url = opts.method === 'POST' ? `${this.endpoint}/` : `${this.endpoint}/?${canonicalize(normalized)}`;
    // 4. send request
    const entry = {
      url: url,
      request: null,
      response: null
    };
 
    if (opts && !opts.agent) {
      opts.agent = this.keepAliveAgent;
    }
 
    if (opts.method === 'POST') {
      opts.headers = opts.headers || {};
      opts.headers['content-type'] = 'application/x-www-form-urlencoded';
      opts.data = canonicalize(normalized);
    }
 
    const response = await httpx.request(url, opts);
    entry.request = {
      headers: response.req.getHeaders ? response.req.getHeaders() : response.req._headers
    };
    entry.response = {
      statusCode: response.statusCode,
      headers: response.headers
    };
 
    const buffer = await httpx.read(response);
    const json = JSON.parse(buffer);
    if (json.Code && !this.codes.has(json.Code)) {
      const err = new Error(`${json.Message}, URL: ${url}`);
      err.name = json.Code + 'Error';
      err.data = json;
      err.code = json.Code;
      err.url = url;
      err.entry = entry;
      throw err;
    }
 
    if (this.verbose) {
      return [json, entry];
    }
 
    return json;
  }
 
  _buildParams() {
    const defaultParams = {
      Format: 'JSON',
      SignatureMethod: 'HMAC-SHA1',
      SignatureNonce: kitx.makeNonce(),
      SignatureVersion: '1.0',
      Timestamp: timestamp(),
      AccessKeyId: this.accessKeyId,
      Version: this.apiVersion,
    };
    if (this.securityToken) {
      defaultParams.SecurityToken = this.securityToken;
    }
    return defaultParams;
  }
}
 
module.exports = RPCClient;