Commit 03edaf12 by liimin

refactor(core): 重构请求处理和签名逻辑,优化错误处理流程

- 重构请求分发逻辑,拆分重复提交检查和签名处理为独立方法
- 优化签名处理流程,分离参数处理和签名生成逻辑
- 移除冗余的错误事件触发代码,统一在适配器层处理
- 改进超时处理机制,确保资源正确释放
- 添加类型定义SignatureHeaders用于签名请求头
1 parent 79bd0232
...@@ -88,6 +88,7 @@ ...@@ -88,6 +88,7 @@
baseURL: 'http://192.168.3.145:9898/gsc-vcp-web-facade', baseURL: 'http://192.168.3.145:9898/gsc-vcp-web-facade',
appId: 'dj_zhixin', appId: 'dj_zhixin',
appSecret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b', appSecret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
timeout:500,
sentry: { sentry: {
enable: false, enable: false,
dsn: 'https://be4fb79a912b4c34a5d1c539a1618978@sentry.glsx.com.cn/1' dsn: 'https://be4fb79a912b4c34a5d1c539a1618978@sentry.glsx.com.cn/1'
...@@ -139,10 +140,10 @@ ...@@ -139,10 +140,10 @@
"dogs":{"name":"haogou","age":1}, "dogs":{"name":"haogou","age":1},
"X-Mock":false "X-Mock":false
}, },
retry:{ // retry:{
retries: 1, // retries: 1,
retryDelay: 1000, // retryDelay: 1000,
} // }
}); });
resultElement.textContent = resultElement.textContent =
......
...@@ -4,7 +4,7 @@ import { buildURL } from '../utils'; ...@@ -4,7 +4,7 @@ import { buildURL } from '../utils';
import { processResponse } from '../handlers/response-handler'; import { processResponse } from '../handlers/response-handler';
import { handleRequestError, handleResponseParseError } from '../handlers/error-handler'; import { handleRequestError, handleResponseParseError } from '../handlers/error-handler';
import type { Adapter } from '../types'; import type { Adapter } from '../types';
import { dispatchEvent } from "../../monitoring/events";
/** /**
* 基础适配器类 * 基础适配器类
* 提供适配器的通用功能,子类只需实现特定的请求发送逻辑 * 提供适配器的通用功能,子类只需实现特定的请求发送逻辑
...@@ -43,20 +43,8 @@ export abstract class BaseAdapter { ...@@ -43,20 +43,8 @@ export abstract class BaseAdapter {
* @param config 请求配置 * @param config 请求配置
* @returns 基础请求选项 * @returns 基础请求选项
*/ */
protected createBaseRequestOptions(config: RequestConfig): { protected createBaseRequestOptions(config: RequestConfig) {
method: string; const { method = 'GET', headers = {}, data = {}, timeout = 5000, signal } = config;
headers: Record<string, string>;
data: any;
timeout: number;
signal?: AbortSignal;
} {
const {
method = 'GET',
headers = {},
data = {},
timeout = 5000,
signal
} = config;
return { return {
method: method.toUpperCase(), method: method.toUpperCase(),
...@@ -73,15 +61,8 @@ export abstract class BaseAdapter { ...@@ -73,15 +61,8 @@ export abstract class BaseAdapter {
* @param fullURL 完整URL * @param fullURL 完整URL
* @returns 平台请求选项 * @returns 平台请求选项
*/ */
protected createPlatformRequestOptions(config: RequestConfig, fullURL: string): { protected createPlatformRequestOptions(config: RequestConfig, fullURL: string) {
url: string; const { method, headers, data, timeout } = this.createBaseRequestOptions(config);
method: string;
header: Record<string, string>;
timeout: number;
data: any;
} {
const baseOptions = this.createBaseRequestOptions(config);
const { method, headers, data, timeout } = baseOptions;
return { return {
url: fullURL, url: fullURL,
...@@ -115,10 +96,10 @@ export abstract class BaseAdapter { ...@@ -115,10 +96,10 @@ export abstract class BaseAdapter {
*/ */
protected checkHttpStatus(responseData: ResponseData<any>, config: RequestConfig): void { protected checkHttpStatus(responseData: ResponseData<any>, config: RequestConfig): void {
if (responseData.status >= 400) { if (responseData.status >= 400) {
const errorCode = responseData.status >= 500 ? 'SERVER_ERROR' : 'CLIENT_ERROR'; // const errorCode = responseData.status >= 500 ? 'SERVER_ERROR' : 'CLIENT_ERROR';
throw new RequestError( throw new RequestError(
`HTTP ${responseData.status}: ${responseData.statusText || 'Unknown Error'}`, `HTTP ${responseData.status}: ${responseData.statusText || 'Unknown Error'}`,
errorCode, String(responseData.status),
config, config,
undefined, undefined,
responseData responseData
...@@ -142,34 +123,55 @@ export abstract class BaseAdapter { ...@@ -142,34 +123,55 @@ export abstract class BaseAdapter {
* @returns Promise<ResponseData<any>> * @returns Promise<ResponseData<any>>
*/ */
protected handleRequest(config: RequestConfig): Promise<ResponseData<any>> { protected handleRequest(config: RequestConfig): Promise<ResponseData<any>> {
const { const { baseURL = '', url = '', method = 'GET', params = {}, timeout = 5000 } = config;
baseURL = '',
url = '',
method = 'GET',
params = {},
timeout = 5000,
signal
} = config;
// 构建完整URL // 构建完整URL
const fullURL = buildURL(baseURL, url, params, method); const fullURL = buildURL(baseURL, url, params, method);
// 创建请求选项
const options = this.createRequestOptions(config, fullURL); const options = this.createRequestOptions(config, fullURL);
// 如果没有设置超时,直接返回请求Promise
if (!timeout) {
return this.sendRequest(config, options, fullURL);
}
// 创建请求Promise return this.createTimeoutRace(config, options, fullURL, timeout);
const requestPromise = this.sendRequest(config, options, fullURL); }
/**
* 创建带超时的请求竞争
* @param config 请求配置
* @param options 请求选项
* @param fullURL 完整URL
* @param timeout 超时时间
* @returns Promise<ResponseData<any>>
*/
private createTimeoutRace(
config: RequestConfig,
options: any,
fullURL: string,
timeout: number
): Promise<ResponseData<any>> {
let timeoutId: NodeJS.Timeout | number | null = null;
let isCompleted = false;
const cleanup = () => {
isCompleted = true;
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
};
// 创建超时Promise
const timeoutPromise = new Promise<never>((_, reject) => { const timeoutPromise = new Promise<never>((_, reject) => {
if (timeout) { timeoutId = setTimeout(() => {
setTimeout(() => { if (!isCompleted) {
reject(RequestError.createTimeoutError(config)); reject(RequestError.createTimeoutError(config));
}, timeout); }
} }, timeout);
}); });
// 使用Promise.race竞争超时和请求 const requestPromise = this.sendRequest(config, options, fullURL).finally(cleanup);
return Promise.race([requestPromise, timeoutPromise]); return Promise.race([requestPromise, timeoutPromise]);
} }
...@@ -180,33 +182,24 @@ export abstract class BaseAdapter { ...@@ -180,33 +182,24 @@ export abstract class BaseAdapter {
* @param fullURL 完整URL * @param fullURL 完整URL
* @returns Promise<ResponseData<any>> * @returns Promise<ResponseData<any>>
*/ */
protected sendRequest(config: RequestConfig, options: any, fullURL: string): Promise<ResponseData<any>> { protected async sendRequest(config: RequestConfig, options: any, fullURL: string): Promise<ResponseData<any>> {
return new Promise<ResponseData<any>>((resolve, reject) => { try {
try { // 将fullURL添加到options中,以便executeRequest方法使用
// 将fullURL添加到options中,以便executeRequest方法使用 const optionsWithURL = { ...options, fullURL };
const optionsWithURL = { ...options, fullURL }; const rawResponse = await this.executeRequest(config, optionsWithURL);
this.executeRequest(config, optionsWithURL)
.then(async (rawResponse: any) => { // 转换响应数据
try { const responseData = await Promise.resolve(this.transformResponse(rawResponse, config));
// 转换响应数据
const responseData = await Promise.resolve(this.transformResponse(rawResponse, config)); // 检查HTTP状态码
// 检查HTTP状态码 this.checkHttpStatus(responseData, config);
this.checkHttpStatus(responseData, config);
// 处理响应 // 处理响应
resolve(this.handleResponse(responseData, config)); return this.handleResponse(responseData, config);
} catch (error) { } catch (error) {
reject(this.handleError(error, config)); // 处理请求错误
} this.handleError(error as any, config, config.signal);
}) }
.catch((error: any) => {
// 处理请求错误
reject(this.handleError(error, config, config.signal));
});
} catch (error) {
// 处理执行请求时的错误
reject(this.handleError(error, config, config.signal));
}
});
} }
/** /**
...@@ -230,6 +223,7 @@ export abstract class BaseAdapter { ...@@ -230,6 +223,7 @@ export abstract class BaseAdapter {
* @param signal 取消信号 * @param signal 取消信号
*/ */
protected handleError(error: any, config: RequestConfig, signal?: AbortSignal): never { protected handleError(error: any, config: RequestConfig, signal?: AbortSignal): never {
dispatchEvent('error', error, config);
return handleRequestError(error, config, signal); return handleRequestError(error, config, signal);
} }
} }
\ No newline at end of file \ No newline at end of file
...@@ -4,7 +4,7 @@ import { ...@@ -4,7 +4,7 @@ import {
type SignatureOptions, type SignatureOptions,
type SignatureResult, type SignatureResult,
} from "../security/signature"; } from "../security/signature";
import type { RequestConfig, ResponseData } from "../types"; import type { RequestConfig, ResponseData, SignatureHeaders } from "../types";
import { RequestError } from "../utils/error"; import { RequestError } from "../utils/error";
import { getAdapter, type Adapter } from "../adapter"; import { getAdapter, type Adapter } from "../adapter";
import { dispatchEvent } from "../monitoring/events"; import { dispatchEvent } from "../monitoring/events";
...@@ -63,10 +63,7 @@ class Request { ...@@ -63,10 +63,7 @@ class Request {
this.adapter = getAdapter(); this.adapter = getAdapter();
// 在初始化时确定签名函数 // 在初始化时确定签名函数
this.signFunc = (function (config: RequestConfig) { this.signFunc = this.defaults.signatureFunc || generateSignature;
// 如果用户提供了自定义签名函数,则使用它,否则使用默认签名函数
return config.signatureFunc || generateSignature;
})(this.defaults);
// 自动订阅事件 // 自动订阅事件
subscribeEvents(this.defaults.events); subscribeEvents(this.defaults.events);
...@@ -106,7 +103,24 @@ class Request { ...@@ -106,7 +103,24 @@ class Request {
// 将controller.signal设置到config中 // 将controller.signal设置到config中
config.signal = controller.signal; config.signal = controller.signal;
// 创建请求链 // 构建并执行拦截器链
const promise = this.buildInterceptorChain(config);
// 为Promise添加abort方法
const promiseWithAbort = promise as Promise<any> & { abort: () => void };
promiseWithAbort.abort = () => {
controller.abort();
};
return promiseWithAbort;
}
/**
* 构建拦截器链
* @param config 请求配置
* @returns 执行链Promise
*/
private buildInterceptorChain(config: RequestConfig): Promise<any> {
const chain: Array<(value: any) => any | Promise<any> | undefined> = [ const chain: Array<(value: any) => any | Promise<any> | undefined> = [
this.dispatchRequest.bind(this), this.dispatchRequest.bind(this),
() => undefined, () => undefined,
...@@ -132,52 +146,70 @@ class Request { ...@@ -132,52 +146,70 @@ class Request {
); );
} }
// 为Promise添加abort方法 return promise;
const promiseWithAbort = promise as Promise<any> & { abort: () => void };
promiseWithAbort.abort = () => {
controller.abort();
};
return promiseWithAbort;
} }
/** /**
* 处理请求分发 * 处理请求分发
* @param {Object} config 请求配置 * @param config 请求配置
* @returns {Promise} * @returns Promise
*/ */
async dispatchRequest<T = any>( async dispatchRequest<T = any>(
config: RequestConfig config: RequestConfig
): Promise<ResponseData<T>> { ): Promise<ResponseData<T>> {
// 防重复提交检查 // 防重复提交检查
if (config.duplicatePrevention) { this.handleDuplicatePrevention(config);
const requestUrl = config.url || '';
const isDuplicate = duplicatePreventionManager.checkDuplicate(config.duplicatePrevention, requestUrl);
if (isDuplicate) {
// 触发重复请求事件
dispatchEvent("duplicate",requestUrl, config);
throw new DuplicateRequestError(
`请求正在进行中,请勿重复提交。接口: ${requestUrl}`,
requestUrl,
config
);
}
}
// 添加签名 // 添加签名
const signedConfig = await this.addSignature(config); const signedConfig = await this.addSignature(config);
// 触发request事件
// 触发request事件
dispatchEvent("request", signedConfig.url, signedConfig); dispatchEvent("request", signedConfig.url, signedConfig);
// 根据单次请求是否有retry配置决定是否启用重试逻辑 // 执行请求
const requestPromise = this.executeRequest<T>(signedConfig); const requestPromise = this.executeRequest<T>(signedConfig);
// 注册请求到防重复提交管理器 // 注册请求到防重复提交管理器
if (config.duplicatePrevention) { this.registerDuplicatePreventionRequest(config, requestPromise);
duplicatePreventionManager.registerRequest(config.duplicatePrevention, config.url!, requestPromise);
}
return requestPromise; return requestPromise;
} }
/** /**
* 处理防重复提交检查
* @param config 请求配置
*/
private handleDuplicatePrevention(config: RequestConfig): void {
if (!config.duplicatePrevention) return;
const requestUrl = config.url || '';
const isDuplicate = duplicatePreventionManager.checkDuplicate(config.duplicatePrevention, requestUrl);
if (isDuplicate) {
dispatchEvent("duplicate", requestUrl, config);
throw new DuplicateRequestError(
`请求正在进行中,请勿重复提交。接口: ${requestUrl}`,
requestUrl,
config
);
}
}
/**
* 注册防重复提交请求
* @param config 请求配置
* @param requestPromise 请求Promise
*/
private registerDuplicatePreventionRequest<T>(
config: RequestConfig,
requestPromise: Promise<ResponseData<T>>
): void {
if (config.duplicatePrevention && config.url) {
duplicatePreventionManager.registerRequest(config.duplicatePrevention, config.url, requestPromise);
}
}
/**
* 执行请求,根据配置决定是否启用重试 * 执行请求,根据配置决定是否启用重试
* @param {RequestConfig} config 请求配置 * @param {RequestConfig} config 请求配置
* @returns {Promise<ResponseData<T>>} 请求结果 * @returns {Promise<ResponseData<T>>} 请求结果
...@@ -186,42 +218,14 @@ class Request { ...@@ -186,42 +218,14 @@ class Request {
if (config.retry) { if (config.retry) {
return sendRequestWithRetry(this.adapter, config); return sendRequestWithRetry(this.adapter, config);
} else { } else {
// 无重试的情况,需要手动处理error事件触发 return this.adapter(config);
return this.adapter(config).catch((error: any) => {
// 根据错误类型创建更准确的statusText
let statusText = 'Unknown Error';
if (error.response?.statusText) {
statusText = error.response.statusText;
} else if (error.code === 'TIMEOUT_ERROR') {
statusText = 'Request Timeout';
} else if (error.code === 'NETWORK_ERROR') {
statusText = 'Network Error';
} else if (error.message) {
statusText = error.message;
}
// 创建错误响应数据用于error事件
const errorResponseData = {
data: null,
status: error.response?.status || 0,
statusText,
headers: error.response?.headers || {},
config
};
// 触发error事件
dispatchEvent("error", errorResponseData, config);
// 重新抛出错误
throw error;
});
} }
} }
/** /**
* 添加签名信息 * 添加签名信息
* @param {Object} config 请求配置 * @param config 请求配置
* @returns {Object} 添加签名后的配置 * @returns 添加签名后的配置
*/ */
async addSignature(config: RequestConfig): Promise<RequestConfig> { async addSignature(config: RequestConfig): Promise<RequestConfig> {
const { appId, appSecret } = config; const { appId, appSecret } = config;
...@@ -229,41 +233,71 @@ class Request { ...@@ -229,41 +233,71 @@ class Request {
console.warn('\x1b[33m⚠️ %s\x1b[0m', "缺少签名所需的应用ID或密钥"); console.warn('\x1b[33m⚠️ %s\x1b[0m', "缺少签名所需的应用ID或密钥");
return config; return config;
} }
// 获取请求参数 // 处理白名单检查和参数
const params = await this.processWhitelistAndParams(config);
config.params = params;
const signature = this.buildSignatureHeaders(config);
config.headers = {
...config.headers,
...signature,
};
return config;
}
/**
* 处理白名单检查和参数
* @param config 请求配置
* @returns 处理后的参数
*/
private async processWhitelistAndParams(config: RequestConfig): Promise<Record<string, any>> {
const params = { ...config.params }; const params = { ...config.params };
// 根据配置决定是否检查白名单 if (this.defaults.security.enable && config.url) {
if (this.defaults.security.enable) { const isInWhitelist = await checkWhitelist(config.url, this.defaults.security.address);
// 检查当前请求的URL是否在白名单中
const isInWhitelist = await checkWhitelist(config.url!, this.defaults.security.address);
// 如果URL在白名单中,将sdctag=true添加到URL和签名参数中
if (isInWhitelist) { if (isInWhitelist) {
// 检查URL是否已经包含查询参数
params.sdctag = "true"; params.sdctag = "true";
} }
} }
config.params = params;
// 合并URL参数和请求体数据用于签名 return params;
}
/**
* 构建签名参数
* @param config 请求配置
* @returns 签名参数
*/
private buildSignatureParams(config: RequestConfig): Record<string, any> {
const signatureParams = { ...config.params }; const signatureParams = { ...config.params };
if (config.data && typeof config.data === "object") { if (config.data && typeof config.data === "object") {
Object.assign(signatureParams, config.data); Object.assign(signatureParams, config.data);
} }
return signatureParams;
}
// 使用预先确定的签名函数 /**
* 构建签名请求头
* @param config 请求配置
* @returns 签名请求头
*/
private buildSignatureHeaders(config: RequestConfig): SignatureHeaders {
const { appId, appSecret } = config;
// 生成签名参数
const signatureParams = this.buildSignatureParams(config);
// 生成并应用签名
const signature = this.signFunc({ const signature = this.signFunc({
appId, appId: appId!,
appSecret, appSecret: appSecret!,
params: signatureParams, params: signatureParams,
method: config.method || "POST", method: config.method || "POST",
}); });
// 添加签名到请求头
config.headers = { return {
...config.headers, "X-App-Id": appId!,
"X-App-Id": appId,
"X-Nonce": signature.nonce, "X-Nonce": signature.nonce,
"X-Timestamp": signature.timestamp, "X-Timestamp": signature.timestamp,
"X-Sign": signature.sign, "X-Sign": signature.sign,
}; };
return config;
} }
} }
......
...@@ -7,6 +7,13 @@ export interface RequestHeaders { ...@@ -7,6 +7,13 @@ export interface RequestHeaders {
[key: string]: string | undefined; [key: string]: string | undefined;
} }
export interface SignatureHeaders {
'X-App-Id': string;
'X-Nonce': string;
'X-Timestamp': string;
'X-Sign': string;
}
export interface SecurityConfig { export interface SecurityConfig {
enable?: boolean; // 是否启用白名单功能,默认为true enable?: boolean; // 是否启用白名单功能,默认为true
address?: string; // 获取白名单的地址,如果未提供则使用SDK内置默认地址 address?: string; // 获取白名单的地址,如果未提供则使用SDK内置默认地址
......
...@@ -14,6 +14,7 @@ export function isRetryableError(error: RequestError): boolean { ...@@ -14,6 +14,7 @@ export function isRetryableError(error: RequestError): boolean {
return ( return (
error.code === "NETWORK_ERROR" || error.code === "NETWORK_ERROR" ||
error.code === "TIMEOUT_ERROR" || error.code === "TIMEOUT_ERROR" ||
error.code === "SERVER_ERROR" ||
(error.response && (error.response &&
error.response.status >= 500 && error.response.status >= 500 &&
error.response.status < 600) error.response.status < 600)
...@@ -58,12 +59,10 @@ export function sendRequestWithRetry( ...@@ -58,12 +59,10 @@ export function sendRequestWithRetry(
if (shouldRetry) { if (shouldRetry) {
console.log('\x1b[33m🔄 %s\x1b[0m', `请求失败,正在进行第${retryCount + 1}次重试...`); console.log('\x1b[33m🔄 %s\x1b[0m', `请求失败,正在进行第${retryCount + 1}次重试...`);
// 创建延迟Promise // 创建延迟Promise
const delayPromise = new Promise((resolve) => { const delayPromise = new Promise((resolve) => {
setTimeout(resolve, retryDelay); setTimeout(resolve, retryDelay);
}); });
// 延迟后重试 // 延迟后重试
return delayPromise.then(() => { return delayPromise.then(() => {
// 如果需要重置超时,则重新创建一个新的AbortController // 如果需要重置超时,则重新创建一个新的AbortController
...@@ -71,38 +70,9 @@ export function sendRequestWithRetry( ...@@ -71,38 +70,9 @@ export function sendRequestWithRetry(
const controller = createAbortController(); const controller = createAbortController();
config.signal = controller.signal; config.signal = controller.signal;
} }
return sendRequestWithRetry(adapter, config, retryCount + 1); return sendRequestWithRetry(adapter, config, retryCount + 1);
}); });
} }
// 不需要重试,触发error事件后抛出错误
console.log('\x1b[31m💥 %s\x1b[0m', '重试最终失败,触发error事件');
// 根据错误类型创建更准确的statusText
let statusText = 'Unknown Error';
if (error.response?.statusText) {
statusText = error.response.statusText;
} else if (error.code === 'TIMEOUT_ERROR') {
statusText = 'Request Timeout';
} else if (error.code === 'NETWORK_ERROR') {
statusText = 'Network Error';
} else if (error.message) {
statusText = error.message;
}
// 创建一个模拟的响应数据用于error事件
const errorResponseData = {
data: null,
status: error.response?.status || 0,
statusText,
headers: error.response?.headers || {},
config
};
// 触发error事件
dispatchEvent("error", errorResponseData, config);
throw error; throw error;
}); });
} }
\ No newline at end of file \ No newline at end of file
// 测试新的超时管理机制与重试逻辑的兼容性
const { Request } = require('./dist/index.js');
// 创建请求实例
const request = new Request({
baseURL: 'http://localhost:3002',
timeout: 2000, // 2秒超时
retry: {
retries: 3,
retryDelay: 1000,
retryCondition: (error) => {
console.log('🔍 重试条件检查:', {
errorType: error.constructor.name,
code: error.code,
message: error.message,
isTimeout: error.code === 'TIMEOUT',
isNetworkError: error.code === 'NETWORK_ERROR'
});
// 允许超时错误和网络错误重试
return error.code === 'TIMEOUT' || error.code === 'NETWORK_ERROR' ||
(error.response && error.response.status >= 500);
}
}
});
async function testTimeoutRetry() {
console.log('🚀 开始测试超时重试机制...\n');
try {
console.log('📡 测试1: 请求500错误端点(应该重试)');
const result1 = await request.get('/api/test-500');
console.log('✅ 测试1结果:', result1.data);
} catch (error) {
console.log('❌ 测试1失败:', {
type: error.constructor.name,
code: error.code,
message: error.message
});
}
console.log('\n' + '='.repeat(50) + '\n');
try {
console.log('📡 测试2: 请求不存在的端点(模拟超时,应该重试)');
const result2 = await request.get('/api/very-slow-endpoint');
console.log('✅ 测试2结果:', result2.data);
} catch (error) {
console.log('❌ 测试2失败:', {
type: error.constructor.name,
code: error.code,
message: error.message
});
}
console.log('\n' + '='.repeat(50) + '\n');
try {
console.log('📡 测试3: 请求成功端点(不应该重试)');
const result3 = await request.get('/api/test-success');
console.log('✅ 测试3结果:', result3.data);
} catch (error) {
console.log('❌ 测试3失败:', {
type: error.constructor.name,
code: error.code,
message: error.message
});
}
}
// 运行测试
testTimeoutRetry().then(() => {
console.log('\n🎉 测试完成!');
process.exit(0);
}).catch((error) => {
console.error('💥 测试过程中发生错误:', error);
process.exit(1);
});
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!