@cmdoss/memwal-sdk 0.9.0 → 1.0.0

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 (174) hide show
  1. package/README.md +157 -52
  2. package/dist/client/ClientMemoryManager.d.ts.map +1 -1
  3. package/dist/client/ClientMemoryManager.js +25 -8
  4. package/dist/client/ClientMemoryManager.js.map +1 -1
  5. package/dist/client/PersonalDataWallet.d.ts.map +1 -1
  6. package/dist/client/SimplePDWClient.d.ts +2 -1
  7. package/dist/client/SimplePDWClient.d.ts.map +1 -1
  8. package/dist/client/SimplePDWClient.js +23 -6
  9. package/dist/client/SimplePDWClient.js.map +1 -1
  10. package/dist/client/namespaces/MemoryNamespace.d.ts +6 -0
  11. package/dist/client/namespaces/MemoryNamespace.d.ts.map +1 -1
  12. package/dist/client/namespaces/MemoryNamespace.js +131 -18
  13. package/dist/client/namespaces/MemoryNamespace.js.map +1 -1
  14. package/dist/client/namespaces/consolidated/StorageNamespace.d.ts +3 -1
  15. package/dist/client/namespaces/consolidated/StorageNamespace.d.ts.map +1 -1
  16. package/dist/client/namespaces/consolidated/StorageNamespace.js.map +1 -1
  17. package/dist/config/ConfigurationHelper.js +61 -61
  18. package/dist/config/index.d.ts +1 -0
  19. package/dist/config/index.d.ts.map +1 -1
  20. package/dist/config/index.js +2 -0
  21. package/dist/config/index.js.map +1 -1
  22. package/dist/config/modelDefaults.d.ts +67 -0
  23. package/dist/config/modelDefaults.d.ts.map +1 -0
  24. package/dist/config/modelDefaults.js +91 -0
  25. package/dist/config/modelDefaults.js.map +1 -0
  26. package/dist/graph/GraphService.d.ts.map +1 -1
  27. package/dist/graph/GraphService.js +22 -21
  28. package/dist/graph/GraphService.js.map +1 -1
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +1 -1
  32. package/dist/index.js.map +1 -1
  33. package/dist/langchain/createPDWRAG.js +30 -30
  34. package/dist/pipeline/MemoryPipeline.d.ts.map +1 -1
  35. package/dist/pipeline/MemoryPipeline.js +2 -1
  36. package/dist/pipeline/MemoryPipeline.js.map +1 -1
  37. package/dist/services/GeminiAIService.d.ts.map +1 -1
  38. package/dist/services/GeminiAIService.js +311 -310
  39. package/dist/services/GeminiAIService.js.map +1 -1
  40. package/dist/services/StorageService.d.ts +4 -1
  41. package/dist/services/StorageService.d.ts.map +1 -1
  42. package/dist/services/StorageService.js.map +1 -1
  43. package/dist/services/storage/QuiltBatchManager.d.ts +7 -0
  44. package/dist/services/storage/QuiltBatchManager.d.ts.map +1 -1
  45. package/dist/services/storage/QuiltBatchManager.js +24 -5
  46. package/dist/services/storage/QuiltBatchManager.js.map +1 -1
  47. package/dist/services/storage/WalrusStorageManager.d.ts +10 -1
  48. package/dist/services/storage/WalrusStorageManager.d.ts.map +1 -1
  49. package/dist/services/storage/WalrusStorageManager.js +53 -12
  50. package/dist/services/storage/WalrusStorageManager.js.map +1 -1
  51. package/dist/vector/BrowserHnswIndexService.js +2 -2
  52. package/dist/vector/BrowserHnswIndexService.js.map +1 -1
  53. package/dist/vector/NodeHnswService.js +4 -4
  54. package/dist/vector/NodeHnswService.js.map +1 -1
  55. package/dist/vector/createHnswService.d.ts +4 -0
  56. package/dist/vector/createHnswService.d.ts.map +1 -1
  57. package/dist/vector/createHnswService.js +15 -3
  58. package/dist/vector/createHnswService.js.map +1 -1
  59. package/package.json +1 -1
  60. package/src/access/PermissionService.ts +635 -635
  61. package/src/aggregation/AggregationService.ts +389 -389
  62. package/src/ai-sdk/PDWVectorStore.ts +715 -715
  63. package/src/ai-sdk/index.ts +65 -65
  64. package/src/ai-sdk/tools.ts +460 -460
  65. package/src/ai-sdk/types.ts +404 -404
  66. package/src/batch/BatchManager.ts +597 -597
  67. package/src/batch/BatchingService.ts +429 -429
  68. package/src/batch/MemoryProcessingCache.ts +492 -492
  69. package/src/batch/index.ts +30 -30
  70. package/src/browser.ts +200 -200
  71. package/src/client/ClientMemoryManager.ts +1004 -987
  72. package/src/client/PersonalDataWallet.ts +345 -345
  73. package/src/client/SimplePDWClient.ts +1387 -1369
  74. package/src/client/factory.ts +154 -154
  75. package/src/client/namespaces/AnalyticsNamespace.ts +377 -377
  76. package/src/client/namespaces/BatchNamespace.ts +356 -356
  77. package/src/client/namespaces/CacheNamespace.ts +123 -123
  78. package/src/client/namespaces/CapabilityNamespace.ts +217 -217
  79. package/src/client/namespaces/ClassifyNamespace.ts +169 -169
  80. package/src/client/namespaces/ContextNamespace.ts +297 -297
  81. package/src/client/namespaces/EncryptionNamespace.ts +221 -221
  82. package/src/client/namespaces/GraphNamespace.ts +468 -468
  83. package/src/client/namespaces/IndexNamespace.ts +364 -364
  84. package/src/client/namespaces/MemoryNamespace.ts +1704 -1569
  85. package/src/client/namespaces/PermissionsNamespace.ts +254 -254
  86. package/src/client/namespaces/PipelineNamespace.ts +220 -220
  87. package/src/client/namespaces/StorageNamespace.ts +458 -458
  88. package/src/client/namespaces/TxNamespace.ts +260 -260
  89. package/src/client/namespaces/WalletNamespace.ts +243 -243
  90. package/src/client/namespaces/consolidated/BlockchainNamespace.ts +607 -607
  91. package/src/client/namespaces/consolidated/SecurityNamespace.ts +648 -648
  92. package/src/client/namespaces/consolidated/StorageNamespace.ts +1143 -1141
  93. package/src/client/namespaces/consolidated/index.ts +41 -41
  94. package/src/client/signers/KeypairSigner.ts +108 -108
  95. package/src/client/signers/UnifiedSigner.ts +110 -110
  96. package/src/client/signers/WalletAdapterSigner.ts +159 -159
  97. package/src/client/signers/index.ts +26 -26
  98. package/src/config/ConfigurationHelper.ts +412 -412
  99. package/src/config/defaults.ts +56 -56
  100. package/src/config/index.ts +16 -9
  101. package/src/config/modelDefaults.ts +103 -0
  102. package/src/config/validation.ts +70 -70
  103. package/src/core/index.ts +14 -14
  104. package/src/core/interfaces/IService.ts +307 -307
  105. package/src/core/interfaces/index.ts +8 -8
  106. package/src/core/types/capability.ts +297 -297
  107. package/src/core/types/index.ts +874 -874
  108. package/src/core/types/wallet.ts +270 -270
  109. package/src/core/types.ts +9 -9
  110. package/src/core/wallet.ts +222 -222
  111. package/src/embedding/index.ts +19 -19
  112. package/src/embedding/types.ts +357 -357
  113. package/src/errors/index.ts +602 -602
  114. package/src/errors/recovery.ts +461 -461
  115. package/src/errors/validation.ts +567 -567
  116. package/src/generated/pdw/capability.ts +319 -319
  117. package/src/graph/GraphService.ts +888 -887
  118. package/src/graph/KnowledgeGraphManager.ts +728 -728
  119. package/src/graph/index.ts +25 -25
  120. package/src/index.ts +498 -498
  121. package/src/infrastructure/index.ts +22 -22
  122. package/src/infrastructure/seal/EncryptionService.ts +628 -628
  123. package/src/infrastructure/seal/SealService.ts +613 -613
  124. package/src/infrastructure/seal/index.ts +9 -9
  125. package/src/infrastructure/sui/BlockchainManager.ts +627 -627
  126. package/src/infrastructure/sui/SuiService.ts +888 -888
  127. package/src/infrastructure/sui/index.ts +9 -9
  128. package/src/infrastructure/walrus/StorageManager.ts +604 -604
  129. package/src/infrastructure/walrus/WalrusStorageService.ts +637 -637
  130. package/src/infrastructure/walrus/index.ts +9 -9
  131. package/src/langchain/createPDWRAG.ts +303 -303
  132. package/src/langchain/index.ts +47 -47
  133. package/src/permissions/ConsentRepository.browser.ts +249 -249
  134. package/src/permissions/ConsentRepository.ts +364 -364
  135. package/src/pipeline/MemoryPipeline.ts +863 -862
  136. package/src/pipeline/PipelineManager.ts +683 -683
  137. package/src/pipeline/index.ts +26 -26
  138. package/src/retrieval/AdvancedSearchService.ts +629 -629
  139. package/src/retrieval/MemoryAnalyticsService.ts +711 -711
  140. package/src/retrieval/MemoryDecryptionPipeline.ts +825 -825
  141. package/src/retrieval/index.ts +42 -42
  142. package/src/services/BatchService.ts +352 -352
  143. package/src/services/CapabilityService.ts +464 -464
  144. package/src/services/ClassifierService.ts +465 -465
  145. package/src/services/CrossContextPermissionService.ts +486 -486
  146. package/src/services/EmbeddingService.ts +796 -796
  147. package/src/services/EncryptionService.ts +712 -712
  148. package/src/services/GeminiAIService.ts +754 -753
  149. package/src/services/MemoryIndexService.ts +1009 -1009
  150. package/src/services/MemoryService.ts +369 -369
  151. package/src/services/QueryService.ts +890 -890
  152. package/src/services/StorageService.ts +1185 -1182
  153. package/src/services/TransactionService.ts +838 -838
  154. package/src/services/VectorService.ts +462 -462
  155. package/src/services/ViewService.ts +484 -484
  156. package/src/services/index.ts +25 -25
  157. package/src/services/storage/BlobAttributesManager.ts +333 -333
  158. package/src/services/storage/KnowledgeGraphManager.ts +425 -425
  159. package/src/services/storage/MemorySearchManager.ts +387 -387
  160. package/src/services/storage/QuiltBatchManager.ts +1157 -1130
  161. package/src/services/storage/WalrusMetadataManager.ts +268 -268
  162. package/src/services/storage/WalrusStorageManager.ts +333 -287
  163. package/src/services/storage/index.ts +57 -57
  164. package/src/types/index.ts +13 -13
  165. package/src/utils/index.ts +76 -76
  166. package/src/utils/memoryIndexOnChain.ts +507 -507
  167. package/src/vector/BrowserHnswIndexService.ts +758 -758
  168. package/src/vector/HnswWasmService.ts +731 -731
  169. package/src/vector/IHnswService.ts +233 -233
  170. package/src/vector/NodeHnswService.ts +833 -833
  171. package/src/vector/createHnswService.ts +147 -135
  172. package/src/vector/index.ts +56 -56
  173. package/src/wallet/ContextWalletService.ts +656 -656
  174. package/src/wallet/MainWalletService.ts +317 -317
@@ -1,462 +1,462 @@
1
- /**
2
- * Retry and Recovery Utilities for Personal Data Wallet SDK
3
- *
4
- * Provides automatic retry logic, circuit breaker patterns,
5
- * and error recovery strategies for resilient operations.
6
- */
7
-
8
- import { PDWError, isPDWError, NetworkError, TimeoutError, ValidationError } from './index';
9
-
10
- // ==================== RETRY CONFIGURATION ====================
11
-
12
- export interface RetryConfig {
13
- /** Maximum number of retry attempts */
14
- maxAttempts: number;
15
- /** Initial delay between retries in milliseconds */
16
- initialDelay: number;
17
- /** Maximum delay between retries in milliseconds */
18
- maxDelay: number;
19
- /** Backoff multiplier for exponential backoff */
20
- backoffMultiplier: number;
21
- /** Whether to add random jitter to delays */
22
- jitter: boolean;
23
- /** Function to determine if error should be retried */
24
- shouldRetry?: (error: any, attempt: number) => boolean;
25
- /** Function called before each retry attempt */
26
- onRetry?: (error: any, attempt: number, delay: number) => void;
27
- }
28
-
29
- export const DEFAULT_RETRY_CONFIG: RetryConfig = {
30
- maxAttempts: 3,
31
- initialDelay: 1000,
32
- maxDelay: 10000,
33
- backoffMultiplier: 2,
34
- jitter: true,
35
- shouldRetry: (error: any) => {
36
- if (isPDWError(error)) {
37
- return error.isRetryable();
38
- }
39
- // Retry network errors, timeouts, and temporary failures
40
- return error?.code === 'ECONNRESET' ||
41
- error?.code === 'ENOTFOUND' ||
42
- error?.code === 'TIMEOUT' ||
43
- error?.status >= 500;
44
- },
45
- onRetry: (error, attempt, delay) => {
46
- console.warn(`Retry attempt ${attempt} after ${delay}ms due to:`, error.message);
47
- },
48
- };
49
-
50
- // ==================== RETRY FUNCTION ====================
51
-
52
- /**
53
- * Execute a function with automatic retry logic
54
- */
55
- export async function withRetry<T>(
56
- operation: () => Promise<T>,
57
- config: Partial<RetryConfig> = {}
58
- ): Promise<T> {
59
- const finalConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
60
- let lastError: any;
61
-
62
- for (let attempt = 1; attempt <= finalConfig.maxAttempts; attempt++) {
63
- try {
64
- return await operation();
65
- } catch (error) {
66
- lastError = error;
67
-
68
- // Check if we should retry
69
- if (attempt >= finalConfig.maxAttempts ||
70
- !finalConfig.shouldRetry!(error, attempt)) {
71
- throw error;
72
- }
73
-
74
- // Calculate delay with exponential backoff and jitter
75
- const baseDelay = Math.min(
76
- finalConfig.initialDelay * Math.pow(finalConfig.backoffMultiplier, attempt - 1),
77
- finalConfig.maxDelay
78
- );
79
-
80
- const jitter = finalConfig.jitter ?
81
- Math.random() * 0.1 * baseDelay : 0;
82
-
83
- const delay = Math.floor(baseDelay + jitter);
84
-
85
- // Call retry callback
86
- if (finalConfig.onRetry) {
87
- finalConfig.onRetry(error, attempt, delay);
88
- }
89
-
90
- // Wait before retrying
91
- await new Promise(resolve => setTimeout(resolve, delay));
92
- }
93
- }
94
-
95
- throw lastError;
96
- }
97
-
98
- // ==================== CIRCUIT BREAKER ====================
99
-
100
- export interface CircuitBreakerConfig {
101
- /** Number of failures before opening circuit */
102
- failureThreshold: number;
103
- /** Time in milliseconds to wait before attempting to close circuit */
104
- resetTimeout: number;
105
- /** Minimum number of calls before circuit can open */
106
- minimumCalls: number;
107
- /** Success ratio threshold to close circuit (0-1) */
108
- successThreshold: number;
109
- }
110
-
111
- export enum CircuitState {
112
- CLOSED = 'CLOSED',
113
- OPEN = 'OPEN',
114
- HALF_OPEN = 'HALF_OPEN',
115
- }
116
-
117
- export class CircuitBreaker {
118
- private state = CircuitState.CLOSED;
119
- private failureCount = 0;
120
- private successCount = 0;
121
- private totalCalls = 0;
122
- private lastFailureTime = 0;
123
- private readonly config: CircuitBreakerConfig;
124
-
125
- constructor(config: Partial<CircuitBreakerConfig> = {}) {
126
- this.config = {
127
- failureThreshold: 5,
128
- resetTimeout: 30000,
129
- minimumCalls: 10,
130
- successThreshold: 0.8,
131
- ...config,
132
- };
133
- }
134
-
135
- async execute<T>(operation: () => Promise<T>): Promise<T> {
136
- if (this.state === CircuitState.OPEN) {
137
- if (Date.now() - this.lastFailureTime > this.config.resetTimeout) {
138
- this.state = CircuitState.HALF_OPEN;
139
- this.successCount = 0;
140
- this.totalCalls = 0;
141
- } else {
142
- throw new NetworkError(
143
- 'Circuit breaker is open - service temporarily unavailable',
144
- 'CIRCUIT_BREAKER_OPEN'
145
- );
146
- }
147
- }
148
-
149
- try {
150
- const result = await operation();
151
- this.onSuccess();
152
- return result;
153
- } catch (error) {
154
- this.onFailure();
155
- throw error;
156
- }
157
- }
158
-
159
- private onSuccess(): void {
160
- this.successCount++;
161
- this.totalCalls++;
162
-
163
- if (this.state === CircuitState.HALF_OPEN) {
164
- const successRatio = this.successCount / this.totalCalls;
165
- if (this.totalCalls >= this.config.minimumCalls &&
166
- successRatio >= this.config.successThreshold) {
167
- this.reset();
168
- }
169
- } else {
170
- this.failureCount = 0;
171
- }
172
- }
173
-
174
- private onFailure(): void {
175
- this.failureCount++;
176
- this.totalCalls++;
177
- this.lastFailureTime = Date.now();
178
-
179
- if (this.state === CircuitState.HALF_OPEN) {
180
- this.state = CircuitState.OPEN;
181
- } else if (this.failureCount >= this.config.failureThreshold &&
182
- this.totalCalls >= this.config.minimumCalls) {
183
- this.state = CircuitState.OPEN;
184
- }
185
- }
186
-
187
- private reset(): void {
188
- this.state = CircuitState.CLOSED;
189
- this.failureCount = 0;
190
- this.successCount = 0;
191
- this.totalCalls = 0;
192
- }
193
-
194
- getState(): CircuitState {
195
- return this.state;
196
- }
197
-
198
- getMetrics() {
199
- return {
200
- state: this.state,
201
- failureCount: this.failureCount,
202
- successCount: this.successCount,
203
- totalCalls: this.totalCalls,
204
- lastFailureTime: this.lastFailureTime,
205
- };
206
- }
207
- }
208
-
209
- // ==================== RATE LIMITER ====================
210
-
211
- export class RateLimiter {
212
- private tokens: number;
213
- private lastRefill: number;
214
- private readonly capacity: number;
215
- private readonly refillRate: number; // tokens per second
216
-
217
- constructor(capacity: number, refillRate: number) {
218
- this.capacity = capacity;
219
- this.refillRate = refillRate;
220
- this.tokens = capacity;
221
- this.lastRefill = Date.now();
222
- }
223
-
224
- async acquire(tokens = 1): Promise<void> {
225
- this.refill();
226
-
227
- if (this.tokens >= tokens) {
228
- this.tokens -= tokens;
229
- return;
230
- }
231
-
232
- // Wait for tokens to be available
233
- const tokensNeeded = tokens - this.tokens;
234
- const waitTime = (tokensNeeded / this.refillRate) * 1000;
235
-
236
- await new Promise(resolve => setTimeout(resolve, waitTime));
237
-
238
- this.refill();
239
- this.tokens -= tokens;
240
- }
241
-
242
- private refill(): void {
243
- const now = Date.now();
244
- const timePassed = (now - this.lastRefill) / 1000;
245
- const tokensToAdd = timePassed * this.refillRate;
246
-
247
- this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);
248
- this.lastRefill = now;
249
- }
250
-
251
- getTokens(): number {
252
- this.refill();
253
- return this.tokens;
254
- }
255
- }
256
-
257
- // ==================== RECOVERY STRATEGIES ====================
258
-
259
- export interface RecoveryStrategy<T> {
260
- canRecover(error: any): boolean;
261
- recover(error: any, originalOperation: () => Promise<T>): Promise<T>;
262
- }
263
-
264
- export class FallbackRecovery<T> implements RecoveryStrategy<T> {
265
- constructor(
266
- private fallbackOperation: (error: any) => Promise<T>,
267
- private canRecoverFn: (error: any) => boolean = () => true
268
- ) {}
269
-
270
- canRecover(error: any): boolean {
271
- return this.canRecoverFn(error);
272
- }
273
-
274
- async recover(error: any): Promise<T> {
275
- return this.fallbackOperation(error);
276
- }
277
- }
278
-
279
- export class CacheRecovery<T> implements RecoveryStrategy<T> {
280
- private cache = new Map<string, { data: T; timestamp: number }>();
281
-
282
- constructor(
283
- private keyGenerator: (...args: any[]) => string,
284
- private ttl: number = 300000 // 5 minutes
285
- ) {}
286
-
287
- canRecover(error: any): boolean {
288
- return isPDWError(error) &&
289
- (error.code === 'NETWORK_ERROR' ||
290
- error.code === 'TIMEOUT_ERROR' ||
291
- error.code === 'CONNECTION_ERROR');
292
- }
293
-
294
- async recover(error: any, originalOperation: () => Promise<T>): Promise<T> {
295
- // This is a simplified recovery - in practice, you'd need access to the original arguments
296
- throw new Error('Cache recovery requires implementation context');
297
- }
298
-
299
- setCacheEntry(key: string, data: T): void {
300
- this.cache.set(key, {
301
- data,
302
- timestamp: Date.now(),
303
- });
304
- }
305
-
306
- getCacheEntry(key: string): T | null {
307
- const entry = this.cache.get(key);
308
- if (!entry) {
309
- return null;
310
- }
311
-
312
- if (Date.now() - entry.timestamp > this.ttl) {
313
- this.cache.delete(key);
314
- return null;
315
- }
316
-
317
- return entry.data;
318
- }
319
- }
320
-
321
- // ==================== RESILIENT OPERATION WRAPPER ====================
322
-
323
- export interface ResilienceConfig {
324
- retry?: Partial<RetryConfig>;
325
- circuitBreaker?: Partial<CircuitBreakerConfig>;
326
- rateLimiter?: { capacity: number; refillRate: number };
327
- recoveryStrategies?: RecoveryStrategy<any>[];
328
- }
329
-
330
- export class ResilientOperation<T> {
331
- private circuitBreaker?: CircuitBreaker;
332
- private rateLimiter?: RateLimiter;
333
- private retryConfig: RetryConfig;
334
- private recoveryStrategies: RecoveryStrategy<T>[];
335
-
336
- constructor(config: ResilienceConfig = {}) {
337
- this.retryConfig = { ...DEFAULT_RETRY_CONFIG, ...config.retry };
338
-
339
- if (config.circuitBreaker) {
340
- this.circuitBreaker = new CircuitBreaker(config.circuitBreaker);
341
- }
342
-
343
- if (config.rateLimiter) {
344
- this.rateLimiter = new RateLimiter(
345
- config.rateLimiter.capacity,
346
- config.rateLimiter.refillRate
347
- );
348
- }
349
-
350
- this.recoveryStrategies = config.recoveryStrategies || [];
351
- }
352
-
353
- async execute(operation: () => Promise<T>): Promise<T> {
354
- // Apply rate limiting
355
- if (this.rateLimiter) {
356
- await this.rateLimiter.acquire();
357
- }
358
-
359
- const executeWithCircuitBreaker = this.circuitBreaker ?
360
- () => this.circuitBreaker!.execute(operation) :
361
- operation;
362
-
363
- try {
364
- return await withRetry(executeWithCircuitBreaker, this.retryConfig);
365
- } catch (error) {
366
- // Try recovery strategies
367
- for (const strategy of this.recoveryStrategies) {
368
- if (strategy.canRecover(error)) {
369
- try {
370
- return await strategy.recover(error, operation);
371
- } catch (recoveryError) {
372
- // If recovery fails, continue to next strategy
373
- continue;
374
- }
375
- }
376
- }
377
-
378
- // If no recovery worked, throw the original error
379
- throw error;
380
- }
381
- }
382
- }
383
-
384
- // ==================== UTILITY FUNCTIONS ====================
385
-
386
- /**
387
- * Create a resilient version of an async function
388
- */
389
- export function makeResilient<T extends any[], R>(
390
- fn: (...args: T) => Promise<R>,
391
- config: ResilienceConfig = {}
392
- ): (...args: T) => Promise<R> {
393
- const resilientOp = new ResilientOperation<R>(config);
394
-
395
- return (...args: T) => {
396
- return resilientOp.execute(() => fn(...args));
397
- };
398
- }
399
-
400
- /**
401
- * Delay execution for a specified time
402
- */
403
- export function delay(ms: number): Promise<void> {
404
- return new Promise(resolve => setTimeout(resolve, ms));
405
- }
406
-
407
- /**
408
- * Create a timeout wrapper for promises
409
- */
410
- export function withTimeout<T>(
411
- promise: Promise<T>,
412
- timeoutMs: number,
413
- timeoutMessage = 'Operation timed out'
414
- ): Promise<T> {
415
- const timeoutPromise = new Promise<never>((_, reject) => {
416
- setTimeout(() => {
417
- reject(new TimeoutError('operation', timeoutMs));
418
- }, timeoutMs);
419
- });
420
-
421
- return Promise.race([promise, timeoutPromise]);
422
- }
423
-
424
- /**
425
- * Batch operations with concurrency control
426
- */
427
- export async function batch<T, R>(
428
- items: T[],
429
- operation: (item: T, index: number) => Promise<R>,
430
- concurrency = 5
431
- ): Promise<R[]> {
432
- const results: R[] = [];
433
- const errors: Array<{ index: number; error: any }> = [];
434
-
435
- for (let i = 0; i < items.length; i += concurrency) {
436
- const batch = items.slice(i, i + concurrency);
437
- const promises = batch.map((item, batchIndex) =>
438
- operation(item, i + batchIndex)
439
- .catch(error => ({ error, index: i + batchIndex }))
440
- );
441
-
442
- const batchResults = await Promise.all(promises);
443
-
444
- batchResults.forEach((result, batchIndex) => {
445
- if (result && typeof result === 'object' && 'error' in result) {
446
- errors.push(result as { index: number; error: any });
447
- } else {
448
- results[i + batchIndex] = result as R;
449
- }
450
- });
451
- }
452
-
453
- if (errors.length > 0) {
454
- throw new ValidationError(
455
- `Batch operation failed for ${errors.length} items`,
456
- 'batch',
457
- { errors: errors.map(e => ({ index: e.index, message: e.error.message })) }
458
- );
459
- }
460
-
461
- return results;
1
+ /**
2
+ * Retry and Recovery Utilities for Personal Data Wallet SDK
3
+ *
4
+ * Provides automatic retry logic, circuit breaker patterns,
5
+ * and error recovery strategies for resilient operations.
6
+ */
7
+
8
+ import { PDWError, isPDWError, NetworkError, TimeoutError, ValidationError } from './index';
9
+
10
+ // ==================== RETRY CONFIGURATION ====================
11
+
12
+ export interface RetryConfig {
13
+ /** Maximum number of retry attempts */
14
+ maxAttempts: number;
15
+ /** Initial delay between retries in milliseconds */
16
+ initialDelay: number;
17
+ /** Maximum delay between retries in milliseconds */
18
+ maxDelay: number;
19
+ /** Backoff multiplier for exponential backoff */
20
+ backoffMultiplier: number;
21
+ /** Whether to add random jitter to delays */
22
+ jitter: boolean;
23
+ /** Function to determine if error should be retried */
24
+ shouldRetry?: (error: any, attempt: number) => boolean;
25
+ /** Function called before each retry attempt */
26
+ onRetry?: (error: any, attempt: number, delay: number) => void;
27
+ }
28
+
29
+ export const DEFAULT_RETRY_CONFIG: RetryConfig = {
30
+ maxAttempts: 3,
31
+ initialDelay: 1000,
32
+ maxDelay: 10000,
33
+ backoffMultiplier: 2,
34
+ jitter: true,
35
+ shouldRetry: (error: any) => {
36
+ if (isPDWError(error)) {
37
+ return error.isRetryable();
38
+ }
39
+ // Retry network errors, timeouts, and temporary failures
40
+ return error?.code === 'ECONNRESET' ||
41
+ error?.code === 'ENOTFOUND' ||
42
+ error?.code === 'TIMEOUT' ||
43
+ error?.status >= 500;
44
+ },
45
+ onRetry: (error, attempt, delay) => {
46
+ console.warn(`Retry attempt ${attempt} after ${delay}ms due to:`, error.message);
47
+ },
48
+ };
49
+
50
+ // ==================== RETRY FUNCTION ====================
51
+
52
+ /**
53
+ * Execute a function with automatic retry logic
54
+ */
55
+ export async function withRetry<T>(
56
+ operation: () => Promise<T>,
57
+ config: Partial<RetryConfig> = {}
58
+ ): Promise<T> {
59
+ const finalConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
60
+ let lastError: any;
61
+
62
+ for (let attempt = 1; attempt <= finalConfig.maxAttempts; attempt++) {
63
+ try {
64
+ return await operation();
65
+ } catch (error) {
66
+ lastError = error;
67
+
68
+ // Check if we should retry
69
+ if (attempt >= finalConfig.maxAttempts ||
70
+ !finalConfig.shouldRetry!(error, attempt)) {
71
+ throw error;
72
+ }
73
+
74
+ // Calculate delay with exponential backoff and jitter
75
+ const baseDelay = Math.min(
76
+ finalConfig.initialDelay * Math.pow(finalConfig.backoffMultiplier, attempt - 1),
77
+ finalConfig.maxDelay
78
+ );
79
+
80
+ const jitter = finalConfig.jitter ?
81
+ Math.random() * 0.1 * baseDelay : 0;
82
+
83
+ const delay = Math.floor(baseDelay + jitter);
84
+
85
+ // Call retry callback
86
+ if (finalConfig.onRetry) {
87
+ finalConfig.onRetry(error, attempt, delay);
88
+ }
89
+
90
+ // Wait before retrying
91
+ await new Promise(resolve => setTimeout(resolve, delay));
92
+ }
93
+ }
94
+
95
+ throw lastError;
96
+ }
97
+
98
+ // ==================== CIRCUIT BREAKER ====================
99
+
100
+ export interface CircuitBreakerConfig {
101
+ /** Number of failures before opening circuit */
102
+ failureThreshold: number;
103
+ /** Time in milliseconds to wait before attempting to close circuit */
104
+ resetTimeout: number;
105
+ /** Minimum number of calls before circuit can open */
106
+ minimumCalls: number;
107
+ /** Success ratio threshold to close circuit (0-1) */
108
+ successThreshold: number;
109
+ }
110
+
111
+ export enum CircuitState {
112
+ CLOSED = 'CLOSED',
113
+ OPEN = 'OPEN',
114
+ HALF_OPEN = 'HALF_OPEN',
115
+ }
116
+
117
+ export class CircuitBreaker {
118
+ private state = CircuitState.CLOSED;
119
+ private failureCount = 0;
120
+ private successCount = 0;
121
+ private totalCalls = 0;
122
+ private lastFailureTime = 0;
123
+ private readonly config: CircuitBreakerConfig;
124
+
125
+ constructor(config: Partial<CircuitBreakerConfig> = {}) {
126
+ this.config = {
127
+ failureThreshold: 5,
128
+ resetTimeout: 30000,
129
+ minimumCalls: 10,
130
+ successThreshold: 0.8,
131
+ ...config,
132
+ };
133
+ }
134
+
135
+ async execute<T>(operation: () => Promise<T>): Promise<T> {
136
+ if (this.state === CircuitState.OPEN) {
137
+ if (Date.now() - this.lastFailureTime > this.config.resetTimeout) {
138
+ this.state = CircuitState.HALF_OPEN;
139
+ this.successCount = 0;
140
+ this.totalCalls = 0;
141
+ } else {
142
+ throw new NetworkError(
143
+ 'Circuit breaker is open - service temporarily unavailable',
144
+ 'CIRCUIT_BREAKER_OPEN'
145
+ );
146
+ }
147
+ }
148
+
149
+ try {
150
+ const result = await operation();
151
+ this.onSuccess();
152
+ return result;
153
+ } catch (error) {
154
+ this.onFailure();
155
+ throw error;
156
+ }
157
+ }
158
+
159
+ private onSuccess(): void {
160
+ this.successCount++;
161
+ this.totalCalls++;
162
+
163
+ if (this.state === CircuitState.HALF_OPEN) {
164
+ const successRatio = this.successCount / this.totalCalls;
165
+ if (this.totalCalls >= this.config.minimumCalls &&
166
+ successRatio >= this.config.successThreshold) {
167
+ this.reset();
168
+ }
169
+ } else {
170
+ this.failureCount = 0;
171
+ }
172
+ }
173
+
174
+ private onFailure(): void {
175
+ this.failureCount++;
176
+ this.totalCalls++;
177
+ this.lastFailureTime = Date.now();
178
+
179
+ if (this.state === CircuitState.HALF_OPEN) {
180
+ this.state = CircuitState.OPEN;
181
+ } else if (this.failureCount >= this.config.failureThreshold &&
182
+ this.totalCalls >= this.config.minimumCalls) {
183
+ this.state = CircuitState.OPEN;
184
+ }
185
+ }
186
+
187
+ private reset(): void {
188
+ this.state = CircuitState.CLOSED;
189
+ this.failureCount = 0;
190
+ this.successCount = 0;
191
+ this.totalCalls = 0;
192
+ }
193
+
194
+ getState(): CircuitState {
195
+ return this.state;
196
+ }
197
+
198
+ getMetrics() {
199
+ return {
200
+ state: this.state,
201
+ failureCount: this.failureCount,
202
+ successCount: this.successCount,
203
+ totalCalls: this.totalCalls,
204
+ lastFailureTime: this.lastFailureTime,
205
+ };
206
+ }
207
+ }
208
+
209
+ // ==================== RATE LIMITER ====================
210
+
211
+ export class RateLimiter {
212
+ private tokens: number;
213
+ private lastRefill: number;
214
+ private readonly capacity: number;
215
+ private readonly refillRate: number; // tokens per second
216
+
217
+ constructor(capacity: number, refillRate: number) {
218
+ this.capacity = capacity;
219
+ this.refillRate = refillRate;
220
+ this.tokens = capacity;
221
+ this.lastRefill = Date.now();
222
+ }
223
+
224
+ async acquire(tokens = 1): Promise<void> {
225
+ this.refill();
226
+
227
+ if (this.tokens >= tokens) {
228
+ this.tokens -= tokens;
229
+ return;
230
+ }
231
+
232
+ // Wait for tokens to be available
233
+ const tokensNeeded = tokens - this.tokens;
234
+ const waitTime = (tokensNeeded / this.refillRate) * 1000;
235
+
236
+ await new Promise(resolve => setTimeout(resolve, waitTime));
237
+
238
+ this.refill();
239
+ this.tokens -= tokens;
240
+ }
241
+
242
+ private refill(): void {
243
+ const now = Date.now();
244
+ const timePassed = (now - this.lastRefill) / 1000;
245
+ const tokensToAdd = timePassed * this.refillRate;
246
+
247
+ this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);
248
+ this.lastRefill = now;
249
+ }
250
+
251
+ getTokens(): number {
252
+ this.refill();
253
+ return this.tokens;
254
+ }
255
+ }
256
+
257
+ // ==================== RECOVERY STRATEGIES ====================
258
+
259
+ export interface RecoveryStrategy<T> {
260
+ canRecover(error: any): boolean;
261
+ recover(error: any, originalOperation: () => Promise<T>): Promise<T>;
262
+ }
263
+
264
+ export class FallbackRecovery<T> implements RecoveryStrategy<T> {
265
+ constructor(
266
+ private fallbackOperation: (error: any) => Promise<T>,
267
+ private canRecoverFn: (error: any) => boolean = () => true
268
+ ) {}
269
+
270
+ canRecover(error: any): boolean {
271
+ return this.canRecoverFn(error);
272
+ }
273
+
274
+ async recover(error: any): Promise<T> {
275
+ return this.fallbackOperation(error);
276
+ }
277
+ }
278
+
279
+ export class CacheRecovery<T> implements RecoveryStrategy<T> {
280
+ private cache = new Map<string, { data: T; timestamp: number }>();
281
+
282
+ constructor(
283
+ private keyGenerator: (...args: any[]) => string,
284
+ private ttl: number = 300000 // 5 minutes
285
+ ) {}
286
+
287
+ canRecover(error: any): boolean {
288
+ return isPDWError(error) &&
289
+ (error.code === 'NETWORK_ERROR' ||
290
+ error.code === 'TIMEOUT_ERROR' ||
291
+ error.code === 'CONNECTION_ERROR');
292
+ }
293
+
294
+ async recover(error: any, originalOperation: () => Promise<T>): Promise<T> {
295
+ // This is a simplified recovery - in practice, you'd need access to the original arguments
296
+ throw new Error('Cache recovery requires implementation context');
297
+ }
298
+
299
+ setCacheEntry(key: string, data: T): void {
300
+ this.cache.set(key, {
301
+ data,
302
+ timestamp: Date.now(),
303
+ });
304
+ }
305
+
306
+ getCacheEntry(key: string): T | null {
307
+ const entry = this.cache.get(key);
308
+ if (!entry) {
309
+ return null;
310
+ }
311
+
312
+ if (Date.now() - entry.timestamp > this.ttl) {
313
+ this.cache.delete(key);
314
+ return null;
315
+ }
316
+
317
+ return entry.data;
318
+ }
319
+ }
320
+
321
+ // ==================== RESILIENT OPERATION WRAPPER ====================
322
+
323
+ export interface ResilienceConfig {
324
+ retry?: Partial<RetryConfig>;
325
+ circuitBreaker?: Partial<CircuitBreakerConfig>;
326
+ rateLimiter?: { capacity: number; refillRate: number };
327
+ recoveryStrategies?: RecoveryStrategy<any>[];
328
+ }
329
+
330
+ export class ResilientOperation<T> {
331
+ private circuitBreaker?: CircuitBreaker;
332
+ private rateLimiter?: RateLimiter;
333
+ private retryConfig: RetryConfig;
334
+ private recoveryStrategies: RecoveryStrategy<T>[];
335
+
336
+ constructor(config: ResilienceConfig = {}) {
337
+ this.retryConfig = { ...DEFAULT_RETRY_CONFIG, ...config.retry };
338
+
339
+ if (config.circuitBreaker) {
340
+ this.circuitBreaker = new CircuitBreaker(config.circuitBreaker);
341
+ }
342
+
343
+ if (config.rateLimiter) {
344
+ this.rateLimiter = new RateLimiter(
345
+ config.rateLimiter.capacity,
346
+ config.rateLimiter.refillRate
347
+ );
348
+ }
349
+
350
+ this.recoveryStrategies = config.recoveryStrategies || [];
351
+ }
352
+
353
+ async execute(operation: () => Promise<T>): Promise<T> {
354
+ // Apply rate limiting
355
+ if (this.rateLimiter) {
356
+ await this.rateLimiter.acquire();
357
+ }
358
+
359
+ const executeWithCircuitBreaker = this.circuitBreaker ?
360
+ () => this.circuitBreaker!.execute(operation) :
361
+ operation;
362
+
363
+ try {
364
+ return await withRetry(executeWithCircuitBreaker, this.retryConfig);
365
+ } catch (error) {
366
+ // Try recovery strategies
367
+ for (const strategy of this.recoveryStrategies) {
368
+ if (strategy.canRecover(error)) {
369
+ try {
370
+ return await strategy.recover(error, operation);
371
+ } catch (recoveryError) {
372
+ // If recovery fails, continue to next strategy
373
+ continue;
374
+ }
375
+ }
376
+ }
377
+
378
+ // If no recovery worked, throw the original error
379
+ throw error;
380
+ }
381
+ }
382
+ }
383
+
384
+ // ==================== UTILITY FUNCTIONS ====================
385
+
386
+ /**
387
+ * Create a resilient version of an async function
388
+ */
389
+ export function makeResilient<T extends any[], R>(
390
+ fn: (...args: T) => Promise<R>,
391
+ config: ResilienceConfig = {}
392
+ ): (...args: T) => Promise<R> {
393
+ const resilientOp = new ResilientOperation<R>(config);
394
+
395
+ return (...args: T) => {
396
+ return resilientOp.execute(() => fn(...args));
397
+ };
398
+ }
399
+
400
+ /**
401
+ * Delay execution for a specified time
402
+ */
403
+ export function delay(ms: number): Promise<void> {
404
+ return new Promise(resolve => setTimeout(resolve, ms));
405
+ }
406
+
407
+ /**
408
+ * Create a timeout wrapper for promises
409
+ */
410
+ export function withTimeout<T>(
411
+ promise: Promise<T>,
412
+ timeoutMs: number,
413
+ timeoutMessage = 'Operation timed out'
414
+ ): Promise<T> {
415
+ const timeoutPromise = new Promise<never>((_, reject) => {
416
+ setTimeout(() => {
417
+ reject(new TimeoutError('operation', timeoutMs));
418
+ }, timeoutMs);
419
+ });
420
+
421
+ return Promise.race([promise, timeoutPromise]);
422
+ }
423
+
424
+ /**
425
+ * Batch operations with concurrency control
426
+ */
427
+ export async function batch<T, R>(
428
+ items: T[],
429
+ operation: (item: T, index: number) => Promise<R>,
430
+ concurrency = 5
431
+ ): Promise<R[]> {
432
+ const results: R[] = [];
433
+ const errors: Array<{ index: number; error: any }> = [];
434
+
435
+ for (let i = 0; i < items.length; i += concurrency) {
436
+ const batch = items.slice(i, i + concurrency);
437
+ const promises = batch.map((item, batchIndex) =>
438
+ operation(item, i + batchIndex)
439
+ .catch(error => ({ error, index: i + batchIndex }))
440
+ );
441
+
442
+ const batchResults = await Promise.all(promises);
443
+
444
+ batchResults.forEach((result, batchIndex) => {
445
+ if (result && typeof result === 'object' && 'error' in result) {
446
+ errors.push(result as { index: number; error: any });
447
+ } else {
448
+ results[i + batchIndex] = result as R;
449
+ }
450
+ });
451
+ }
452
+
453
+ if (errors.length > 0) {
454
+ throw new ValidationError(
455
+ `Batch operation failed for ${errors.length} items`,
456
+ 'batch',
457
+ { errors: errors.map(e => ({ index: e.index, message: e.error.message })) }
458
+ );
459
+ }
460
+
461
+ return results;
462
462
  }