ApiRequestCountingFilter.java

/*
 * Copyright 2026 Global Crop Diversity Trust
 * Licensed under the Apache License, Version 2.0
 * See LICENSE file in project root folder or http://www.apache.org/licenses/LICENSE-2.0
 */

package org.gringlobal.metrics;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import org.apache.commons.lang3.StringUtils;

@Slf4j
public class ApiRequestCountingFilter extends OncePerRequestFilter {

	private static final AntPathMatcher MATCHER = new AntPathMatcher();

	private final ApiRequestMetrics metrics;
	private final List<String> excludedPaths;

	public ApiRequestCountingFilter(ApiRequestMetrics metrics, String excludedPaths) {
		this.metrics = metrics;
		this.excludedPaths = parseExcludedPaths(excludedPaths);
	}

	static List<String> parseExcludedPaths(String excludedPaths) {
		if (StringUtils.isBlank(excludedPaths)) {
			return Collections.emptyList();
		}
		return Arrays.stream(excludedPaths.split(","))
			.map(String::trim)
			.filter(StringUtils::isNotBlank)
			.collect(Collectors.toList());
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		String sid = null;
		var auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth != null) {
			sid = auth.getName();
		}

		if (!isExcluded(request)) {
			try {
				metrics.incrementForSid(sid);
			} catch (Throwable e) {
				// Catch all errors, log and continue processing the request
				log.warn("Error incrementing API counter: {}", e.getMessage(), e);
			}
		}

		filterChain.doFilter(request, response);
	}

	private boolean isExcluded(HttpServletRequest request) {
		if (excludedPaths.isEmpty()) {
			return false;
		}
		String path = request.getServletPath();
		for (String pattern : excludedPaths) {
			if (MATCHER.match(pattern, path)) {
				log.debug("Skipping API request count for excluded path: {}", path);
				return true;
			}
		}
		return false;
	}
}