1- import { logger , retry } from '@/utils' ;
2- import type { RetryOptions } from '@/utils' ;
1+ import { logger } from '@/utils' ;
32import { createTimeWheel } from '@/utils/data-structures/TimeWheel' ;
43import type { TimeWheel } from '@/utils/data-structures/TimeWheel' ;
54
@@ -22,6 +21,17 @@ interface FingerprintData {
2221 hitCount : number ;
2322}
2423
24+ /**
25+ * 重试选项
26+ */
27+ interface RetryOptions {
28+ maxRetries : number ;
29+ backoff : ( attempt : number ) => number ;
30+ shouldRetry ?: ( error : unknown ) => boolean ;
31+ onRetry ?: ( attempt : number , error : unknown ) => void ;
32+ silent ?: boolean ;
33+ }
34+
2535/**
2636 * 请求批处理器类
2737 *
@@ -60,6 +70,55 @@ export class RequestBatcher {
6070 return `${ method } :${ key } :${ headerStr } ` ;
6171 }
6272
73+ /**
74+ * 重试选项
75+ */
76+ private withRetry = async < T > (
77+ fn : ( ) => Promise < T > ,
78+ options : RetryOptions
79+ ) : Promise < T > => {
80+ const {
81+ maxRetries,
82+ backoff,
83+ shouldRetry = ( ) => true ,
84+ onRetry,
85+ silent = false
86+ } = options ;
87+
88+ let lastError : unknown = null ;
89+
90+ for ( let attempt = 0 ; attempt <= maxRetries ; attempt ++ ) {
91+ try {
92+ const result = await fn ( ) ;
93+ if ( attempt > 0 ) {
94+ logger . debug ( `操作在第 ${ ( attempt + 1 ) . toString ( ) } 次尝试后成功` ) ;
95+ }
96+ return result ;
97+ } catch ( error : unknown ) {
98+ lastError = error ;
99+
100+ if ( attempt < maxRetries && shouldRetry ( error ) ) {
101+ const delay = backoff ( attempt ) ;
102+
103+ if ( onRetry !== undefined ) {
104+ onRetry ( attempt , error ) ;
105+ }
106+
107+ if ( ! silent ) {
108+ const errorMessage = error instanceof Error ? error . message : String ( error ) ;
109+ logger . debug ( `重试操作 (尝试 ${ ( attempt + 1 ) . toString ( ) } /${ ( maxRetries + 1 ) . toString ( ) } ),延迟 ${ delay . toString ( ) } ms: ${ errorMessage } ` ) ;
110+ }
111+
112+ await new Promise ( resolve => setTimeout ( resolve , delay ) ) ;
113+ } else {
114+ break ;
115+ }
116+ }
117+ }
118+
119+ throw lastError ;
120+ } ;
121+
63122 /**
64123 * 将请求加入批处理队列
65124 *
@@ -191,7 +250,7 @@ export class RequestBatcher {
191250
192251 try {
193252 // 使用通用重试逻辑执行请求
194- const result = await retry . withRetry ( executeRequest , retryOptions ) ;
253+ const result = await this . withRetry ( executeRequest , retryOptions ) ;
195254
196255 // 缓存成功的请求结果
197256 if ( ! skipDeduplication ) {
0 commit comments