fix: anti-ban 模块改为 .js(Node.js 原生支持)

This commit is contained in:
2026-05-15 20:46:07 +08:00
parent a1b6a76b8c
commit 45c2d42905
@@ -6,50 +6,41 @@
* - Each wait adds 0-jitterMax seconds of random jitter * - Each wait adds 0-jitterMax seconds of random jitter
*/ */
export interface AntiBanConfig { const DEFAULT_CONFIG = {
baseDelay: number; // seconds
maxDelay: number; // seconds
jitterMax: number; // seconds
}
const DEFAULT_CONFIG: AntiBanConfig = {
baseDelay: Number(process.env.GEMINI_BASE_DELAY) || 15, baseDelay: Number(process.env.GEMINI_BASE_DELAY) || 15,
maxDelay: Number(process.env.GEMINI_MAX_DELAY) || 120, maxDelay: Number(process.env.GEMINI_MAX_DELAY) || 120,
jitterMax: 5, jitterMax: 5,
}; };
export class AntiBanController { export class AntiBanController {
private currentDelay: number; constructor(config) {
private config: AntiBanConfig;
retryCount = 0;
rateLimitEvents = 0;
constructor(config?: Partial<AntiBanConfig>) {
this.config = { ...DEFAULT_CONFIG, ...config }; this.config = { ...DEFAULT_CONFIG, ...config };
this.currentDelay = this.config.baseDelay; this.currentDelay = this.config.baseDelay;
this.retryCount = 0;
this.rateLimitEvents = 0;
} }
/** Call after a successful generation */ /** Call after a successful generation */
onSuccess(): void { onSuccess() {
this.currentDelay = Math.max(this.config.baseDelay * 0.5, this.currentDelay * 0.7); this.currentDelay = Math.max(this.config.baseDelay * 0.5, this.currentDelay * 0.7);
} }
/** Call after rate limit / timeout / error */ /** Call after rate limit / timeout / error */
onRateLimit(): void { onRateLimit() {
this.rateLimitEvents++; this.rateLimitEvents++;
this.currentDelay = Math.min(this.config.maxDelay, this.currentDelay * 2); this.currentDelay = Math.min(this.config.maxDelay, this.currentDelay * 2);
} }
/** Wait between requests with jitter */ /** Wait between requests with jitter */
async wait(): Promise<void> { async wait() {
const jitter = Math.random() * this.config.jitterMax; const jitter = Math.random() * this.config.jitterMax;
const totalMs = (this.currentDelay + jitter) * 1000; const totalMs = (this.currentDelay + jitter) * 1000;
const log = (await import('./browser.js')).log; const { log } = await import('./browser.js');
log(`[anti-ban] waiting ${(totalMs / 1000).toFixed(1)}s (base=${this.currentDelay.toFixed(1)}s, jitter=${jitter.toFixed(1)}s)`); log(`[anti-ban] waiting ${(totalMs / 1000).toFixed(1)}s (base=${this.currentDelay.toFixed(1)}s, jitter=${jitter.toFixed(1)}s)`);
await new Promise((r) => setTimeout(r, totalMs)); await new Promise((r) => setTimeout(r, totalMs));
} }
get delay(): number { get delay() {
return this.currentDelay; return this.currentDelay;
} }