Package com.reve.balancemanager
Class BalanceManager
java.lang.Object
com.reve.balancemanager.BalanceManager
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 Summary
FieldsModifier and TypeFieldDescriptionstatic final Stringstatic final Stringstatic final com.reve.utils.DoubleFormatterThe instance that will be used to clip double value to 6 decimal places.static final doubleValue to increase or decrease when adjusting lease chunk with demandstatic final intstatic final doubleMaximum lease chunk Balance Manager tries to store locally from Redis for an account whenLeaseDTO.getLease(double, LeaseResponse, boolean)is calledstatic final doubleMaximum amount of money which can stay in available local balance ofLeaseDTO.static final doubleMinimum lease chunk Balance Manager tries to store locally from Redis for an account whenLeaseDTO.getLease(double, LeaseResponse, boolean)is calledstatic final longTime above which a lease request is received in Redis, we will decrease local balance chunk for a LeaseDTOstatic final longTime under which a lease request is received in Redis, we will increase local balance chunk for a LeaseDTOstatic final Stringstatic final Stringstatic final longWhen 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 -
Constructor Summary
ConstructorsConstructorDescriptionBalanceManager(String identifier, com.reve.redis.cluster.ClusterObserver clusterObserver) Create an instance ofBalanceManager.BalanceManager(String identifier, String redisHost, int redisPort, String redisPass, com.reve.websocket.ssl.SSLConfiguration sslConfiguration) Create an instance ofBalanceManager.BalanceManager(String identifier, String redisHost, int redisPort, String redisPass, com.reve.websocket.ssl.SSLConfiguration sslConfiguration, int connectionCount) Create an instance ofBalanceManager. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddOrgBilledAmount(long orgClientID, double billedAmount) Adds billed amount to total bill for corresponding account iddoubleaddTerBilledAmount(long terClientID, double billedAmount) Adds billed amount to total billed amount for corresponding account idfindTargetAccounts(String failedBMId) Method to find the account IDs which were present in the failed SBC/Balance ManagerGet the set of all account id present in this balance manager.voidgetBalanceToSync(List<LeaseDTO> list, boolean syncAll) Get all the instances ofLeaseDTOthose needed to be synced.com.reve.redis.cluster.ClusterObserverGetter forclusterObserverdoublegetLease(long accountId, double leaseAmount, LeaseResponse response) Try to get a lease from this account balance.doublegetLease(long accountId, double leaseAmount, LeaseResponse response, boolean partialEnabled) Try to get a lease from this account balance.getLeaseDTO(long accountID) Get the instance ofLeaseDTOmapped with the given account id.doublegetMysqlBalance(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.doubleGetter forpubSubPublisherdoublevoidinitLeaseDTO(Collection<Long> clientIDs) Initialize the instances ofLeaseDTOfor all the given clients at the startup.booleanisFrozen(long accountID) Check if the given account id is now in frozen mode or not.voidloadBalanceInRedis(long accountId) Successful completion of this method will ensure the presence of thisLeaseDTOin redis cluster Either in the nearest node or In the far node.booleanmitigatePossibleBalanceMismatch(long accountID) This method will call balance mitigatory process to resolve any dispute in balance.voidonProcessShutdown(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.voidprocessAccFreezeAck(long accountID, String balanceManagerID) ProcessMessageType.ACK_FREEZE_REQUESTmessage from the given balance manager.voidprocessAccFreezeCompete(long accountID, String balanceManagerID) ProcessMessageType.FREEZE_COMPLETEmessage from the given balance manager.voidprocessAccFreezeRequest(long accountId) When a freeze request is received from mitigator this method will be called.voidprocessAccUnFreezeCompete(long accountID, String balanceManagerID) ProcessMessageType.UNFREEZE_COMPLETEmessage from the given balance manager.voidprocessAccUnfreezeRequest(long accountId) When an unfreeze request is received from mitigator this method will be called.voidrefundBalance(long accountID, double balance) For some unsuccessful case we may need to refund the balance of a transaction.doublereturnLease(long accountId, double leaseAmount) Extra amount left at the end of the call is added to the lease (make sure to provide +ve value).voidreturnLeaseOnRequest(long accountId, boolean returnFullAmount) In case the balance of an account gets exhausted, balance manager will broadcast an empty status to all BMs.voidsaveRedisCall(RedisCallDTO redisCallDTO) Whenever any redis call is required byLeaseDTOasynchronously, this method must be called with an instance ofRedisCallDTO.booleansetBalance(long accountID, double balance, double credit) Set the balance of the given account id to the given amount.voidsetBalanceFreezer(BalanceFreezer balanceFreezer) Setter for the balance freezer needed to freeze accountsvoidsetEnableRedisCall(boolean enableRedisCall) booleansetMysqlBalance(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.voidsetPercentageToRelease(double percentageToRelease) Setter for the percentage which Balance Manager will release whenreturnLeaseOnRequest(long, boolean)is calledvoidsetThresholdToReleaseFullAmount(double thresholdToReleaseFullAmount) Setter to configure threshold under which Balance Manager will release the full available amountvoidstartMysqlBalanceUpdate(boolean start, boolean redundancy) If anyone wantsBalanceManagerto update mysql balance as well, then this method must be called with true By defaultBalanceManagerwill not update mysql balance.voidsyncAllAccounts(Collection<Long> accountsToSync) Method to sync balance of the accounts present in failed SBC.voidupdateMysqlBalance(Map<Long, ? extends BalanceStatus> balanceMap) Update the value ofBalanceStatus.setMysqlAmount(double)for all the instance ofBalanceStatusof the given map.
-
Field Details
-
APPLICATION_NAME
- See Also:
-
VERSION
- See Also:
-
doubleFormatter
public static final com.reve.utils.DoubleFormatter doubleFormatterThe instance that will be used to clip double value to 6 decimal places. -
TOKENIZER
- See Also:
-
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_CHUNKMinimum lease chunk Balance Manager tries to store locally from Redis for an account whenLeaseDTO.getLease(double, LeaseResponse, boolean)is called- See Also:
-
MAXIMUM_LEASE_CHUNK
public static final double MAXIMUM_LEASE_CHUNKMaximum lease chunk Balance Manager tries to store locally from Redis for an account whenLeaseDTO.getLease(double, LeaseResponse, boolean)is called- See Also:
-
MAXIMUM_LOCAL_BALANCE
public static final double MAXIMUM_LOCAL_BALANCEMaximum amount of money which can stay in available local balance ofLeaseDTO. 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_STEPValue 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_CHUNKTime 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_CHUNKTime 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_RELEASEWhen 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 ofBalanceManager.- 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 clustersslConfiguration- if ssl/tls is configured in the redis cluster, then an instance ofSSLConfigurationmust 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 nullconnectionCount- 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 ofBalanceManager.- 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 clustersslConfiguration- if ssl/tls is configured in the redis cluster, then an instance ofSSLConfigurationmust 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 ofBalanceManager.- Parameters:
identifier- Balance Manager unique identifier. Can not contain these characters in the string : "-", "+", "*", ":", "\", "$", "%", "(", ")". Can not be null or empty.clusterObserver- Cluster Observer of whichBalanceManagerwill be part of.- Throws:
Exception- if occurs any while loading cluster information
-
-
Method Details
-
initLeaseDTO
Initialize the instances ofLeaseDTOfor all the given clients at the startup. This method must be called just after creating the instance ofBalanceManager- Parameters:
clientIDs- list of client id, which should be loaded at startup.
-
getPublisher
Getter forpubSubPublisher- 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 tablecredit- 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
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 fromleaseAmount- The amount to be added to the leaseresponse- 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 fromleaseAmount- The amount to be added to the leaseresponse- 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 call is added to the lease (make sure to provide +ve value). The optional total bill, if present, is also queued to be updated in the db at next update cycle.- Parameters:
accountId- Account id the lease should be returned toleaseAmount- remaining lease amount. make sure that it's +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 happenbalance- amount of balance should be refunded.
-
getLeaseDTO
Get the instance ofLeaseDTOmapped with the given account id. If there is none, then create one and return -
loadBalanceInRedis
public void loadBalanceInRedis(long accountId) Successful completion of this method will ensure the presence of thisLeaseDTOin 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 clusterNodeWhich will be needed for all consecutive call- Parameters:
accountId- The account id of a client whose balance to be loaded into redis.
-
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
ProcessMessageType.ACK_FREEZE_REQUESTmessage from the given balance manager.- Parameters:
accountID- Account id for which ack message is received.balanceManagerID- Identification ofBalanceManagerfrom where this message is received.
-
processAccFreezeCompete
ProcessMessageType.FREEZE_COMPLETEmessage from the given balance manager.- Parameters:
accountID- Account id for whichMessageType.FREEZE_COMPLETEmessage is received.balanceManagerID- Identification ofBalanceManagerfrom where this message is received.
-
processAccUnFreezeCompete
ProcessMessageType.UNFREEZE_COMPLETEmessage from the given balance manager.- Parameters:
accountID- Account id for whichMessageType.UNFREEZE_COMPLETEmessage is received.balanceManagerID- Identification ofBalanceManagerfrom where this message is received.
-
getIdentifier
- Returns:
- Getter for identifier for this Balance Manager. The identifier is unique.
-
getClusterObserver
public com.reve.redis.cluster.ClusterObserver getClusterObserver()Getter forclusterObserver- Returns:
- The
ClusterObserverinstance 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 whenreturnLeaseOnRequest(long, boolean)is called- Parameters:
percentageToRelease- percentage tp release from available balance
-
getPubSubPublisher
- Returns:
- Getter for the PubSub publisher which is used for communication
-
setBalanceFreezer
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 wantsBalanceManagerto update mysql balance as well, then this method must be called with true By defaultBalanceManagerwill not update mysql balance.- Parameters:
start- if mysql balance update is required then true. Otherwise, false.redundancy- If redundancy is running for thisBalanceManagerthen 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 addedbilledAmount- 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 happenedbilledAmount- 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
Get all the instances ofLeaseDTOthose needed to be synced.- Parameters:
list- will contain those instances ofLeaseDTOsyncAll- if we want all the instances, this value should be true.
-
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 toChannels.BALANCE_FREEZE_CHANNELof 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 toChannels.BALANCE_FREEZE_CHANNELof 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
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
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
Whenever any redis call is required byLeaseDTOasynchronously, this method must be called with an instance ofRedisCallDTO. Which will be picked by an instance ofRedisCallerand will be executed- Parameters:
redisCallDTO- the instance ofRedisCallDTOwhich should be executed byRedisCalleras soon as possible.
-
setEnableRedisCall
public void setEnableRedisCall(boolean enableRedisCall) -
updateMysqlBalance
Update the value ofBalanceStatus.setMysqlAmount(double)for all the instance ofBalanceStatusof the given map. The amount to be set is taken fromMysqlBalanceUpdater.getMysqlBalance(long)method.- Parameters:
balanceMap- map ofBalanceStatusto 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.
-