UNPKG

shora-ai-payment-sdk

Version:

The first open-source payment SDK designed specifically for AI agents and chatbots - ACP Compatible

66 lines (65 loc) 1.91 kB
export class CircuitBreaker { constructor() { this.failureCount = 0; this.lastFailureTime = 0; this.state = 'CLOSED'; this.failureThreshold = 5; this.timeout = 60000; } async execute(fn) { if (this.state === 'OPEN') { if (Date.now() - this.lastFailureTime > this.timeout) { this.state = 'HALF_OPEN'; } else { throw new Error('Circuit breaker is OPEN'); } } try { const result = await fn(); this.onSuccess(); return result; } catch (error) { this.onFailure(); throw error; } } onSuccess() { this.failureCount = 0; this.state = 'CLOSED'; } onFailure() { this.failureCount++; this.lastFailureTime = Date.now(); if (this.failureCount >= this.failureThreshold) { this.state = 'OPEN'; } } getState() { return this.state; } } export async function withRetry(fn, options = {}) { const { maxAttempts = 3, baseDelay = 1000, maxDelay = 10000, backoffMultiplier = 2, retryCondition = (error) => { return !error.response || error.response.status >= 500; } } = options; let lastError; for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { return await fn(); } catch (error) { lastError = error; if (attempt === maxAttempts || !retryCondition(error)) { throw error; } const delay = Math.min(baseDelay * Math.pow(backoffMultiplier, attempt - 1), maxDelay); await new Promise(resolve => setTimeout(resolve, delay)); } } throw lastError; } export function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }