Skip to content

List of tokens #189

basanth-ivoyant started this conversation in General
List of tokens #189
Nov 11, 2021 · 2 comments

Hi -
Is there a way , where in we can fill the bucket with actual values and any of the consume methods, can return token values as list. I could write implementations of filler, which could query a source to fill the bucket with actual token values.

thank you,

Replies

Hello @basanth-ivoyant

About quiring actual tokens per each bandwidth:
There is VerboseApi and its asynchronous analog. That can be used to get any internal information about a bucket, see the comment in this issue as an example. You need to use getAvailableTokens on VerboseBucket

VerboseResult<Long> verboseResult = bucket.asVerbose().getAvailableTokens();
long[] availableTokens = BucketInvestigationUtil.getAvailableTokens(verboseResult);

////////////////////////////////////////////////////////////////////////
package io.github.bucket4j;

// This class needs to be placed to the io.github.bucket4j package in order to have access to the BucketState#getCurrentSize
public class BucketInvestigationUtil {
    
     public static long[] availableTokens getAvailableTokens(VerboseResult<Long> verboseResult) {
        BucketConfiguration configuration = verboseResult.getConfiguration();
        Bandwidth[] bandwidths = configuration.getBandwidths();
        BucketState state = verboseResult.getState();

        long[] availableTokens = new long[bandwidths.length];
        for (int i = 0; i < bandwidths.length; i++) {
            availableTokens[i] = state.getCurrentSize(i);
        }

        return availableTokens;
    }
}

Unfortunately, there is no clean way in the current API to set available tokens directly. I think this feature is reasonable and I will think about implementing it.

Fortunately, you can use a little bit of dirty workaround through java bucket.replaceConfiguration(newConfiguration, TokensInheritanceStrategy.RESET) together with specifying initial tokens, like this:

long newAvailableTokensValue = 50;
BucketConfiguration configuration = Bucket4j.configurationBuilder()
    .addLimit(
        Bandwidth.simple(100, Duration.ofMinutes(1)).withInitialTokens(newAvailableTokensValue)
     )
    .build();

// newAvailableTokensValue will replace current tokens because bucket state will be totally rewritten
bucket.replaceConfiguration(newConfiguration, TokensInheritanceStrategy.RESET)
0 replies

With version 6.4.0 desired behavior can be achieved in the following way:

VerboseResult<Long> result = bucket.asVerbose().getAvailableTokens();
long[] availableTokens  = result.getDiagnostics().getAvailableTokensPerEachBandwidth();
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants