Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(browser): synchronize server-side and client-side time errors #1151

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 52 additions & 28 deletions lib/browser/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function Client(options, ctx) {
this.options = Client.initOptions(options);
}

this.options.cancelFlag = false;// cancel flag: if true need to be cancelled, default false
this.options.cancelFlag = false; // cancel flag: if true need to be cancelled, default false

// support custom agent and urllib client
if (this.options.urllib) {
Expand All @@ -57,7 +57,7 @@ function Client(options, ctx) {
this.stsTokenFreshTime = new Date();

// record the time difference between client and server
this.options.amendTimeSkewed = 0;
// this.amendTimeSkewed = 0;
}

/**
Expand All @@ -68,18 +68,22 @@ module.exports = Client;

Client.initOptions = function initOptions(options) {
if (!options.stsToken) {
console.warn('Please use STS Token for safety, see more details at https://help.aliyun.com/document_detail/32077.html');
console.warn(
'Please use STS Token for safety, see more details at https://help.aliyun.com/document_detail/32077.html'
);
}
const opts = Object.assign({
secure: isHttpsWebProtocol(),
// for browser compatibility disable fetch.
useFetch: false,
}, options);
const opts = Object.assign(
{
secure: isHttpsWebProtocol(),
// for browser compatibility disable fetch.
useFetch: false
},
options
);

return _initOptions(opts);
};


/**
* prototype
*/
Expand Down Expand Up @@ -179,7 +183,12 @@ proto.authorization = function authorization(method, resource, subres, headers)
parameters: subres
});

return signUtils.authorization(this.options.accessKeyId, this.options.accessKeySecret, stringToSign, this.options.headerEncoding);
return signUtils.authorization(
this.options.accessKeyId,
this.options.accessKeySecret,
stringToSign,
this.options.headerEncoding
);
};

/**
Expand All @@ -204,8 +213,8 @@ proto.authorization = function authorization(method, resource, subres, headers)
proto.request = async function (params) {
if (this.options.retryMax) {
return await retry(request.bind(this), this.options.retryMax, {
errorHandler: (err) => {
const _errHandle = (_err) => {
errorHandler: err => {
const _errHandle = _err => {
if (params.stream) return false;
const statusErr = [-1, -2].includes(_err.status);
const requestErrorRetryHandle = this.options.requestErrorRetryHandle || (() => true);
Expand Down Expand Up @@ -233,7 +242,14 @@ async function request(params) {
const useStream = !!params.stream;
try {
result = await this.urllib.request(reqParams.url, reqParams.params);
this.debug('response %s %s, got %s, headers: %j', params.method, reqParams.url, result.status, result.headers, 'info');
this.debug(
'response %s %s, got %s, headers: %j',
params.method,
reqParams.url,
result.status,
result.headers,
'info'
);
} catch (err) {
reqErr = err;
}
Expand All @@ -242,7 +258,7 @@ async function request(params) {
err = await this.requestError(result);
// not use stream
if (err.code === 'RequestTimeTooSkewed' && !useStream) {
this.options.amendTimeSkewed = +new Date(err.serverTime) - new Date();
this.setAmendTimeSkewed(+new Date(err.serverTime) - new Date());
return await this.request(params);
}
err.params = params;
Expand Down Expand Up @@ -282,7 +298,7 @@ proto._escape = function _escape(name) {
*/

proto._getUserAgent = function _getUserAgent() {
const agent = (process && process.browser) ? 'js' : 'nodejs';
const agent = process && process.browser ? 'js' : 'nodejs';
const sdk = `aliyun-sdk-${agent}/${pkg.version}`;
let plat = platform.description;
if (!plat && process) {
Expand All @@ -306,7 +322,7 @@ proto._checkUserAgent = function _checkUserAgent(ua) {
*/

proto.checkBrowserAndVersion = function checkBrowserAndVersion(name, version) {
return ((bowser.name === name) && (bowser.version.split('.')[0] === version));
return bowser.name === name && bowser.version.split('.')[0] === version;
};

/**
Expand All @@ -321,16 +337,20 @@ proto.parseXML = function parseXMLThunk(str) {
if (Buffer.isBuffer(str)) {
str = str.toString();
}
xml.parseString(str, {
explicitRoot: false,
explicitArray: false
}, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
xml.parseString(
str,
{
explicitRoot: false,
explicitArray: false
},
(err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
});
);
});
};

Expand All @@ -344,7 +364,8 @@ proto.parseXML = function parseXMLThunk(str) {
proto.requestError = async function requestError(result) {
let err = null;
if (!result.data || !result.data.length) {
if (result.status === -1 || result.status === -2) { // -1 is net error , -2 is timeout
if (result.status === -1 || result.status === -2) {
// -1 is net error , -2 is timeout
err = new Error(result.message);
err.name = result.name;
err.status = result.status;
Expand Down Expand Up @@ -375,7 +396,7 @@ proto.requestError = async function requestError(result) {

let info;
try {
info = await this.parseXML(message) || {};
info = (await this.parseXML(message)) || {};
} catch (error) {
this.debug(message, 'error');
error.message += `\nraw xml: ${message}`;
Expand All @@ -384,7 +405,7 @@ proto.requestError = async function requestError(result) {
return error;
}

let msg = info.Message || (`unknow request error, status: ${result.status}`);
let msg = info.Message || `unknow request error, status: ${result.status}`;
if (info.Condition) {
msg += ` (condition: ${info.Condition})`;
}
Expand All @@ -401,3 +422,6 @@ proto.requestError = async function requestError(result) {
return err;
};

proto.setAmendTimeSkewed = function (offset) {
proto.amendTimeSkewed = offset;
};
4 changes: 2 additions & 2 deletions lib/common/utils/createRequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ function delHeader(headers, name) {
}
function createRequest(params) {
let date = new Date();
if (this.options.amendTimeSkewed) {
date = +new Date() + this.options.amendTimeSkewed;
if (this.amendTimeSkewed) {
date = +new Date() + this.amendTimeSkewed;
}
const headers = {
'x-oss-date': dateFormat(date, "UTC:ddd, dd mmm yyyy HH:MM:ss 'GMT'")
Expand Down
4 changes: 2 additions & 2 deletions lib/common/utils/createRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ function delHeader(headers: Headers, name: string) {

export function createRequest(this: any, params) {
let date = new Date();
if (this.options.amendTimeSkewed) {
date = +new Date() + this.options.amendTimeSkewed;
if (this.amendTimeSkewed) {
date = +new Date() + this.amendTimeSkewed;
}
const headers: Headers = {
'x-oss-date': dateFormat(date, "UTC:ddd, dd mmm yyyy HH:MM:ss 'GMT'")
Expand Down
5 changes: 3 additions & 2 deletions test/browser/browser.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1990,8 +1990,9 @@ describe('browser', () => {
const resultPut = await store.put(name, file);
assert.equal(resultPut.res.status, 200);

assert.equal(requestSpy.callCount, 2);
assert.equal(requestErrorSpy.callCount, 1);
// 因为现在更改了时间偏移的实现,当第一实例矫正偏移后会保存所以这里现在只能为1,因为都矫正过了
assert.equal(requestSpy.callCount, 1);
assert.equal(requestErrorSpy.callCount, 0);

const resultGet = await store.get(name);
assert.equal(resultGet.res.status, 200);
Expand Down