/*
 *  The MIT License
 *  Copyright (c) 2019- Nordic Institute for Interoperability Solutions (NIIS)
 *  Copyright (c) 2018 Estonian Information System Authority (RIA),
 *  Nordic Institute for Interoperability Solutions (NIIS), Population Register Centre (VRK)
 *  Copyright (c) 2015-2017 Estonian Information System Authority (RIA), Population Register Centre (VRK)
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */
package org.niis.xroad.common.api.throttle;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import io.github.bucket4j.Bucket;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import static io.github.bucket4j.Bandwidth.simple;

/**
 * Rate-limits requests
 */
@Slf4j
public class IpThrottlingFilter implements Filter {
    private static final int HTTP_STATUS_TOO_MANY_REQUESTS = 429;

    private final IpThrottlingFilterConfig ipThrottlingFilterConfig;
    private final LoadingCache<String, Bucket> bucketCache;

    public IpThrottlingFilter(IpThrottlingFilterConfig properties) {
        this.ipThrottlingFilterConfig = properties;
        //BandWidth is immutable and can be reused
        bucketCache = CacheBuilder.newBuilder()
                .maximumSize(properties.getRateLimitCacheSize())
                .expireAfterAccess(properties.getRateLimitExpireAfterAccessMinutes(), TimeUnit.MINUTES)
                .build(CacheLoader.from(this::createStandardBucket));
    }

    /**
     * create a new bucket
     */
    private Bucket createStandardBucket() {
        var builder = Bucket.builder();
        if (ipThrottlingFilterConfig.getRateLimitRequestsPerSecond() > 0) {
            builder.addLimit(simple(ipThrottlingFilterConfig.getRateLimitRequestsPerSecond(), Duration.ofSeconds(1)));
        }
        if (ipThrottlingFilterConfig.getRateLimitRequestsPerMinute() > 0) {
            builder.addLimit(simple(ipThrottlingFilterConfig.getRateLimitRequestsPerMinute(), Duration.ofMinutes(1)));
        }

        log.info("API access rate limiting initialized with {} req/sec and {} req/min",
                ipThrottlingFilterConfig.getRateLimitRequestsPerSecond(),
                ipThrottlingFilterConfig.getRateLimitRequestsPerMinute());
        return builder.build();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws
            IOException, ServletException {

        final var ip = servletRequest.getRemoteAddr();
        final Bucket bucket;

        try {
            bucket = bucketCache.get(ip);
        } catch (ExecutionException e) {
            throw new ServletException("Rate limit failure", e);
        }

        if (bucket.tryConsume(1)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            log.warn("Request rate limit exceeded for ip {}, responding with 429 TOO_MANY_REQUESTS", ip);
            if (servletResponse instanceof HttpServletResponse) {
                HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
                httpResponse.setContentType("application/json");
                httpResponse.setCharacterEncoding("UTF-8");
                httpResponse.addHeader("Connection", "close");
                httpResponse.setStatus(HTTP_STATUS_TOO_MANY_REQUESTS);
                httpResponse.getWriter().append("{\"status\":429}");
            }
        }
    }
}
