schangxiang@126.com
2025-09-19 0821aa23eabe557c0d9ef5dbe6989c68be35d1fe
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
 
const Base = require('sdk-base');
const util = require('util');
const ready = require('get-ready');
const copy = require('copy-to');
const currentIP = require('address').ip();
 
const RR = 'roundRobin';
const MS = 'masterSlave';
 
module.exports = function (OssClient) {
  function Client(options) {
    if (!(this instanceof Client)) {
      return new Client(options);
    }
 
    if (!options || !Array.isArray(options.cluster)) {
      throw new Error('require options.cluster to be an array');
    }
 
    Base.call(this);
 
    this.clients = [];
    this.availables = {};
 
    for (let i = 0; i < options.cluster.length; i++) {
      const opt = options.cluster[i];
      copy(options).pick('timeout', 'agent', 'urllib').to(opt);
      this.clients.push(new OssClient(opt));
      this.availables[i] = true;
    }
 
    this.schedule = options.schedule || RR;
    this.index = 0;
 
    const heartbeatInterval = options.heartbeatInterval || 10000;
    this._checkAvailableLock = false;
    this._timerId = this._deferInterval(this._checkAvailable.bind(this, true), heartbeatInterval);
    this._ignoreStatusFile = options.ignoreStatusFile || false;
    this._init();
  }
 
  util.inherits(Client, Base);
  const proto = Client.prototype;
  ready.mixin(proto);
 
  const GET_METHODS = [
    'head',
    'get',
    'getStream',
    'list',
    'getACL'
  ];
 
  const PUT_METHODS = [
    'put',
    'putStream',
    'delete',
    'deleteMulti',
    'copy',
    'putMeta',
    'putACL'
  ];
 
  GET_METHODS.forEach((method) => {
    proto[method] = async function (...args) {
      const client = this.chooseAvailable();
      let lastError;
      try {
        return await client[method](...args);
      } catch (err) {
        if (err.status && err.status >= 200 && err.status < 500) {
          // 200 ~ 499 belong to normal response, don't try again
          throw err;
        }
        // < 200 || >= 500 need to retry from other cluser node
        lastError = err;
      }
 
      for (let i = 0; i < this.clients.length; i++) {
        const c = this.clients[i];
        if (c !== client) {
          try {
            return await c[method].apply(client, args);
          } catch (err) {
            if (err.status && err.status >= 200 && err.status < 500) {
              // 200 ~ 499 belong to normal response, don't try again
              throw err;
            }
            // < 200 || >= 500 need to retry from other cluser node
            lastError = err;
          }
        }
      }
 
      lastError.message += ' (all clients are down)';
      throw lastError;
    };
  });
 
  // must cluster node write success
  PUT_METHODS.forEach((method) => {
    proto[method] = async function (...args) {
      const res = await Promise.all(this.clients.map(client => client[method](...args)));
      return res[0];
    };
  });
 
  proto.signatureUrl = function signatureUrl(/* name */...args) {
    const client = this.chooseAvailable();
    return client.signatureUrl(...args);
  };
 
  proto.getObjectUrl = function getObjectUrl(/* name, baseUrl */...args) {
    const client = this.chooseAvailable();
    return client.getObjectUrl(...args);
  };
 
  proto._init = function _init() {
    const that = this;
    (async () => {
      await that._checkAvailable(that._ignoreStatusFile);
      that.ready(true);
    })().catch((err) => {
      that.emit('error', err);
    });
  };
 
  proto._checkAvailable = async function _checkAvailable(ignoreStatusFile) {
    const name = `._ali-oss/check.status.${currentIP}.txt`;
    if (!ignoreStatusFile) {
      // only start will try to write the file
      await this.put(name, new Buffer(`check available started at ${Date()}`));
    }
 
    if (this._checkAvailableLock) {
      return;
    }
    this._checkAvailableLock = true;
    const downStatusFiles = [];
    for (let i = 0; i < this.clients.length; i++) {
      const client = this.clients[i];
      // check 3 times
      let available = await this._checkStatus(client, name);
      if (!available) {
        // check again
        available = await this._checkStatus(client, name);
      }
      if (!available) {
        // check again
        /* eslint no-await-in-loop: [0] */
        available = await this._checkStatus(client, name);
        if (!available) {
          downStatusFiles.push(client._objectUrl(name));
        }
      }
      this.availables[i] = available;
    }
    this._checkAvailableLock = false;
 
    if (downStatusFiles.length > 0) {
      const err = new Error(`${downStatusFiles.length} data node down, please check status file: ${downStatusFiles.join(', ')}`);
      err.name = 'CheckAvailableError';
      this.emit('error', err);
    }
  };
 
  proto._checkStatus = async function _checkStatus(client, name) {
    let available = true;
    try {
      await client.head(name);
    } catch (err) {
      // 404 will be available too
      if (!err.status || err.status >= 500 || err.status < 200) {
        available = false;
      }
    }
    return available;
  };
 
  proto.chooseAvailable = function chooseAvailable() {
    if (this.schedule === MS) {
      for (let i = 0; i < this.clients.length; i++) {
        if (this.availables[i]) {
          return this.clients[i];
        }
      }
      // all down, try to use this first one
      return this.clients[0];
    }
 
    // RR
    let n = this.clients.length;
    while (n > 0) {
      const i = this._nextRRIndex();
      if (this.availables[i]) {
        return this.clients[i];
      }
      n--;
    }
    // all down, try to use this first one
    return this.clients[0];
  };
 
  proto._nextRRIndex = function _nextRRIndex() {
    const index = this.index++;
    if (this.index >= this.clients.length) {
      this.index = 0;
    }
    return index;
  };
 
  proto._error = function error(err) {
    if (err) throw err;
  };
 
  proto._createCallback = function _createCallback(ctx, gen, cb) {
    return () => {
      cb = cb || this._error;
      gen.call(ctx).then(() => {
        cb();
      }, cb);
    };
  };
  proto._deferInterval = function _deferInterval(gen, timeout, cb) {
    return setInterval(this._createCallback(this, gen, cb), timeout);
  };
 
  proto.close = function close() {
    clearInterval(this._timerId);
    this._timerId = null;
  };
 
  return Client;
};