Skip to content

sync main#267

Merged
ca333 merged 2 commits intomainfrom
dev
Oct 29, 2025
Merged

sync main#267
ca333 merged 2 commits intomainfrom
dev

Conversation

@ca333
Copy link
Copy Markdown
Contributor

@ca333 ca333 commented Oct 29, 2025

  • ios reinit fix
  • fix withdraw

Summary by CodeRabbit

Release Notes

  • New Features

    • Added HTTP client reset capability to recover from stale connections and improve connection reliability.
    • Implemented pre-flight health verification for authentication operations.
  • Bug Fixes

    • Improved detection and automatic recovery from transport-related connection failures.
    • Enhanced KDF health monitoring with better error handling.
  • Improvements

    • Expanded logging and observability for better debugging and monitoring.
    • Made KMD rewards field handling more flexible for withdrawal operations.

Copilot AI review requested due to automatic review settings October 29, 2025 01:07
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Oct 29, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes introduce HTTP client reset capability throughout the framework to recover from stale connections and transport failures, enhance KDF health verification in the auth service with concurrency control and forced restart logic, inject KMD-specific withdrawal parameters, and make the KmdRewards claimedByMe field optional.

Changes

Cohort / File(s) Summary
HTTP Client Reset Interface & Implementations
packages/komodo_defi_framework/lib/src/operations/kdf_operations_interface.dart, kdf_operations_local_executable.dart, kdf_operations_native.dart, kdf_operations_native_stub.dart, kdf_operations_remote.dart, kdf_operations_wasm.dart
Added resetHttpClient() method across all KDF operations implementations. Interface declares the contract; native library implements actual reset logic (closes and reinitializes HTTP client); remote, stub, and WASM provide no-op implementations with appropriate logging; local executable delegates to remote.
Main Framework Error Handling & Observability
packages/komodo_defi_framework/lib/komodo_defi_framework.dart
Enhanced version() with Stopwatch timing and error logging; simplified isHealthy() to single RPC-based check; added public resetHttpClient() method; upgraded executeRpc() catch block to detect fatal transport-related SocketExceptions and trigger HTTP client reset with enhanced logging.
Auth Service Health Check & Restart Flow
packages/komodo_defi_local_auth/lib/src/auth/auth_service.dart
Introduced comprehensive KDF health-check coordination with single-flight guard (_ongoingHealthCheck) and cooldown logic (_lastHealthCheckCompleted). Added _performHealthCheck() and _verifyKdfHealthy() for two-step validation. Integrated forced restart via _forceStartKdf() with post-restart verification and conditional logout emission. Enhanced signIn() with pre-flight health checks and retry logic; added session-scoped UUID and logging utilities.
Withdrawal Parameter Injection & Type Changes
packages/komodo_defi_rpc_methods/lib/src/rpc_methods/withdrawal/withdraw_request.dart, packages/komodo_defi_types/lib/src/withdrawal/withdrawal_types.dart
Inject KMD-specific rewards parameters in WithdrawRequest.toJson() and WithdrawInitRequest.toJson() when coin is KMD. Made KmdRewards.claimedByMe field optional (bool?) with conditional JSON serialization and nullable deserialization.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant AuthService
    participant KomodoDefiFramework
    participant KdfOperations

    User->>AuthService: signIn()
    AuthService->>AuthService: log login attempt
    AuthService->>AuthService: ensureKdfHealthy() with timeout
    
    alt Health check in progress (single-flight)
        AuthService->>AuthService: wait for ongoing check
    else First check or cooldown expired
        AuthService->>AuthService: _performHealthCheck()
        AuthService->>KomodoDefiFramework: isHealthy()
        KomodoDefiFramework->>KdfOperations: executeRpc(version)
        
        alt Success
            KdfOperations-->>KomodoDefiFramework: result
            KomodoDefiFramework-->>AuthService: true
        else Fatal transport error (e.g., ECONNRESET)
            KdfOperations->>KdfOperations: detect SocketException
            KdfOperations->>KomodoDefiFramework: resetHttpClient()
            KomodoDefiFramework->>KdfOperations: resetHttpClient()
            KdfOperations->>KdfOperations: close + reinit HTTP client
            KdfOperations-->>KomodoDefiFramework: error logged & rethrown
        end
        
        alt Still unhealthy after check
            AuthService->>AuthService: _forceStartKdf()
            AuthService->>AuthService: _verifyKdfHealthy()
            
            alt Still fails after retry
                AuthService-->>User: throw AuthException (KDF unavailable)
            else Healthy after restart
                AuthService->>AuthService: emit logged-out state (if user was signed in)
                AuthService-->>User: proceed with signIn
            end
        else Healthy
            AuthService-->>User: proceed with signIn
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

  • KdfAuthService (auth_service.dart): Dense logic with concurrent health-check coordination, forced restart flow, state machine transitions, and logging; requires careful review of race conditions and cooldown semantics.
  • KomodoDefiFramework (komodo_defi_framework.dart): Transport error detection and automatic HTTP client reset in executeRpc() and isHealthy() refactoring; verify exception classification correctness and timing instrumentation.
  • KmdRewards type change (withdrawal_types.dart): Optional field transition; verify backward compatibility of JSON deserialization and conditional serialization logic across all consumers.
  • HTTP client reset implementations: While pattern-consistent across 6 files, the native library's mutable HTTP client change and proper initialization/cleanup must be validated.

Suggested labels

bug

Poem

🐰 A hop through health and HTTP streams,
Where clients reset their broken dreams!
One flight, one check, no double dance—
KDF springs back with fresh advance.
Now KMD rewards find their way,
And optional fields brighten the day! ✨

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dev

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7e1a277 and fed0e3c.

📒 Files selected for processing (10)
  • packages/komodo_defi_framework/lib/komodo_defi_framework.dart (2 hunks)
  • packages/komodo_defi_framework/lib/src/operations/kdf_operations_interface.dart (1 hunks)
  • packages/komodo_defi_framework/lib/src/operations/kdf_operations_local_executable.dart (1 hunks)
  • packages/komodo_defi_framework/lib/src/operations/kdf_operations_native.dart (2 hunks)
  • packages/komodo_defi_framework/lib/src/operations/kdf_operations_native_stub.dart (1 hunks)
  • packages/komodo_defi_framework/lib/src/operations/kdf_operations_remote.dart (1 hunks)
  • packages/komodo_defi_framework/lib/src/operations/kdf_operations_wasm.dart (1 hunks)
  • packages/komodo_defi_local_auth/lib/src/auth/auth_service.dart (5 hunks)
  • packages/komodo_defi_rpc_methods/lib/src/rpc_methods/withdrawal/withdraw_request.dart (3 hunks)
  • packages/komodo_defi_types/lib/src/withdrawal/withdrawal_types.dart (1 hunks)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@ca333 ca333 merged commit 10b2e25 into main Oct 29, 2025
9 of 11 checks passed
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR implements robust KDF health check mechanisms and KMD withdrawal support improvements. It addresses iOS backgrounding issues where KDF becomes unresponsive but reports as running, causing authentication failures.

  • Enhanced KDF health checking with double verification, single-flight guards, and cooldown mechanisms
  • Made KmdRewards.claimedByMe nullable to handle optional API responses
  • Added automatic KMD rewards parameters to withdrawal requests

Reviewed Changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
withdrawal_types.dart Made claimedByMe field optional/nullable in KmdRewards class
withdraw_request.dart Added automatic KMD rewards parameters for KMD coin withdrawals
auth_service.dart Implemented comprehensive health check with single-flight guards, cooldown, and proactive KDF verification before login
komodo_defi_framework.dart Enhanced version RPC with timing logs, improved isHealthy() to rely only on RPC verification, added HTTP client reset and transport error detection
kdf_operations_*.dart Implemented resetHttpClient() across all operation implementations

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +282 to +285
final errorType = errorString.contains('errno = 32') || errorString.contains('broken pipe') ? 'EPIPE (32)' :
errorString.contains('errno = 54') || errorString.contains('connection reset') ? 'ECONNRESET (54)' :
errorString.contains('errno = 60') || errorString.contains('operation timed out') ? 'ETIMEDOUT (60)' :
'ECONNREFUSED (61)';
Copy link

Copilot AI Oct 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The nested ternary operator chain for error type mapping is difficult to read and maintain. Consider refactoring to use a helper function or if-else statements for better clarity.

Copilot uses AI. Check for mistakes.
final now = DateTime.now();
if (_lastHealthCheckCompleted != null) {
final timeSinceLastCheck = now.difference(_lastHealthCheckCompleted!);
if (timeSinceLastCheck.inSeconds < 2) {
Copy link

Copilot AI Oct 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cooldown period of 2 seconds is a magic number. Consider extracting it as a named constant (e.g., _kHealthCheckCooldownSeconds) to improve maintainability and make the purpose clear.

Copilot uses AI. Check for mistakes.
Comment on lines +141 to +144
onTimeout: () {
_logger.warning('[$_sessionId] signIn: Health check timed out after 3s');
return false;
},
Copy link

Copilot AI Oct 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The timeout duration of 3 seconds is hardcoded in multiple places (lines 140, 152, 578, 590, 618, 652). Consider extracting these timeout values as named constants to avoid inconsistencies and improve maintainability.

Copilot uses AI. Check for mistakes.
// Add 200ms delay after restart before verification to avoid race where
// native status reports "up" but HTTP listener hasn't bound yet
_logger.info('[$_sessionId] _performHealthCheck: Waiting 200ms for HTTP listener to bind');
await Future.delayed(const Duration(milliseconds: 200));
Copy link

Copilot AI Oct 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 200ms delay after restart is a magic number. Consider extracting it as a named constant (e.g., _kHttpListenerBindDelayMs) with a clear name explaining why this delay is necessary.

Copilot uses AI. Check for mistakes.
@github-actions
Copy link
Copy Markdown
Contributor

Visit the preview URL for this PR (updated for commit fed0e3c):

https://kdf-sdk--pr267-dev-5dgxb221.web.app

(expires Wed, 05 Nov 2025 01:12:26 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: 9c1b6e6c010cf0b965c455ba7a69c4aedafa8a1d

@github-actions
Copy link
Copy Markdown
Contributor

Visit the preview URL for this PR (updated for commit fed0e3c):

https://komodo-playground--pr267-dev-dsd1z56b.web.app

(expires Wed, 05 Nov 2025 01:14:44 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: 2bfedd77fdea45b25ba7c784416e81f177aa5c47

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants