forked from CredenceOrg/Credence-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutationRecovery.ts
More file actions
794 lines (696 loc) · 25.4 KB
/
Copy pathmutationRecovery.ts
File metadata and controls
794 lines (696 loc) · 25.4 KB
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
/**
* @file mutationRecovery.ts
* @description Recovery system for bond and trust-score mutations with deterministic guarantees.
*
* Recovery Strategies:
* 1. Operation state reconstruction from storage
* 2. API confirmation for submitted transactions
* 3. Idempotent retry with exponential backoff
* 4. Partial state cleanup and rollback
* 5. Concurrent operation detection and resolution
*
* Invariants Enforced:
* - No duplicate mutations reach the network
* - Failed operations can always be resumed or cancelled
* - Partial state is cleaned up atomically
* - Users see consistent operation status across sessions
*/
import { apiFetch, ApiError, ApiRateLimitError } from '../api/client'
import {
type MutationOperation,
type MutationOperationId,
type MutationType,
type MutationError,
getMutationOperation,
getMutationOperations,
updateMutationOperation,
createMutationOperation,
} from './mutationStorage'
import { submitCreateBond, submitWithdrawBond } from './bondMutations'
import { validateBondAmount, validateTrustScoreAddress } from './mutationGuard'
import { logInfo, logWarn, logError } from './log'
// ═══════════════════════════════════════════════════════════════════════════
// Recovery Configuration
// ═══════════════════════════════════════════════════════════════════════════
interface RetryPolicy {
maxAttempts: number
baseDelayMs: number
maxDelayMs: number
backoffMultiplier: number
retryableErrors: MutationError['type'][]
}
const DEFAULT_RETRY_POLICY: RetryPolicy = {
maxAttempts: 3,
baseDelayMs: 1000,
maxDelayMs: 30000,
backoffMultiplier: 2,
retryableErrors: ['network', 'timeout', 'generic'],
}
const OPERATION_RECOVERY_TIMEOUT_MS = 300000 // 5 minutes
// ═══════════════════════════════════════════════════════════════════════════
// Recovery Utilities
// ═══════════════════════════════════════════════════════════════════════════
function calculateRetryDelay(attemptNumber: number, policy: RetryPolicy): number {
const delay = policy.baseDelayMs * Math.pow(policy.backoffMultiplier, attemptNumber - 1)
return Math.min(delay, policy.maxDelayMs)
}
function shouldRetryError(error: MutationError, policy: RetryPolicy): boolean {
return policy.retryableErrors.includes(error.type)
}
function createMutationError(
type: MutationError['type'],
message: string,
retryable: boolean = true,
code?: string | number
): MutationError {
return {
type,
message,
code,
timestamp: new Date().toISOString(),
retryable,
}
}
/** Coerce a payload's `retryAfterMs` to a positive finite number, else undefined. */
function safeNumber(value: unknown): number | undefined {
const n = typeof value === 'number' ? value : Number(value)
return Number.isFinite(n) && n > 0 ? n : undefined
}
function apiErrorToMutationError(apiError: ApiError): MutationError {
let type: MutationError['type'] = 'generic'
let retryable = true
// Check for wallet rejection patterns
if (
apiError.message.toLowerCase().includes('user rejected') ||
apiError.message.toLowerCase().includes('cancelled') ||
apiError.message.toLowerCase().includes('denied')
) {
type = 'wallet_rejected'
retryable = false
} else if (apiError.status === 429) {
type = 'rate_limit'
retryable = false
} else if (apiError.status === 0) {
type = 'network'
} else if (apiError.status >= 400 && apiError.status < 500) {
type = 'validation'
retryable = false
} else if (apiError.status >= 500) {
type = 'backend'
}
const retryAfterMs =
apiError.payload && typeof apiError.payload === 'object' && 'retryAfterMs' in apiError.payload
? safeNumber(apiError.payload.retryAfterMs)
: apiError instanceof ApiRateLimitError
? apiError.retryAfterMs
: undefined
const mutationError = createMutationError(type, apiError.message, retryable, apiError.status)
if (retryAfterMs !== undefined) {
mutationError.retryAfterMs = retryAfterMs
}
return mutationError
}
function parseUnknownError(error: unknown): MutationError {
if (error instanceof ApiError) {
return apiErrorToMutationError(error)
}
const message = error instanceof Error ? error.message : String(error)
const lower = message.toLowerCase()
if (
lower.includes('user rejected') ||
lower.includes('rejected') ||
lower.includes('cancelled') ||
lower.includes('denied')
) {
return createMutationError('wallet_rejected', message, false)
}
return createMutationError('generic', message, true)
}
// ═══════════════════════════════════════════════════════════════════════════
// Operation Execution Engine
// ═══════════════════════════════════════════════════════════════════════════
export interface ExecutionContext {
operationId: MutationOperationId
operation: MutationOperation
signal: AbortSignal
retryPolicy: RetryPolicy
}
export interface ExecutionResult {
success: boolean
txHash?: string
response?: Record<string, unknown>
error?: MutationError
shouldRetry?: boolean
}
async function executeBondCreate(
params: { amountUsdc: number },
context: ExecutionContext
): Promise<ExecutionResult> {
const amount = validateBondAmount(params?.amountUsdc)
if (!amount.ok) {
// Bounded input: reject adversarial/burst sizes before any expensive work.
return {
success: false,
error: createMutationError('validation', amount.message, false),
}
}
try {
const result = await submitCreateBond({ amountUsdc: amount.value })
return {
success: true,
txHash: result.hash,
response: { hash: result.hash, amountUsdc: amount.value },
}
} catch (error) {
const mutationError = parseUnknownError(error)
return {
success: false,
error: mutationError,
shouldRetry: shouldRetryError(mutationError, context.retryPolicy),
}
}
}
async function executeBondWithdraw(
params: { bondId: number; amountUsdc: number },
context: ExecutionContext
): Promise<ExecutionResult> {
const amount = validateBondAmount(params?.amountUsdc)
if (!amount.ok) {
return {
success: false,
error: createMutationError('validation', amount.message, false),
}
}
if (!Number.isSafeInteger(params?.bondId) || (params?.bondId ?? 0) <= 0) {
return {
success: false,
error: createMutationError('validation', 'Bond id must be a positive integer.', false),
}
}
try {
const result = await submitWithdrawBond({ bondId: params.bondId, amountUsdc: amount.value })
return {
success: true,
txHash: result.hash,
response: { hash: result.hash, bondId: params.bondId, amountUsdc: amount.value },
}
} catch (error) {
const mutationError = parseUnknownError(error)
return {
success: false,
error: mutationError,
shouldRetry: shouldRetryError(mutationError, context.retryPolicy),
}
}
}
async function executeTrustScoreLookup(
params: { address: string },
context: ExecutionContext
): Promise<ExecutionResult> {
const address = validateTrustScoreAddress(params?.address)
if (!address.ok) {
// Bounded input: reject unbounded/empty addresses before the lookup path.
return {
success: false,
error: createMutationError('validation', address.message, false),
}
}
try {
const result = await apiFetch(`/trust-score/${encodeURIComponent(address.value)}`, {
signal: context.signal,
})
return {
success: true,
response: result as Record<string, unknown>,
}
} catch (error) {
const mutationError =
error instanceof ApiError
? apiErrorToMutationError(error)
: createMutationError('generic', error instanceof Error ? error.message : String(error))
return {
success: false,
error: mutationError,
shouldRetry: shouldRetryError(mutationError, context.retryPolicy),
}
}
}
async function executeOperation(context: ExecutionContext): Promise<ExecutionResult> {
const { operation } = context
const params = operation.requestMetadata
switch (operation.type) {
case 'bond_create':
return executeBondCreate(params as { amountUsdc: number }, context)
case 'bond_withdraw':
return executeBondWithdraw(params as { bondId: number; amountUsdc: number }, context)
case 'trust_score_lookup':
return executeTrustScoreLookup(params as { address: string }, context)
default:
return {
success: false,
error: createMutationError('validation', `Unknown mutation type: ${operation.type}`, false),
}
}
}
// ═══════════════════════════════════════════════════════════════════════════
// Recovery Engine
// ═══════════════════════════════════════════════════════════════════════════
export class MutationRecoveryEngine {
private activeRecoveries = new Map<MutationOperationId, AbortController>()
private retryPolicy: RetryPolicy
constructor(retryPolicy: RetryPolicy = DEFAULT_RETRY_POLICY) {
this.retryPolicy = retryPolicy
}
/**
* Recovers all pending operations from storage on application startup.
*/
async recoverPendingOperations(): Promise<{
recovered: number
failed: number
operations: MutationOperationId[]
}> {
const pendingOperations = getMutationOperations(undefined, 'pending').concat(
getMutationOperations(undefined, 'submitting')
)
logInfo('mutation_recovery_started', {
pendingCount: pendingOperations.length,
})
const results = {
recovered: 0,
failed: 0,
operations: [] as MutationOperationId[],
}
for (const operation of pendingOperations) {
try {
const recovered = await this.recoverOperation(operation.operationId)
if (recovered) {
results.recovered++
} else {
results.failed++
}
results.operations.push(operation.operationId)
} catch (error) {
logError('mutation_recovery_operation_failed', {
operationId: operation.operationId,
error: error instanceof Error ? error.message : String(error),
})
results.failed++
}
}
logInfo('mutation_recovery_completed', {
recoveredCount: results.recovered,
failedCount: results.failed,
operationsCount: results.operations.length,
})
return results
}
/**
* Recovers a specific operation with full state reconstruction.
*/
async recoverOperation(operationId: MutationOperationId): Promise<boolean> {
const operation = getMutationOperation(operationId)
if (!operation) {
logWarn('mutation_recovery_operation_not_found', { operationId })
return false
}
// Check if already being recovered
if (this.activeRecoveries.has(operationId)) {
logInfo('mutation_recovery_already_active', { operationId })
return true
}
const controller = new AbortController()
this.activeRecoveries.set(operationId, controller)
try {
// Mark as being recovered
updateMutationOperation(operationId, () => ({
isRecovered: true,
recoveredAt: new Date().toISOString(),
recoverySource: 'storage',
}))
// Try to confirm existing transaction first
if (operation.finalTxHash) {
const confirmed = await this.confirmTransaction(operation.finalTxHash, controller.signal)
if (confirmed) {
updateMutationOperation(operationId, () => ({
status: 'success',
completedAt: new Date().toISOString(),
}))
return true
}
}
// Determine recovery strategy based on operation state
if (operation.status === 'submitting' && operation.attempts.length > 0) {
// Wait for in-flight operation or retry if timed out
return await this.recoverSubmittingOperation(operationId, controller.signal)
} else if (
operation.status === 'pending' ||
operation.status === 'error' ||
operation.status === 'idle'
) {
// Resume execution from where it left off
return await this.resumeOperation(operationId, controller.signal, operation)
}
logWarn('mutation_recovery_unsupported_state', {
operationId,
status: operation.status,
})
return false
} catch (error) {
logError('mutation_recovery_failed', {
operationId,
error: error instanceof Error ? error.message : String(error),
})
// Mark as error state for user visibility
updateMutationOperation(operationId, () => ({
status: 'error',
attempts: [
...operation.attempts,
{
attemptId: `recovery:${Date.now()}`,
timestamp: new Date().toISOString(),
requestHash: operation.requestHash,
status: 'error',
error: createMutationError(
'generic',
`Recovery failed: ${error instanceof Error ? error.message : String(error)}`,
false
),
},
],
}))
return false
} finally {
this.activeRecoveries.delete(operationId)
}
}
/**
* Confirms if a transaction hash exists and is successful.
*/
private async confirmTransaction(txHash: string, signal: AbortSignal): Promise<boolean> {
try {
// For demo purposes, assume local hashes are always confirmed
// In real implementation, this would query Stellar Horizon API
if (txHash.startsWith('local-')) {
return true
}
// For actual blockchain transactions, implement proper confirmation logic
const response = await apiFetch(`/transactions/${txHash}/status`, {
signal,
skipRateLimit: true,
})
return (response as { status: string }).status === 'success'
} catch (error) {
logWarn('mutation_recovery_confirmation_failed', {
txHash,
error: error instanceof Error ? error.message : String(error),
})
return false
}
}
/**
* Recovers an operation that was submitting when the app crashed/reloaded.
*/
private async recoverSubmittingOperation(
operationId: MutationOperationId,
signal: AbortSignal
): Promise<boolean> {
const operation = getMutationOperation(operationId)
if (!operation) return false
const lastAttempt = operation.attempts[operation.attempts.length - 1]
if (!lastAttempt) return false
const timeSinceLastAttempt = Date.now() - new Date(lastAttempt.timestamp).getTime()
if (timeSinceLastAttempt < OPERATION_RECOVERY_TIMEOUT_MS) {
// Recent attempt - wait a bit longer before assuming failure
await new Promise((resolve) =>
setTimeout(resolve, Math.min(5000, OPERATION_RECOVERY_TIMEOUT_MS - timeSinceLastAttempt))
)
// Check if transaction was confirmed in the meantime
if (lastAttempt.txHash) {
const confirmed = await this.confirmTransaction(lastAttempt.txHash, signal)
if (confirmed) {
updateMutationOperation(operationId, () => ({
status: 'success',
finalTxHash: lastAttempt.txHash,
completedAt: new Date().toISOString(),
}))
return true
}
}
}
// Assume the submitting operation failed and retry if possible
updateMutationOperation(operationId, (op) => ({
status: 'error',
attempts: [
...op.attempts.slice(0, -1),
{
...lastAttempt,
status: 'error',
error: createMutationError('timeout', 'Operation timed out during recovery', true),
},
],
}))
// Retry if we haven't exceeded max attempts
if (operation.attempts.length < operation.maxAttempts) {
return await this.resumeOperation(operationId, signal, operation)
}
return false
}
/**
* Resumes execution of a pending operation.
*/
private async resumeOperation(
operationId: MutationOperationId,
signal: AbortSignal,
opParam?: MutationOperation
): Promise<boolean> {
if (signal.aborted) return false
const operation = getMutationOperation(operationId) || opParam
if (!operation || operation.status === 'cancelled') return false
if (operation.attempts.length >= operation.maxAttempts) {
logWarn('mutation_recovery_max_attempts_exceeded', { operationId })
return false
}
// Calculate retry delay based on previous attempts
const retryDelay = calculateRetryDelay(operation.attempts.length + 1, this.retryPolicy)
if (retryDelay > 0) {
await new Promise((resolve) => setTimeout(resolve, retryDelay))
}
if (signal.aborted) return false
return await this.executeOperationAttempt(operationId, signal, operation)
}
/**
* Executes a single operation attempt with proper state management.
*/
private async executeOperationAttempt(
operationId: MutationOperationId,
signal: AbortSignal,
opParam?: MutationOperation
): Promise<boolean> {
if (signal.aborted) return false
const operation = getMutationOperation(operationId) || opParam
if (!operation || operation.status === 'cancelled') return false
const attemptId = `attempt:${Date.now()}:${Math.random().toString(36).substr(2, 9)}`
// Mark as submitting and create new attempt record
updateMutationOperation(operationId, (op) => ({
status: 'submitting',
attempts: [
...op.attempts,
{
attemptId,
timestamp: new Date().toISOString(),
requestHash: operation.requestHash,
status: 'submitting',
},
],
}))
const context: ExecutionContext = {
operationId,
operation,
signal,
retryPolicy: this.retryPolicy,
}
try {
const result = await executeOperation(context)
if (result.success) {
// Update successful attempt and complete operation
updateMutationOperation(operationId, (op) => ({
status: 'success',
finalTxHash: result.txHash,
finalResponse: result.response,
completedAt: new Date().toISOString(),
attempts: op.attempts.map((attempt) =>
attempt.attemptId === attemptId
? { ...attempt, status: 'success', txHash: result.txHash, response: result.response }
: attempt
),
}))
logInfo('mutation_recovery_success', { operationId, txHash: result.txHash })
return true
} else {
// Update failed attempt
updateMutationOperation(operationId, (op) => ({
status: result.shouldRetry && op.attempts.length < op.maxAttempts ? 'pending' : 'error',
attempts: op.attempts.map((attempt) =>
attempt.attemptId === attemptId
? { ...attempt, status: 'error', error: result.error }
: attempt
),
}))
// Retry if appropriate
if (result.shouldRetry && operation.attempts.length + 1 < operation.maxAttempts) {
logInfo('mutation_recovery_retry_scheduled', {
operationId,
attemptNumber: operation.attempts.length + 1,
})
return await this.resumeOperation(operationId, signal)
}
logWarn('mutation_recovery_failed_permanently', {
operationId,
error: result.error?.message,
})
return false
}
} catch (error) {
// Update attempt with execution error
const executionError = createMutationError(
'generic',
error instanceof Error ? error.message : String(error),
false
)
updateMutationOperation(operationId, (op) => ({
status: 'error',
attempts: op.attempts.map((attempt) =>
attempt.attemptId === attemptId
? { ...attempt, status: 'error', error: executionError }
: attempt
),
}))
logError('mutation_recovery_execution_error', {
operationId,
error: error instanceof Error ? error.message : String(error),
})
return false
}
}
/**
* Cancels active recovery for an operation.
*/
cancelRecovery(operationId: MutationOperationId): boolean {
const controller = this.activeRecoveries.get(operationId)
if (controller) {
controller.abort('cancelled by user')
this.activeRecoveries.delete(operationId)
updateMutationOperation(operationId, () => ({
status: 'cancelled',
completedAt: new Date().toISOString(),
}))
logInfo('mutation_recovery_cancelled', { operationId })
return true
}
return false
}
/**
* Cancels all active recoveries (for app shutdown).
*/
cancelAllRecoveries(): number {
const activeCount = this.activeRecoveries.size
for (const [operationId, controller] of this.activeRecoveries) {
controller.abort('app shutdown')
updateMutationOperation(operationId, () => ({
status: 'pending', // Return to pending so it can be recovered on next startup
}))
}
this.activeRecoveries.clear()
logInfo('mutation_recovery_all_cancelled', { count: activeCount })
return activeCount
}
/**
* Gets the current recovery status for all operations.
*/
getRecoveryStatus(): {
active: MutationOperationId[]
pending: number
failed: number
} {
const pendingOperations = getMutationOperations(undefined, 'pending').concat(
getMutationOperations(undefined, 'submitting')
)
const failedOperations = getMutationOperations(undefined, 'error')
return {
active: Array.from(this.activeRecoveries.keys()),
pending: pendingOperations.length,
failed: failedOperations.length,
}
}
}
// ═══════════════════════════════════════════════════════════════════════════
// Public API
// ═══════════════════════════════════════════════════════════════════════════
// Singleton recovery engine
export const mutationRecoveryEngine = new MutationRecoveryEngine()
/**
* Initiates a new mutation with automatic deduplication and recovery setup.
*/
export async function initiateMutation(
type: MutationType,
params: Record<string, unknown>,
maxAttempts?: number
): Promise<{
operationId: MutationOperationId
isNewOperation: boolean
started: boolean
}> {
const { operationId, isNewOperation } = createMutationOperation(type, params, maxAttempts)
if (!isNewOperation) {
// Existing operation - trigger recovery if needed
const operation = getMutationOperation(operationId)
if (operation && (operation.status === 'pending' || operation.status === 'error')) {
const recovered = await mutationRecoveryEngine.recoverOperation(operationId)
return { operationId, isNewOperation, started: recovered }
}
return { operationId, isNewOperation, started: true }
}
// New operation - start execution
updateMutationOperation(operationId, () => ({ status: 'pending' }))
const started = await mutationRecoveryEngine.recoverOperation(operationId)
return { operationId, isNewOperation, started }
}
/**
* Force retry of a failed operation.
*/
export async function retryMutation(operationId: MutationOperationId): Promise<boolean> {
const operation = getMutationOperation(operationId)
if (!operation) return false
if (operation.status !== 'error') {
logWarn('mutation_retry_invalid_state', { operationId, status: operation.status })
return false
}
// Reset to pending and trigger recovery
updateMutationOperation(operationId, () => ({ status: 'pending' }))
return await mutationRecoveryEngine.recoverOperation(operationId)
}
/**
* Cancel a pending or active operation.
*/
export function cancelMutation(operationId: MutationOperationId): boolean {
return mutationRecoveryEngine.cancelRecovery(operationId)
}
/**
* Initialize recovery system on app startup.
*/
export async function initializeMutationRecovery(): Promise<void> {
logInfo('mutation_recovery_initializing')
const results = await mutationRecoveryEngine.recoverPendingOperations()
logInfo('mutation_recovery_initialized', {
recoveredCount: results.recovered,
failedCount: results.failed,
operationsCount: results.operations.length,
})
}
/**
* Cleanup recovery system on app shutdown.
*/
export function shutdownMutationRecovery(): void {
const cancelled = mutationRecoveryEngine.cancelAllRecoveries()
logInfo('mutation_recovery_shutdown', { cancelledOperations: cancelled })
}