package example;
public final class RouteScope implements AutoCloseable {
    private static final ThreadLocal<String> CURRENT=new ThreadLocal<>();
    private final String previous;
    private boolean closed;
    private RouteScope(String key){
        if(key==null||key.isBlank())throw new IllegalArgumentException("Route required");
        previous=CURRENT.get();CURRENT.set(key);
    }
    public static RouteScope use(String key){return new RouteScope(key);}
    public static String required(){
        String key=CURRENT.get();
        if(key==null)throw new IllegalStateException("Missing route");
        return key;
    }
    @Override public void close(){
        if(!closed){if(previous==null)CURRENT.remove();else CURRENT.set(previous);closed=true;}
    }
}
