onMessage method

  1. @override
Future<void> onMessage(
  1. dynamic message
)

Handle incoming messages with command/event routing

Implementation

@override
Future<void> onMessage(dynamic message) async {
  // Capture sender at the START of message processing, keyed by command ID
  // This handles concurrent message processing where multiple commands
  // may be processed at the same time
  String? commandKey;
  if (message is Command && context.sender != null) {
    commandKey = message.commandId;
    _capturedSenders[commandKey] = context.sender!;
  }

  try {
    // Check if this is a duplicate command
    if (message is CreateWalletCommand) {
      try {
        if (currentState.isCreated) {
          // Answer deterministically instead of dropping the message:
          // a silent drop left an asking caller to time out.
          final sender = commandKey == null ? null : _capturedSenders[commandKey];
          sender?.tell(WalletCreatedResponse(
            walletId: message.walletId,
            rootAddress: currentState.rootAddress ?? '',
            success: false,
            error: 'Wallet ${message.walletId} already exists',
          ));
          return;
        }
      } catch (e) {
        _log.warning('Failed to check duplicate CreateWalletCommand: $e');
      }
    }
    await super.onMessage(message);
  } finally {
    // Clean up the captured sender for this specific command
    if (commandKey != null) {
      _capturedSenders.remove(commandKey);
      _failureReplied.remove(commandKey);
    }
  }
}