package example.obrh;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.Semaphore;

/** Java 17 synchronous example. Construct ONCE per JVM/capacity domain, not per request. */
public final class EndpointBulkheads {
    // Illustrative aggregate provider work; separate from the Tomcat request gate.
    // Coupled profile: 12 shared-route HTTP connections in HttpPoolExample, A <= 8,
    // B <= 4, and no other unbudgeted users of that transport route.
    private final Semaphore providerTotal = new Semaphore(12);
    // Bounded canonical identities from trusted operation classification.
    private final Map<String, Semaphore> operations = Map.of(
            "providerA.balance", new Semaphore(8),
            "providerA.payment", new Semaphore(4));

    public <T> T invoke(String operation, long deadlineNanos, Callable<T> attempt)
            throws Exception {
        Semaphore local = operations.get(operation);
        if (local == null) {
            throw new IllegalArgumentException("Unknown operation");
        }
        if (System.nanoTime() - deadlineNanos >= 0 || !providerTotal.tryAcquire()) {
            throw new RejectedExecutionException("Provider work budget exhausted");
        }
        boolean admittedOperation = false;
        try {
            admittedOperation = local.tryAcquire();
            if (!admittedOperation) {
                throw new RejectedExecutionException("Operation work budget exhausted");
            }
            if (System.nanoTime() - deadlineNanos >= 0) {
                throw new RejectedExecutionException("Deadline expired before attempt");
            }
            // Borrow HTTP/DB resources INSIDE this scope with remaining-deadline waits.
            // This synchronous Callable must return only after underlying work stops.
            // Release its response/connection in its own try-with-resources.
            return attempt.call();
        } finally {
            if (admittedOperation) {
                local.release();
            }
            providerTotal.release();
        }
    }
    // Retry outside invoke: backoff holds no attempt permit/HTTP lease.
    // Retain logical request admission until the whole request really completes.
    // Permits bound competition, not scheduling guarantees. Useful B capacity also
    // needs coherent pool sharing/lease behavior and adequate CPU/DB/provider capacity.
}
