@retrivora-ai/rag-engine 2.4.3 → 2.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.md +22 -0
  2. package/dist/{BatchProcessor-zbQMaZHm.d.mts → BatchProcessor-BGslIR5l.d.mts} +65 -4
  3. package/dist/{BatchProcessor-D42E706a.d.ts → BatchProcessor-C3gY6kZ0.d.ts} +65 -4
  4. package/dist/handlers/index.js +668 -837
  5. package/dist/handlers/index.mjs +678 -837
  6. package/dist/index.css +5 -0
  7. package/dist/index.d.mts +4 -28
  8. package/dist/index.d.ts +4 -28
  9. package/dist/index.js +91 -43
  10. package/dist/index.min.css +1 -1
  11. package/dist/index.mjs +91 -43
  12. package/dist/server.d.mts +21 -7
  13. package/dist/server.d.ts +21 -7
  14. package/dist/server.js +731 -875
  15. package/dist/server.mjs +741 -875
  16. package/package.json +11 -4
  17. package/src/LicensedRetrivora.ts +0 -278
  18. package/src/app/api/chat/route.ts +0 -4
  19. package/src/app/api/health/route.ts +0 -5
  20. package/src/app/api/ingest/route.ts +0 -27
  21. package/src/app/api/suggestions/route.ts +0 -5
  22. package/src/app/api/upload/route.ts +0 -5
  23. package/src/app/constants.tsx +0 -270
  24. package/src/app/favicon.ico +0 -0
  25. package/src/app/globals.css +0 -449
  26. package/src/app/layout.tsx +0 -22
  27. package/src/app/page.tsx +0 -64
  28. package/src/app/types.ts +0 -30
  29. package/src/browser.tsx +0 -127
  30. package/src/components/ChatWidget.tsx +0 -393
  31. package/src/components/ChatWindow.tsx +0 -952
  32. package/src/components/CodeViewer.tsx +0 -56
  33. package/src/components/ConfigProvider.tsx +0 -141
  34. package/src/components/DocumentUpload.tsx +0 -354
  35. package/src/components/DynamicChart.tsx +0 -297
  36. package/src/components/HourglassLoader.tsx +0 -87
  37. package/src/components/MarkdownComponents.tsx +0 -186
  38. package/src/components/MessageBubble.tsx +0 -498
  39. package/src/components/ObservabilityPanel.tsx +0 -374
  40. package/src/components/ProductCard.tsx +0 -107
  41. package/src/components/ProductCarousel.tsx +0 -97
  42. package/src/components/SourceCard.tsx +0 -61
  43. package/src/components/ThemeProvider.tsx +0 -8
  44. package/src/components/ThemeToggle.tsx +0 -29
  45. package/src/components/ThinkingBlock.tsx +0 -75
  46. package/src/components/UIDispatcher.tsx +0 -342
  47. package/src/components/VisualizationRenderer.tsx +0 -621
  48. package/src/components/constants.tsx +0 -503
  49. package/src/config/ConfigBuilder.ts +0 -285
  50. package/src/config/EmbeddingStrategy.ts +0 -148
  51. package/src/config/LicenseConfigResolver.ts +0 -298
  52. package/src/config/RagConfig.ts +0 -328
  53. package/src/config/UniversalProfiles.ts +0 -82
  54. package/src/config/constants.ts +0 -64
  55. package/src/config/serverConfig.ts +0 -378
  56. package/src/config/uiConstants.ts +0 -47
  57. package/src/core/BatchProcessor.ts +0 -385
  58. package/src/core/CircuitBreaker.ts +0 -118
  59. package/src/core/ConfigFetcher.ts +0 -220
  60. package/src/core/ConfigResolver.ts +0 -165
  61. package/src/core/ConfigValidator.ts +0 -197
  62. package/src/core/DatabaseStorage.ts +0 -526
  63. package/src/core/FreeTierLimitsGuard.ts +0 -281
  64. package/src/core/LLMRouter.ts +0 -79
  65. package/src/core/LangChainAgent.ts +0 -132
  66. package/src/core/LicenseValidator.ts +0 -284
  67. package/src/core/LicenseVerifier.ts +0 -261
  68. package/src/core/MultiAgentCoordinator.ts +0 -239
  69. package/src/core/Pipeline.ts +0 -1279
  70. package/src/core/PluginManager.ts +0 -277
  71. package/src/core/ProjectSettings.ts +0 -247
  72. package/src/core/ProviderHealthCheck.ts +0 -133
  73. package/src/core/ProviderInterfaces.ts +0 -37
  74. package/src/core/ProviderRegistry.ts +0 -156
  75. package/src/core/QueryProcessor.ts +0 -399
  76. package/src/core/Retrivora.ts +0 -98
  77. package/src/core/VectorPlugin.ts +0 -193
  78. package/src/core/mcp.ts +0 -261
  79. package/src/exceptions/index.ts +0 -131
  80. package/src/handlers/index.ts +0 -1625
  81. package/src/hooks/useHydrated.ts +0 -13
  82. package/src/hooks/useProjectSettings.ts +0 -105
  83. package/src/hooks/useRagChat.ts +0 -436
  84. package/src/hooks/useStoredMessages.ts +0 -64
  85. package/src/index.css +0 -4269
  86. package/src/index.ts +0 -137
  87. package/src/lib/plugin.ts +0 -24
  88. package/src/llm/ILLMProvider.ts +0 -60
  89. package/src/llm/LLMFactory.ts +0 -141
  90. package/src/llm/providers/AnthropicProvider.ts +0 -215
  91. package/src/llm/providers/GeminiProvider.ts +0 -311
  92. package/src/llm/providers/GroqProvider.ts +0 -184
  93. package/src/llm/providers/OllamaProvider.ts +0 -232
  94. package/src/llm/providers/OpenAIProvider.ts +0 -188
  95. package/src/llm/providers/QwenProvider.ts +0 -199
  96. package/src/llm/providers/UniversalLLMAdapter.ts +0 -422
  97. package/src/llm/utils.ts +0 -46
  98. package/src/providers/graphdb/BaseGraphProvider.ts +0 -43
  99. package/src/providers/graphdb/SimpleGraphProvider.ts +0 -66
  100. package/src/providers/vectordb/BaseVectorProvider.ts +0 -98
  101. package/src/providers/vectordb/ChromaDBProvider.ts +0 -130
  102. package/src/providers/vectordb/MilvusProvider.ts +0 -134
  103. package/src/providers/vectordb/MongoDBProvider.ts +0 -250
  104. package/src/providers/vectordb/MultiTablePostgresProvider.ts +0 -461
  105. package/src/providers/vectordb/PineconeProvider.ts +0 -295
  106. package/src/providers/vectordb/PostgreSQLProvider.ts +0 -227
  107. package/src/providers/vectordb/QdrantProvider.ts +0 -294
  108. package/src/providers/vectordb/RedisProvider.ts +0 -105
  109. package/src/providers/vectordb/UniversalVectorProvider.ts +0 -221
  110. package/src/providers/vectordb/WeaviateProvider.ts +0 -172
  111. package/src/rag/DocumentChunker.ts +0 -144
  112. package/src/rag/EntityExtractor.ts +0 -90
  113. package/src/rag/LlamaIndexIngestor.ts +0 -60
  114. package/src/rag/Reranker.ts +0 -106
  115. package/src/rendering/IntentClassifier.ts +0 -167
  116. package/src/rendering/RendererRegistry.ts +0 -164
  117. package/src/rendering/RuleEngine.ts +0 -67
  118. package/src/rendering/VisualizationDecisionEngine.ts +0 -164
  119. package/src/rendering/__tests__/VisualizationDecisionEngine.test.ts +0 -237
  120. package/src/rendering/index.ts +0 -12
  121. package/src/rendering/rules/Rule1SpecificInfoRule.ts +0 -28
  122. package/src/rendering/rules/Rule2ComparisonRule.ts +0 -24
  123. package/src/rendering/rules/Rule3ProductDiscoveryRule.ts +0 -28
  124. package/src/rendering/rules/Rule4AnalyticalRule.ts +0 -38
  125. package/src/rendering/rules/Rule5MixedResponseRule.ts +0 -29
  126. package/src/rendering/rules/Rule6SmallResultSetRule.ts +0 -24
  127. package/src/rendering/rules/Rule7LargeTableRule.ts +0 -35
  128. package/src/rendering/types.ts +0 -96
  129. package/src/server.ts +0 -156
  130. package/src/tailwind.css +0 -194
  131. package/src/telemetry/TelemetryService.ts +0 -330
  132. package/src/types/chat.ts +0 -89
  133. package/src/types/index.ts +0 -278
  134. package/src/types/pdf-parse.d.ts +0 -13
  135. package/src/types/props.ts +0 -169
  136. package/src/utils/DocumentParser.ts +0 -111
  137. package/src/utils/ProductExtractor.ts +0 -350
  138. package/src/utils/SchemaMapper.ts +0 -176
  139. package/src/utils/UITransformer.ts +0 -1812
  140. package/src/utils/synonyms.ts +0 -80
  141. package/src/utils/templateUtils.ts +0 -78
  142. package/src/version.ts +0 -6
@@ -1,385 +0,0 @@
1
- /**
2
- * BatchProcessor.ts — Handles batch operations with retry logic.
3
- *
4
- * Provides exponential backoff, partial failure tracking, and
5
- * configurable batch sizing for efficient bulk operations.
6
- */
7
-
8
- import { CircuitBreaker } from './CircuitBreaker';
9
-
10
- export interface BatchOptions {
11
- /** Maximum number of items per batch */
12
- batchSize?: number;
13
- /** Maximum number of retries for transient failures */
14
- maxRetries?: number;
15
- /** Initial delay before retry in milliseconds */
16
- initialDelayMs?: number;
17
- /** Maximum delay between retries in milliseconds */
18
- maxDelayMs?: number;
19
- /** Multiplier for exponential backoff */
20
- backoffMultiplier?: number;
21
- /** Whether to throw on any partial failure */
22
- throwOnPartialFailure?: boolean;
23
- }
24
-
25
- export interface BatchResult<T> {
26
- results: T[];
27
- errors: Array<{ index: number; error: Error; itemCount?: number }>;
28
- totalProcessed: number;
29
- totalFailed: number;
30
- }
31
-
32
- /**
33
- * Determines if an error is transient (should retry)
34
- */
35
- export function isTransientError(error: unknown): boolean {
36
- if (!(error instanceof Error)) return false;
37
-
38
- const message = error.message.toLowerCase();
39
-
40
- // Network errors
41
- if (
42
- message.includes('econnrefused') ||
43
- message.includes('econnreset') ||
44
- message.includes('timeout') ||
45
- message.includes('network') ||
46
- message.includes('socket')
47
- ) {
48
- return true;
49
- }
50
-
51
- // HTTP errors (rate limit, service unavailable)
52
- if (
53
- message.includes('429') ||
54
- message.includes('503') ||
55
- message.includes('502') ||
56
- message.includes('rate limit') ||
57
- message.includes('too many requests')
58
- ) {
59
- return true;
60
- }
61
-
62
- return false;
63
- }
64
-
65
- /**
66
- * Calculates delay using exponential backoff with jitter
67
- */
68
- function calculateBackoffDelay(
69
- attempt: number,
70
- initialDelayMs: number,
71
- maxDelayMs: number,
72
- multiplier: number
73
- ): number {
74
- const exponentialDelay = Math.min(
75
- initialDelayMs * Math.pow(multiplier, attempt),
76
- maxDelayMs
77
- );
78
- // Add jitter: ±10% of the delay
79
- const jitter = exponentialDelay * 0.1 * (Math.random() * 2 - 1);
80
- return Math.max(0, exponentialDelay + jitter);
81
- }
82
-
83
- /**
84
- * Sleeps for the given duration
85
- */
86
- function sleep(ms: number): Promise<void> {
87
- return new Promise((resolve) => setTimeout(resolve, ms));
88
- }
89
-
90
- export class BatchProcessor {
91
- private static readonly cb = new CircuitBreaker({
92
- failureThreshold: 5,
93
- resetTimeoutMs: 30_000,
94
- halfOpenMaxCalls: 1,
95
- });
96
-
97
- /**
98
- * Execute a processor call through the circuit breaker.
99
- * Only transient failures count toward opening the circuit.
100
- */
101
- private static async executeWithCircuitBreaker<T>(processor: () => Promise<T>): Promise<T> {
102
- if (!this.cb.canExecute()) {
103
- const retryAfterSec = Math.ceil(
104
- Math.max(0, 30_000 - (Date.now() - (this.cb as any).lastFailureAt || 0)) / 1000
105
- );
106
- throw new Error(
107
- `[BatchProcessor] Circuit breaker is open. Try again in ${retryAfterSec}s.`
108
- );
109
- }
110
-
111
- if ((this.cb as any).state === 'half-open') {
112
- (this.cb as any).halfOpenCalls++;
113
- }
114
-
115
- try {
116
- const result = await processor();
117
- this.cb.record(true);
118
- return result;
119
- } catch (err) {
120
- if (isTransientError(err)) {
121
- this.cb.record(false);
122
- }
123
- throw err;
124
- }
125
- }
126
-
127
- /**
128
- * Processes an array of items in configurable batches with retry logic.
129
- *
130
- * @param items - Items to process
131
- * @param processor - Async function that processes a batch of items
132
- * @param options - Configuration for batch size, retries, etc.
133
- * @returns Object with results, errors, and statistics
134
- *
135
- * @example
136
- * const docs = [...];
137
- * const result = await BatchProcessor.processBatch(
138
- * docs,
139
- * (batch) => vectorDB.batchUpsert(batch),
140
- * { batchSize: 100, maxRetries: 3 }
141
- * );
142
- */
143
- static async processBatch<T, R>(
144
- items: T[],
145
- processor: (batch: T[]) => Promise<R>,
146
- options?: BatchOptions
147
- ): Promise<BatchResult<R>> {
148
- const {
149
- batchSize = 100,
150
- maxRetries = 3,
151
- initialDelayMs = 100,
152
- maxDelayMs = 10000,
153
- backoffMultiplier = 2,
154
- throwOnPartialFailure = false,
155
- } = options ?? {};
156
-
157
- const results: R[] = [];
158
- const errors: Array<{ index: number; error: Error; itemCount?: number }> = [];
159
-
160
- // Split items into batches
161
- const batches: T[][] = [];
162
- for (let i = 0; i < items.length; i += batchSize) {
163
- batches.push(items.slice(i, i + batchSize));
164
- }
165
-
166
- if (batches.length === 0) {
167
- return { results: [], errors: [], totalProcessed: 0, totalFailed: 0 };
168
- }
169
-
170
- // Process each batch with retry logic
171
- for (let batchIndex = 0; batchIndex < batches.length; batchIndex++) {
172
- const batch = batches[batchIndex];
173
- let success = false;
174
- let lastError: Error | undefined;
175
-
176
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
177
- try {
178
- const result = await BatchProcessor.executeWithCircuitBreaker(() => processor(batch));
179
- results.push(result);
180
- success = true;
181
- break;
182
- } catch (err) {
183
- lastError = err instanceof Error ? err : new Error(String(err));
184
-
185
- // If not transient or last attempt, fail immediately
186
- if (!isTransientError(err) || attempt === maxRetries) {
187
- break;
188
- }
189
-
190
- // Wait before retry with exponential backoff
191
- const delay = calculateBackoffDelay(
192
- attempt,
193
- initialDelayMs,
194
- maxDelayMs,
195
- backoffMultiplier
196
- );
197
- await sleep(delay);
198
- }
199
- }
200
-
201
- if (!success && lastError) {
202
- errors.push({
203
- index: batchIndex,
204
- error: lastError,
205
- itemCount: batch.length,
206
- });
207
- }
208
- }
209
-
210
- const totalProcessed = items.length - (errors.length > 0 ? errors.reduce((sum, e) => sum + (e.itemCount || 0), 0) : 0);
211
- const totalFailed = errors.reduce((sum, e) => sum + (e.itemCount || 0), 0);
212
-
213
- if (throwOnPartialFailure && errors.length > 0) {
214
- const errorMessages = errors
215
- .map((e) => `Batch ${e.index} (${e.itemCount} items): ${e.error.message}`)
216
- .join('\n');
217
- throw new Error(
218
- `[BatchProcessor] Batch processing failed:\n${errorMessages}`
219
- );
220
- }
221
-
222
- return { results, errors, totalProcessed, totalFailed };
223
- }
224
-
225
- /**
226
- * Processes items sequentially (one at a time) with retry logic.
227
- * Useful for operations that don't support batching or when granular
228
- * error tracking is needed.
229
- */
230
- static async processSequential<T, R>(
231
- items: T[],
232
- processor: (item: T) => Promise<R>,
233
- options?: BatchOptions
234
- ): Promise<BatchResult<R>> {
235
- const {
236
- maxRetries = 3,
237
- initialDelayMs = 100,
238
- maxDelayMs = 10000,
239
- backoffMultiplier = 2,
240
- throwOnPartialFailure = false,
241
- } = options ?? {};
242
-
243
- const results: R[] = [];
244
- const errors: Array<{ index: number; error: Error; itemCount?: number }> = [];
245
-
246
- for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
247
- const item = items[itemIndex];
248
- let success = false;
249
- let lastError: Error | undefined;
250
-
251
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
252
- try {
253
- const result = await BatchProcessor.executeWithCircuitBreaker(() => processor(item));
254
- results.push(result);
255
- success = true;
256
- break;
257
- } catch (err) {
258
- lastError = err instanceof Error ? err : new Error(String(err));
259
-
260
- if (!isTransientError(err) || attempt === maxRetries) {
261
- break;
262
- }
263
-
264
- const delay = calculateBackoffDelay(
265
- attempt,
266
- initialDelayMs,
267
- maxDelayMs,
268
- backoffMultiplier
269
- );
270
- await sleep(delay);
271
- }
272
- }
273
-
274
- if (!success && lastError) {
275
- errors.push({ index: itemIndex, error: lastError, itemCount: 1 });
276
- }
277
- }
278
-
279
- const totalProcessed = items.length - errors.length;
280
- const totalFailed = errors.length;
281
-
282
- if (throwOnPartialFailure && errors.length > 0) {
283
- const errorMessages = errors
284
- .map((e) => `Item ${e.index}: ${e.error.message}`)
285
- .join('\n');
286
- throw new Error(
287
- `[BatchProcessor] Sequential processing failed:\n${errorMessages}`
288
- );
289
- }
290
-
291
- return { results, errors, totalProcessed, totalFailed };
292
- }
293
-
294
- /**
295
- * Maps over items with retry logic, returning results in order.
296
- * Like Array.map() but with async processing and automatic retries.
297
- */
298
- static async mapWithRetry<T, R>(
299
- items: T[],
300
- mapper: (item: T) => Promise<R>,
301
- options?: BatchOptions
302
- ): Promise<R[]> {
303
- const result = await this.processSequential(items, mapper, options);
304
-
305
- if (result.errors.length > 0) {
306
- console.warn(
307
- `[BatchProcessor] mapWithRetry: ${result.errors.length} items failed`
308
- );
309
- }
310
-
311
- // Return results in original order (fill gaps with undefined or error value)
312
- const orderedResults: (R | undefined)[] = new Array(items.length);
313
- let resultIndex = 0;
314
- let errorIndex = 0;
315
-
316
- for (let i = 0; i < items.length; i++) {
317
- if (errorIndex < result.errors.length && result.errors[errorIndex].index === i) {
318
- orderedResults[i] = undefined;
319
- errorIndex++;
320
- } else {
321
- orderedResults[i] = result.results[resultIndex];
322
- resultIndex++;
323
- }
324
- }
325
-
326
- return orderedResults.filter((r) => r !== undefined) as R[];
327
- }
328
-
329
- /**
330
- * Parallel processor with concurrency limit.
331
- * Processes up to `concurrency` items at the same time.
332
- */
333
- static async processConcurrent<T, R>(
334
- items: T[],
335
- processor: (item: T) => Promise<R>,
336
- concurrency: number = 5,
337
- options?: BatchOptions
338
- ): Promise<BatchResult<R>> {
339
- const { throwOnPartialFailure = false } = options ?? {};
340
- const results: R[] = [];
341
- const errors: Array<{ index: number; error: Error; itemCount?: number }> = [];
342
-
343
- // Process in chunks of `concurrency` size
344
- for (let i = 0; i < items.length; i += concurrency) {
345
- const chunk = items.slice(i, i + concurrency).map((item, idx) => ({
346
- item,
347
- originalIndex: i + idx,
348
- }));
349
-
350
- const chunkPromises = chunk.map(async ({ item, originalIndex }) => {
351
- try {
352
- const result = await BatchProcessor.executeWithCircuitBreaker(() => processor(item));
353
- return { success: true, result, index: originalIndex };
354
- } catch (err) {
355
- const error = err instanceof Error ? err : new Error(String(err));
356
- return { success: false, error, index: originalIndex };
357
- }
358
- });
359
-
360
- const chunkResults = await Promise.all(chunkPromises);
361
-
362
- for (const { success, result, error, index } of chunkResults) {
363
- if (success) {
364
- results.push(result as R);
365
- } else {
366
- errors.push({ index, error: error as Error, itemCount: 1 });
367
- }
368
- }
369
- }
370
-
371
- const totalProcessed = items.length - errors.length;
372
- const totalFailed = errors.length;
373
-
374
- if (throwOnPartialFailure && errors.length > 0) {
375
- const errorMessages = errors
376
- .map((e) => `Item ${e.index}: ${e.error.message}`)
377
- .join('\n');
378
- throw new Error(
379
- `[BatchProcessor] Concurrent processing failed:\n${errorMessages}`
380
- );
381
- }
382
-
383
- return { results, errors, totalProcessed, totalFailed };
384
- }
385
- }
@@ -1,118 +0,0 @@
1
- type CircuitState = 'closed' | 'open' | 'half-open';
2
-
3
- export interface CircuitBreakerOptions {
4
- failureThreshold?: number;
5
- resetTimeoutMs?: number;
6
- halfOpenMaxCalls?: number;
7
- }
8
-
9
- export class CircuitBreaker {
10
- private state: CircuitState = 'closed';
11
- private failureCount = 0;
12
- private successCount = 0;
13
- private lastFailureAt = 0;
14
- private halfOpenCalls = 0;
15
-
16
- private readonly failureThreshold: number;
17
- private readonly resetTimeoutMs: number;
18
- private readonly halfOpenMaxCalls: number;
19
-
20
- constructor(options: CircuitBreakerOptions = {}) {
21
- this.failureThreshold = options.failureThreshold ?? 5;
22
- this.resetTimeoutMs = options.resetTimeoutMs ?? 30_000;
23
- this.halfOpenMaxCalls = options.halfOpenMaxCalls ?? 1;
24
- }
25
-
26
- record(success: boolean): void {
27
- const now = Date.now();
28
-
29
- if (success) {
30
- this.successCount++;
31
- if (this.state === 'half-open') {
32
- this.state = 'closed';
33
- this.failureCount = 0;
34
- this.halfOpenCalls = 0;
35
- this.successCount = 1;
36
- } else if (this.state === 'closed') {
37
- if (this.successCount >= this.failureThreshold) {
38
- this.failureCount = Math.max(0, this.failureCount - 1);
39
- this.successCount = 0;
40
- }
41
- }
42
- } else {
43
- this.failureCount++;
44
- this.lastFailureAt = now;
45
- this.successCount = 0;
46
- if (this.state === 'half-open') {
47
- this.state = 'open';
48
- this.halfOpenCalls = 0;
49
- } else if (this.state === 'closed' && this.failureCount >= this.failureThreshold) {
50
- this.state = 'open';
51
- }
52
- }
53
- }
54
-
55
- canExecute(): boolean {
56
- const now = Date.now();
57
-
58
- if (this.state === 'closed') {
59
- return true;
60
- }
61
-
62
- if (this.state === 'open') {
63
- if (now - this.lastFailureAt >= this.resetTimeoutMs) {
64
- this.state = 'half-open';
65
- this.halfOpenCalls = 0;
66
- return true;
67
- }
68
- return false;
69
- }
70
-
71
- if (this.state === 'half-open') {
72
- return this.halfOpenCalls < this.halfOpenMaxCalls;
73
- }
74
-
75
- return true;
76
- }
77
-
78
- async wrap<T>(fn: () => Promise<T>): Promise<T> {
79
- if (!this.canExecute()) {
80
- const retryAfterSec = Math.ceil(
81
- Math.max(0, this.resetTimeoutMs - (Date.now() - this.lastFailureAt)) / 1000
82
- );
83
- throw new Error(
84
- `Circuit breaker is open. Try again in ${retryAfterSec}s. ` +
85
- `Failed ${this.failureCount}/${this.failureThreshold} consecutive calls.`
86
- );
87
- }
88
-
89
- if (this.state === 'half-open') {
90
- this.halfOpenCalls++;
91
- }
92
-
93
- try {
94
- const result = await fn();
95
- this.record(true);
96
- return result;
97
- } catch (err) {
98
- this.record(false);
99
- throw err;
100
- }
101
- }
102
-
103
- getState(): CircuitState {
104
- return this.state;
105
- }
106
-
107
- getFailureCount(): number {
108
- return this.failureCount;
109
- }
110
-
111
- reset(): void {
112
- this.state = 'closed';
113
- this.failureCount = 0;
114
- this.successCount = 0;
115
- this.lastFailureAt = 0;
116
- this.halfOpenCalls = 0;
117
- }
118
- }