Class BalanceManager

java.lang.Object
com.reve.balancemanager.BalanceManager

public class BalanceManager extends Object
Manages balance information for all clients presents in mysql BalanceTable.CLIENT_BALANCE_TABLE table. Maintains elastic property to sync balance in between mysql and redis cluster.
  • Field Details

    • APPLICATION_NAME

      public static final String APPLICATION_NAME
      See Also:
    • VERSION

      public static final String VERSION
      See Also:
    • doubleFormatter

      public static final com.reve.utils.DoubleFormatter doubleFormatter
      The instance that will be used to clip double value to 6 decimal places.
    • TOKENIZER

      public static final String TOKENIZER
      See Also:
    • BM_ID_FIELD

      public static final String BM_ID_FIELD
      See Also:
    • MAX_THREAD_COUNT

      public static final int MAX_THREAD_COUNT
      See Also:
    • MINIMUM_LEASE_CHUNK

      public static final double MINIMUM_LEASE_CHUNK
      Minimum lease chunk Balance Manager tries to store locally from Redis for an account when LeaseDTO.getLease(double, LeaseResponse, boolean) is called
      See Also:
    • MAXIMUM_LEASE_CHUNK

      public static final double MAXIMUM_LEASE_CHUNK
      Maximum lease chunk Balance Manager tries to store locally from Redis for an account when LeaseDTO.getLease(double, LeaseResponse, boolean) is called
      See Also:
    • MAXIMUM_LOCAL_BALANCE

      public static final double MAXIMUM_LOCAL_BALANCE
      Maximum amount of money which can stay in available local balance of LeaseDTO. If available local balance crosses this amount 50% of available amount will be returned to redis.
      See Also:
    • LEASE_CHUNK_STEP

      public static final double LEASE_CHUNK_STEP
      Value to increase or decrease when adjusting lease chunk with demand
      See Also:
    • TIME_TO_INCREASE_LEASE_CHUNK

      public static final long TIME_TO_INCREASE_LEASE_CHUNK
      Time under which a lease request is received in Redis, we will increase local balance chunk for a LeaseDTO
      See Also:
    • TIME_TO_DECREASE_LEASE_CHUNK

      public static final long TIME_TO_DECREASE_LEASE_CHUNK
      Time above which a lease request is received in Redis, we will decrease local balance chunk for a LeaseDTO
      See Also:
    • WAIT_TIME_BEFORE_FULL_RELEASE

      public static final long WAIT_TIME_BEFORE_FULL_RELEASE
      When a 100% (full) balance return request is made for an account, Balance manager will not process any further full amount return request for this time
      See Also:
  • Constructor Details

    • BalanceManager

      public BalanceManager(String identifier, String redisHost, int redisPort, String redisPass, com.reve.websocket.ssl.SSLConfiguration sslConfiguration, int connectionCount) throws Exception
      Create an instance of BalanceManager.
      Parameters:
      identifier - Balance Manager unique identifier. Can not contain these characters in the string : "-", "+", "*", ":", "\", "$", "%", "(", ")". Can not be null or empty.
      redisHost - Redis cluster server ip address where balance information will be cached. This cluster node must be a master node in cluster.
      redisPort - Redis cluster server port where balance information will be cached.
      redisPass - Auth Password for redis cluster
      sslConfiguration - if ssl/tls is configured in the redis cluster, then an instance of SSLConfiguration must be passed, which will be used to connect to the redis server. If ssl is not configured in the redis server, then this value should be null
      connectionCount - number of redis connection this application supposed to open.
      Throws:
      Exception - if occurs any while loading cluster information.
    • BalanceManager

      public BalanceManager(String identifier, String redisHost, int redisPort, String redisPass, com.reve.websocket.ssl.SSLConfiguration sslConfiguration) throws Exception
      Create an instance of BalanceManager.
      Parameters:
      identifier - Balance Manager unique identifier. Can not contain these characters in the string : "-", "+", "*", ":", "\", "$", "%", "(", ")". Can not be null or empty.
      redisHost - Redis cluster server ip address where balance information will be cached. This cluster node must be a master node in cluster.
      redisPort - Redis cluster server port where balance information will be cached.
      redisPass - Auth Password for redis cluster
      sslConfiguration - if ssl/tls is configured in the redis cluster, then an instance of SSLConfiguration must be passed, which will be used to connect to the redis server. If ssl is not configured in the redis server, then this value should be null
      Throws:
      Exception - if occurs any while loading cluster information.
    • BalanceManager

      public BalanceManager(String identifier, com.reve.redis.cluster.ClusterObserver clusterObserver) throws Exception
      Create an instance of BalanceManager.
      Parameters:
      identifier - Balance Manager unique identifier. Can not contain these characters in the string : "-", "+", "*", ":", "\", "$", "%", "(", ")". Can not be null or empty.
      clusterObserver - Cluster Observer of which BalanceManager will be part of.
      Throws:
      Exception - if occurs any while loading cluster information
  • Method Details

    • initLeaseDTO

      public void initLeaseDTO(Collection<Long> clientIDs)
      Initialize the instances of LeaseDTO for all the given clients at the startup. This method must be called just after creating the instance of BalanceManager
      Parameters:
      clientIDs - list of client id, which should be loaded at startup.
    • getPublisher

      public PubSubPublisher getPublisher()
      Getter for pubSubPublisher
      Returns:
      pubSubPublisher
    • getMysqlBalance

      public double getMysqlBalance(long accountId)
      If the given accountId is not present in redis then it will be loaded from mysql database and be saved in redis cluster.
      Parameters:
      accountId - Account ID for which balance information will be loaded into redis.
      Returns:
      Total available balance in mysql that can be used in calling or other purpose. = (cbBalance + cbCreditLimit - cbThresholdAmount)
    • setMysqlBalance

      public boolean setMysqlBalance(long accountId, double balance, double credit)
      If the given accountId is not present in redis then it will be loaded from mysql database and be saved in redis cluster.
      Parameters:
      accountId - Account ID for which balance information will be loaded into redis.
      balance - Amount to be set in mysql table
      credit - Amount to be set in mysql table
      Returns:
      Total available balance in mysql that can be used in calling or other purpose. = (cbBalance + cbCreditLimit - cbThresholdAmount)
    • getLease

      public double getLease(long accountId, double leaseAmount, LeaseResponse response)
      Try to get a lease from this account balance. If possible take that lease of given amount. If full amount not possible then try to take lease of possible amount. If that is even not possible then return with zero lease
      Parameters:
      accountId - The account id lease needed from
      leaseAmount - The amount to be added to the lease
      response - The response value will be updated into this instance. This instance must be passed from the caller, and values will be updated here.
      Returns:
      the exact amount that lease was possible for. 0 when no balance available for this client
    • getLease

      public double getLease(long accountId, double leaseAmount, LeaseResponse response, boolean partialEnabled)
      Try to get a lease from this account balance. If possible take that lease of given amount. If full amount not possible then try to take lease of possible amount. If that is even not possible then return with zero lease
      Parameters:
      accountId - The account id lease needed from
      leaseAmount - The amount to be added to the lease
      response - The response value will be updated into this instance. This instance must be passed from the caller, and values will be updated here.
      partialEnabled - if caller is happy with partial lease, ex - caller requested for 10 dollar but leaseDTO gives only 5 dollar, then this value must be true
      Returns:
      the exact amount that lease was possible for. 0 when no balance available for this client
    • returnLease

      public double returnLease(long accountId, double leaseAmount)
      Extra amount left at the end of the operation is added/subtract to the available local balance.
      Parameters:
      accountId - Account id the lease should be returned to
      leaseAmount - remaining lease amount. it can be +ve or -ve.
      Returns:
      the available local balance after this lease amount has been returned.
    • isFrozen

      public boolean isFrozen(long accountID)
      Check if the given account id is now in frozen mode or not.
      Parameters:
      accountID - The account id which to be checked for frozen mode.
      Returns:
      true, if the account is frozen, otherwise, return false.
    • refundBalance

      public void refundBalance(long accountID, double balance)
      For some unsuccessful case we may need to refund the balance of a transaction. This method will add those balance in both mysql and redis.
      Parameters:
      accountID - The account id for which refund should happen
      balance - amount of balance should be refunded. Balance can be +ve or -ve. Positive-refund add to mysql and local balance, whereas negative-refund subtracts from mysql and local balance.
    • getLeaseDTO

      public LeaseDTO getLeaseDTO(long accountID)
      Get the instance of LeaseDTO mapped with the given account id. If there is none, then create one and return
      Parameters:
      accountID - map key for The instance of LeaseDTO
      Returns:
      The instance of LeaseDTO
    • loadBalanceInRedis

      public boolean loadBalanceInRedis(long accountId)
      Successful completion of this method will ensure the presence of this LeaseDTO in redis cluster Either in the nearest node or In the far node. If no one else has loaded the data, It will load data from mysql and save it in My cluster Node Which will be needed for all consecutive call
      Parameters:
      accountId - The account id of a client whose balance to be loaded into redis.
      Returns:
      false if accountID is not found in mysql, true otherwise
    • returnLeaseOnRequest

      public void returnLeaseOnRequest(long accountId, boolean returnFullAmount)
      In case the balance of an account gets exhausted, balance manager will broadcast an empty status to all BMs. This method will be called in response to the broadcast message.
      Parameters:
      accountId - For which account the balance is exhausted/empty.
      returnFullAmount - if this value is true, then it will return all available local balance to redis.
    • processAccFreezeRequest

      public void processAccFreezeRequest(long accountId)
      When a freeze request is received from mitigator this method will be called. This will freeze the account if present in this BM. This method will also return the available balance to the cluster for this account. A FREEZE_COMPLETE will be published after the processing is done.
      Parameters:
      accountId - account id for which Freeze request is being processed.
    • processAccUnfreezeRequest

      public void processAccUnfreezeRequest(long accountId)
      When an unfreeze request is received from mitigator this method will be called. This will unfreeze the account. An UNFREEZE_COMPLETE will be published after the processing is done.
      Parameters:
      accountId - the account id which needs to be unfrozen
    • processAccFreezeAck

      public void processAccFreezeAck(long accountID, String balanceManagerID)
      Process MessageType.ACK_FREEZE_REQUEST message from the given balance manager.
      Parameters:
      accountID - Account id for which ack message is received.
      balanceManagerID - Identification of BalanceManager from where this message is received.
    • processAccFreezeCompete

      public void processAccFreezeCompete(long accountID, String balanceManagerID)
      Process MessageType.FREEZE_COMPLETE message from the given balance manager.
      Parameters:
      accountID - Account id for which MessageType.FREEZE_COMPLETE message is received.
      balanceManagerID - Identification of BalanceManager from where this message is received.
    • processAccUnFreezeCompete

      public void processAccUnFreezeCompete(long accountID, String balanceManagerID)
      Process MessageType.UNFREEZE_COMPLETE message from the given balance manager.
      Parameters:
      accountID - Account id for which MessageType.UNFREEZE_COMPLETE message is received.
      balanceManagerID - Identification of BalanceManager from where this message is received.
    • getIdentifier

      public String getIdentifier()
      Returns:
      Getter for identifier for this Balance Manager. The identifier is unique.
    • getClusterObserver

      public com.reve.redis.cluster.ClusterObserver getClusterObserver()
      Getter for clusterObserver
      Returns:
      The ClusterObserver instance that was used to cache balance information.
    • getThresholdToReleaseFullAmount

      public double getThresholdToReleaseFullAmount()
      Returns:
      Getter for the configured threshold under which Balance Manager will release the full available amount
    • setThresholdToReleaseFullAmount

      public void setThresholdToReleaseFullAmount(double thresholdToReleaseFullAmount)
      Setter to configure threshold under which Balance Manager will release the full available amount
      Parameters:
      thresholdToReleaseFullAmount - Amount to set as threshold to release full amount
    • getPercentageToRelease

      public double getPercentageToRelease()
      Returns:
      Getter for the percentage which Balance Manager will release when returnLeaseOnRequest(long, boolean) is called
    • setPercentageToRelease

      public void setPercentageToRelease(double percentageToRelease)
      Setter for the percentage which Balance Manager will release when returnLeaseOnRequest(long, boolean) is called
      Parameters:
      percentageToRelease - percentage tp release from available balance
    • getPubSubPublisher

      public PubSubPublisher getPubSubPublisher()
      Returns:
      Getter for the PubSub publisher which is used for communication
    • setBalanceFreezer

      public void setBalanceFreezer(BalanceFreezer balanceFreezer)
      Setter for the balance freezer needed to freeze accounts
      Parameters:
      balanceFreezer - Instance of balance freezer needed to freeze accounts
    • startMysqlBalanceUpdate

      public void startMysqlBalanceUpdate(boolean start, boolean redundancy)
      If anyone wants BalanceManager to update mysql balance as well, then this method must be called with true By default BalanceManager will not update mysql balance.
      Parameters:
      start - if mysql balance update is required then true. Otherwise, false.
      redundancy - If redundancy is running for this BalanceManager then mysql balance update will be as fast as possible, without any sleep. otherwise, mysql update will be periodical.
    • addOrgBilledAmount

      public void addOrgBilledAmount(long orgClientID, double billedAmount) throws UnsupportedOperationException
      Adds billed amount to total bill for corresponding account id
      Parameters:
      orgClientID - originating client id for which bill should be added
      billedAmount - billed amount that should be added
      Throws:
      UnsupportedOperationException
    • addTerBilledAmount

      public double addTerBilledAmount(long terClientID, double billedAmount) throws UnsupportedOperationException
      Adds billed amount to total billed amount for corresponding account id
      Parameters:
      terClientID - terminating account id for which bill has happened
      billedAmount - billed amount that should be added in total bill
      Returns:
      the available local balance after this billed amount has been added to ter balance.
      Throws:
      UnsupportedOperationException
    • getBalanceToSync

      public void getBalanceToSync(List<LeaseDTO> list, boolean syncAll)
      Get all the instances of LeaseDTO those needed to be synced.
      Parameters:
      list - will contain those instances of LeaseDTO
      syncAll - if we want all the instances, this value should be true.
    • getAllAccountID

      public Set<Long> getAllAccountID()
      Get the set of all account id present in this balance manager.
      Returns:
      the set of all account id present in this balance manager.
    • mitigatePossibleBalanceMismatch

      public boolean mitigatePossibleBalanceMismatch(long accountID)
      This method will call balance mitigatory process to resolve any dispute in balance. It is not expected to call frequently as balance mitigation process is costly, and it will freeze the account for a certain time period.
      Parameters:
      accountID - The account id which need to be mitigated.
      Returns:
      true, if balance mitigation process is successful, otherwise, return false.
    • setBalance

      public boolean setBalance(long accountID, double balance, double credit)
      Set the balance of the given account id to the given amount. Balance will be set in both redis and mysql. This process may take time. It will freeze the account for the time being, so every process who is using this balance will stop all operations related to the balance. And it will follow the procedure as 1. Send the account freeze request to Channels.BALANCE_FREEZE_CHANNEL of the given account id. 2. Wait sometimes for everyone to respond. 3. Set the balance in mysql to the given amount. 4. Set the balance in redis to the given amount. 5. Send the account unfreeze request to Channels.BALANCE_FREEZE_CHANNEL of the given account id.
      Parameters:
      accountID - the account ID for which balance to be set.
      balance - balance amount to be set.
      credit - credit amount to be set.
      Returns:
      true, if the operation is successful, otherwise, return false.
    • syncAllAccounts

      public void syncAllAccounts(Collection<Long> accountsToSync) throws Exception
      Method to sync balance of the accounts present in failed SBC. First, this will broadcast the Freeze Request to Balance Managers. After waiting and receiving ACK and freeze complete messages back from BMs, it will overwrite the balance of the accounts from MySQL to Redis. Then it will broadcast the unfreeze request and will wait till the frozen accounts are unfrozen.
      Parameters:
      accountsToSync - Hashmap of the accounts that were present in the failed SBC and need to be synced
      Throws:
      Exception - InterruptedException ExecutionException
    • findTargetAccounts

      public Collection<Long> findTargetAccounts(String failedBMId) throws Exception
      Method to find the account IDs which were present in the failed SBC/Balance Manager
      Parameters:
      failedBMId - Identifier of the SBC/ BalanceManager that failed
      Returns:
      HashSet of the accounts that were present in the crashed SBC
      Throws:
      Exception - InterruptedException ExecutionException
    • saveRedisCall

      public void saveRedisCall(RedisCallDTO redisCallDTO)
      Whenever any redis call is required by LeaseDTO asynchronously, this method must be called with an instance of RedisCallDTO. Which will be picked by an instance of RedisCaller and will be executed
      Parameters:
      redisCallDTO - the instance of RedisCallDTO which should be executed by RedisCaller as soon as possible.
    • setEnableRedisCall

      public void setEnableRedisCall(boolean enableRedisCall)
    • changeLeaseDTOStatus

      public void changeLeaseDTOStatus(long accountID, LeaseDTOStatus status)
      change the LeaseDTO validAccountID status.
      Parameters:
      accountID -
      status -
    • detectBalanceMismatch

      public void detectBalanceMismatch()
      Automatically detect balance mismatch if there is any. this method is applicable for detecting balance mismatch when only one instance of Balance Manager is running.
    • updateMysqlBalance

      public void updateMysqlBalance(Map<Long,? extends BalanceStatus> balanceMap)
      Update the value of BalanceStatus.setMysqlAmount(double) for all the instance of BalanceStatus of the given map. The amount to be set is taken from MysqlBalanceUpdater.getMysqlBalance(long) method.
      Parameters:
      balanceMap - map of BalanceStatus to be updated.
    • onProcessShutdown

      public void onProcessShutdown(boolean returnBalance)
      We have taken advanced amount from redis cluster, so When system is getting shut down, all the available cached balance should be returned to redis, otherwise some money will be lost. and calculation mismatch will happen between redis cluster and mysql. This method should be called when the process is going to shut down. This will also remove the identifier of this Balance Manager from account key in Redis
      Parameters:
      returnBalance - If we want all the local balance to return in redis cluster then this value should be true, otherwise this value should be false. If the application is running in standalone or running as master this value should be true. It is considered that if the application is running in redundancy mode only master should return balance in redis cluster and slave should not.