package example.obrh;

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.SemaphoreValve;

/**
 * Tomcat 9 extension-point example. Compile against the installed Catalina API.
 * Scope is ONE Context pipeline instance, never one instance per URL.
 * Does not implement authentication or a full asynchronous request-lifetime cap.
 */
public final class ControlledSemaphoreValve extends SemaphoreValve {
    // Exact proposed paths relative to the selected Context; no prefix bypass.
    private static final String LIVENESS = "/actuator/health/liveness";
    private static final String LB_DIAGNOSTIC = "/internal/lb-system-health";
    // Set only by a trusted earlier container guard after authorization + finite budget.
    // A servlet filter later in the pipeline is too late to establish this attribute.
    public static final String TRUSTED_LB_DIAGNOSTIC =
            "example.obrh.trustedLbDiagnostic";

    @Override
    public boolean controlConcurrency(Request request, Response response) {
        String context = request.getContextPath();
        String uri = request.getRequestURI();
        boolean get = "GET".equals(request.getMethod());
        if (get && (context + LIVENESS).equals(uri)) {
            return false;
        }
        if (get && (context + LB_DIAGNOSTIC).equals(uri)
                && Boolean.TRUE.equals(request.getAttribute(TRUSTED_LB_DIAGNOSTIC))) {
            return false;
        }
        // Ordinary readiness dispatch, other methods, aliases and unknown paths count.
        return true;
    }
}
