All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.bucket4j.caffeine.CaffeineProxyManager Maven / Gradle / Ivy

The newest version!
/*-
 * ========================LICENSE_START=================================
 * Bucket4j
 * %%
 * Copyright (C) 2015 - 2020 Vladimir Bukhtoyarov
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =========================LICENSE_END==================================
 */

package io.github.bucket4j.caffeine;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Expiry;

import io.github.bucket4j.distributed.ExpirationAfterWriteStrategy;
import io.github.bucket4j.distributed.proxy.AbstractProxyManager;
import io.github.bucket4j.distributed.proxy.ClientSideConfig;
import io.github.bucket4j.distributed.remote.CommandResult;
import io.github.bucket4j.distributed.remote.MutableBucketEntry;
import io.github.bucket4j.distributed.remote.RemoteBucketState;
import io.github.bucket4j.distributed.remote.Request;

import java.time.Duration;
import java.util.concurrent.CompletableFuture;

/**
 * The extension of Bucket4j library addressed to support Caffeine caching library.
 */
public class CaffeineProxyManager extends AbstractProxyManager {

    private final Cache cache;

    CaffeineProxyManager(Bucket4jCaffeine.CaffeineProxyManagerBuilder builder) {
        super(builder.getClientSideConfig());

        this.cache = builder.cacheBuilder.expireAfter(new Expiry() {
                private final ExpirationAfterWriteStrategy expiration = getClientSideConfig().getExpirationAfterWriteStrategy()
                    .orElse(ExpirationAfterWriteStrategy.none());

                @Override
                public long expireAfterCreate(K key, RemoteBucketState bucketState, long currentTime) {
                    long ttlNanos = expiration.calculateTimeToLiveMillis(bucketState, currentTimeNanos()) * 1_000_000;
                    return ttlNanos < 0 ? Long.MAX_VALUE : ttlNanos;
                }

                @Override
                public long expireAfterUpdate(K key, RemoteBucketState bucketState, long currentTime, long currentDuration) {
                    long ttlNanos = expiration.calculateTimeToLiveMillis(bucketState, currentTimeNanos()) * 1_000_000;
                    return ttlNanos < 0 ? Long.MAX_VALUE : ttlNanos;
                }

                @Override
                public long expireAfterRead(K key, RemoteBucketState bucketState, long currentTime, long currentDuration) {
                    long ttlNanos = expiration.calculateTimeToLiveMillis(bucketState, currentTimeNanos()) * 1_000_000;
                    return ttlNanos < 0 ? Long.MAX_VALUE : ttlNanos;
                }
            })
            .build();
    }

    /**
     * @deprecated use {@link Bucket4jCaffeine#builderFor(Caffeine)}
     */
    @Deprecated
    public CaffeineProxyManager(Caffeine builder, Duration keepAfterRefillDuration) {
        this(builder, keepAfterRefillDuration, ClientSideConfig.getDefault());
    }

    /**
     * @deprecated use {@link Bucket4jCaffeine#builderFor(Caffeine)}
     */
    @Deprecated
    public CaffeineProxyManager(Caffeine builder, Duration keepAfterRefillDuration, ClientSideConfig clientSideConfig) {
        super(clientSideConfig);
        this.cache = builder
            .expireAfter(new Expiry() {
                @Override
                public long expireAfterCreate(K key, RemoteBucketState bucketState, long currentTime) {
                    long currentTimeNanos = currentTimeNanos();
                    long nanosToFullRefill = bucketState.calculateFullRefillingTime(currentTimeNanos);
                    return nanosToFullRefill + keepAfterRefillDuration.toNanos();
                }

                @Override
                public long expireAfterUpdate(K key, RemoteBucketState bucketState, long currentTime, long currentDuration) {
                    long currentTimeNanos = currentTimeNanos();
                    long nanosToFullRefill = bucketState.calculateFullRefillingTime(currentTimeNanos);
                    return nanosToFullRefill + keepAfterRefillDuration.toNanos();
                }

                @Override
                public long expireAfterRead(K key, RemoteBucketState bucketState, long currentTime, long currentDuration) {
                    long currentTimeNanos = currentTimeNanos();
                    long nanosToFullRefill = bucketState.calculateFullRefillingTime(currentTimeNanos);
                    return nanosToFullRefill + keepAfterRefillDuration.toNanos();
                }
            })
            .build();
    }

    @Override
    public boolean isExpireAfterWriteSupported() {
        return true;
    }

    /**
     * Returns the cache that is used for storing the buckets
     *
     * @return the cache that is used for storing the buckets
     */
    public Cache getCache() {
        return cache;
    }

    @Override
    public  CommandResult execute(K key, Request request) {
        CommandResult[] resultHolder = new CommandResult[1];

        cache.asMap().compute(key, (K k, RemoteBucketState previousState) -> {
            Long clientSideTime = request.getClientSideTime();
            long timeNanos = clientSideTime != null ? clientSideTime : System.currentTimeMillis() * 1_000_000;
            MutableBucketEntry entryWrapper = new MutableBucketEntry(previousState == null ? null : previousState.copy());
            resultHolder[0] = request.getCommand().execute(entryWrapper, timeNanos);
            return entryWrapper.exists() ? entryWrapper.get() : null;
        });

        return resultHolder[0];
    }

    @Override
    public boolean isAsyncModeSupported() {
        return true;
    }

    @Override
    public  CompletableFuture> executeAsync(K key, Request request) {
        CommandResult result = execute(key, request);
        return CompletableFuture.completedFuture(result);
    }

    @Override
    public void removeProxy(K key) {
        cache.asMap().remove(key);
    }

    @Override
    protected CompletableFuture removeAsync(K key) {
        cache.asMap().remove(key);
        return CompletableFuture.completedFuture(null);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy