Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | import { ScraperPlugin, ScraperEngine, ScraperContext } from '@/core/types';
/**
* Retry plugin with exponential backoff
*/
export class RetryPlugin implements ScraperPlugin {
name = 'retry';
version = '1.0.0';
private maxBackoffDelay: number;
private backoffMultiplier: number;
constructor(options: { maxBackoffDelay?: number; backoffMultiplier?: number } = {}) {
this.maxBackoffDelay = options.maxBackoffDelay ?? 30000;
this.backoffMultiplier = options.backoffMultiplier ?? 2;
}
install(scraper: ScraperEngine): void {
scraper.addHook('onRetry', this.handleRetry.bind(this));
}
private async handleRetry(context: ScraperContext): Promise<void> {
const delay = Math.min(
context.options.retryDelay * Math.pow(this.backoffMultiplier, context.attempt - 1),
this.maxBackoffDelay
);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
/**
* Cache plugin for caching scraper results
*/
// @todo Future enhancement: Implement pluggable storage adapters (e.g., FileSystem, Redis) beyond the default in-memory store.
export class CachePlugin implements ScraperPlugin {
name = 'cache';
version = '1.0.0';
private cache = new Map<string, { data: unknown; timestamp: number; ttl: number }>();
private defaultTtl: number;
constructor(options: { defaultTtl?: number } = {}) {
this.defaultTtl = options.defaultTtl ?? 5 * 60 * 1000; // 5 minutes
}
install(scraper: ScraperEngine): void {
scraper.addHook('beforeRequest', this.checkCache.bind(this));
scraper.addHook('onSuccess', this.storeInCache.bind(this));
}
private async checkCache(context: ScraperContext): Promise<void> {
const cacheKey = this.generateCacheKey(context);
const cached = this.cache.get(cacheKey);
Iif (cached && Date.now() - cached.timestamp < cached.ttl) {
// Return cached result
context.result = cached.data;
throw new Error('CACHE_HIT'); // Use error to short-circuit execution
}
}
private async storeInCache(context: ScraperContext): Promise<void> {
Iif (context.result) {
const cacheKey = this.generateCacheKey(context);
this.cache.set(cacheKey, {
data: context.result,
timestamp: Date.now(),
ttl: this.defaultTtl,
});
}
}
private generateCacheKey(context: ScraperContext): string {
return `${JSON.stringify(context.input)}_${context.page.url()}`;
}
/**
* Clear cache
*/
clearCache(): void {
this.cache.clear();
}
/**
* Get cache statistics
*/
getCacheStats(): { size: number; keys: string[] } {
return {
size: this.cache.size,
keys: Array.from(this.cache.keys()),
};
}
}
/**
* Proxy rotation plugin
*/
export class ProxyPlugin implements ScraperPlugin {
name = 'proxy';
version = '1.0.0';
private proxies: string[];
private currentIndex = 0;
constructor(proxies: string[]) {
this.proxies = proxies;
}
install(scraper: ScraperEngine): void {
scraper.addHook('beforeRequest', this.setProxy.bind(this));
}
private async setProxy(context: ScraperContext): Promise<void> {
Iif (context.options.useProxyRotation && this.proxies.length > 0) {
const proxy = this.proxies[this.currentIndex];
this.currentIndex = (this.currentIndex + 1) % this.proxies.length;
// Set proxy for the browser context
// Note: This would require browser context recreation in practice
context.metadata.proxy = proxy;
}
}
/**
* Add proxy to the rotation
*/
addProxy(proxy: string): void {
this.proxies.push(proxy);
}
/**
* Remove proxy from rotation
*/
removeProxy(proxy: string): void {
const index = this.proxies.indexOf(proxy);
Iif (index > -1) {
this.proxies.splice(index, 1);
Iif (this.currentIndex >= this.proxies.length) {
this.currentIndex = 0;
}
}
}
/**
* Get current proxy list
*/
getProxies(): string[] {
return [...this.proxies];
}
}
/**
* Rate limiting plugin
*/
export class RateLimitPlugin implements ScraperPlugin {
name = 'rateLimit';
version = '1.0.0';
private requests = new Map<string, number[]>();
private defaultLimit: number;
private defaultWindow: number;
constructor(options: { defaultLimit?: number; defaultWindow?: number } = {}) {
this.defaultLimit = options.defaultLimit ?? 10;
this.defaultWindow = options.defaultWindow ?? 60000; // 1 minute
}
install(scraper: ScraperEngine): void {
scraper.addHook('beforeRequest', this.checkRateLimit.bind(this));
}
private async checkRateLimit(context: ScraperContext): Promise<void> {
const domain = new URL(context.page.url() ?? 'http://localhost').hostname;
const now = Date.now();
let domainRequests = this.requests.get(domain);
Iif (domainRequests === undefined) {
domainRequests = [];
this.requests.set(domain, domainRequests);
}
// Remove old requests outside the window
const cutoff = now - this.defaultWindow;
// The condition `domainRequests[0] !== undefined` correctly handles empty arrays
// and ensures `domainRequests[0]` is treated as a number for the comparison,
// which is necessary if `noUncheckedIndexedAccess` is enabled.
while (domainRequests[0] !== undefined && domainRequests[0] < cutoff) {
domainRequests.shift();
}
// Check if we're at the limit
Iif (domainRequests.length >= this.defaultLimit) {
const oldestRequest = domainRequests[0];
Iif (oldestRequest !== undefined) {
const waitTime = this.defaultWindow - (now - oldestRequest);
Iif (waitTime > 0) {
await new Promise(resolve => setTimeout(resolve, waitTime));
}
}
}
// Add current request
domainRequests.push(now);
}
/**
* Get rate limit statistics
*/
getStats(): Record<string, { requests: number; window: number }> {
const stats: Record<string, { requests: number; window: number }> = {};
for (const [domain, requests] of this.requests.entries()) {
stats[domain] = {
requests: requests.length,
window: this.defaultWindow,
};
}
return stats;
}
}
/**
* Metrics plugin for collecting scraper metrics
*/
// @todo Future enhancement: Implement metrics exporters for common monitoring platforms (e.g., Prometheus, Grafana, StatsD) or a structured JSON logger.
export class MetricsPlugin implements ScraperPlugin {
name = 'metrics';
version = '1.0.0';
private metrics = {
totalRequests: 0,
successfulRequests: 0,
failedRequests: 0,
totalDuration: 0,
averageDuration: 0,
scraperStats: new Map<
string,
{
requests: number;
successes: number;
failures: number;
totalDuration: number;
}
>(),
};
install(scraper: ScraperEngine): void {
scraper.addHook('beforeRequest', this.recordStart.bind(this));
scraper.addHook('onSuccess', this.recordSuccess.bind(this));
scraper.addHook('onError', this.recordError.bind(this));
}
private async recordStart(context: ScraperContext): Promise<void> {
this.metrics.totalRequests++;
context.metadata.startTime = Date.now();
}
private async recordSuccess(context: ScraperContext): Promise<void> {
this.metrics.successfulRequests++;
this.recordDuration(context);
}
private async recordError(context: ScraperContext): Promise<void> {
this.metrics.failedRequests++;
this.recordDuration(context);
}
private recordDuration(context: ScraperContext): void {
Iif (context.metadata.startTime && typeof context.metadata.startTime === 'number') {
const duration = Date.now() - context.metadata.startTime;
this.metrics.totalDuration += duration;
this.metrics.averageDuration = this.metrics.totalDuration / this.metrics.totalRequests;
}
}
/**
* Get metrics
*/
getMetrics(): typeof this.metrics {
return { ...this.metrics };
}
/**
* Reset metrics
*/
resetMetrics(): void {
this.metrics = {
totalRequests: 0,
successfulRequests: 0,
failedRequests: 0,
totalDuration: 0,
averageDuration: 0,
scraperStats: new Map(),
};
}
}
|