/*
 * Copyright (c) 2018 無色眼镜
 *
 * 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 club.dawdler.breaker.filter;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import club.dawdler.breaker.CircuitBreaker;
import club.dawdler.breaker.CircuitBreakerOpenException;
import club.dawdler.breaker.LocalCircuitBreaker;
import club.dawdler.client.filter.DawdlerClientFilter;
import club.dawdler.client.filter.FilterChain;
import club.dawdler.client.filter.RequestWrapper;
import club.dawdler.core.annotation.Order;
import club.dawdler.core.bean.RequestBean;
import club.dawdler.core.thread.InvokeFuture;

/**
 * @author jackson.song
 * @version V1.0
 * 过滤器用来做熔断拦截
 */
@Order(1)
public class CircuitBreakerFilter implements DawdlerClientFilter {
	private static final Logger logger = LoggerFactory.getLogger(CircuitBreakerFilter.class);
	private final ConcurrentHashMap<String, CircuitBreaker> breakers = new ConcurrentHashMap<>();
	private final ConcurrentHashMap<FallbackKey, Fallback> fallbackCache = new ConcurrentHashMap<>();
	/**
	 * key -> 生效配置的指纹. 同 key 不同参数时先到先得, 被忽略的一方只告警一次.
	 */
	private final ConcurrentHashMap<String, String> effectiveFingerprints = new ConcurrentHashMap<>();
	private final ConcurrentHashMap<String, String> paramMismatchWarned = new ConcurrentHashMap<>();

	@Override
	public boolean beforeConnection() {
		return true;
	}

	@Override
	public Object doFilter(RequestBean request, FilterChain chain) throws Exception {
		RequestWrapper rw = (RequestWrapper) request;

		club.dawdler.core.annotation.CircuitBreaker cb = rw.getCircuitBreaker();
		if (cb == null) {
			return chain.doFilter(request);
		}
		String unique = "".equals(cb.breakerKey())
				? (request.getServiceName() + "#" + request.getMethodName())
				: cb.breakerKey();
		CircuitBreaker circuitBreaker = breakers.get(unique);
		if (circuitBreaker == null) {
			circuitBreaker = new LocalCircuitBreaker(cb); 
			circuitBreaker.addStateChangeListener((from, to) -> logStateChange(unique, from, to));
			CircuitBreaker pre = breakers.putIfAbsent(unique, circuitBreaker);
			if (pre != null) {
				circuitBreaker = pre;
			} else {
				effectiveFingerprints.putIfAbsent(unique, fingerprint(cb));
			}
		}
		warnIfParamsMismatch(unique, cb);
		long ticket = circuitBreaker.acquire();
		if (ticket != CircuitBreaker.REJECTED) {
			ExceptionClassifier classifier = new ExceptionClassifier(cb);
			try {
				Object result = chain.doFilter(request);
				if (rw.isAsync()) {
					InvokeFuture<Object> future = rw.getFuture();
					if (future != null) {
						future.setOutcomeCallback(new AsyncOutcomeRecorder(circuitBreaker, ticket, classifier));
					} else {
						circuitBreaker.recordIgnored(ticket);
					}
				} else {
					circuitBreaker.complete(ticket, false);
				}
				return result;
			} catch (Throwable e) {
				if (classifier.isFailure(e)) {
					circuitBreaker.complete(ticket, true);
				} else {
					circuitBreaker.recordIgnored(ticket);
				}
				throw e;
			}
		} else {
			Class<?> c = rw.getProxyInterface();
			String fallbackMethod = cb.fallbackMethod();
			if (c != null && !"".equals(fallbackMethod)) {
				try {
					Fallback fallback = fallbackCache.computeIfAbsent(
							new FallbackKey(c, fallbackMethod, List.of(request.getTypes())), Fallback::create);
					return invokeFallback(fallback, request.getArgs());
				} catch (Throwable e) {
					logger.error("Failed to invoke fallback {} of {} on open breaker {}, the error will be rethrown.",
							fallbackMethod, c.getName(), unique, e);
					throw e;
				}
			}

			throw new CircuitBreakerOpenException(
					"CircuitBreaker State : " + circuitBreaker.getState().state().name() + ", unique : " + unique);
		}
	}

	/**
	 * 同一 breakerKey 被不同参数共享时, 实际生效的只有最先创建的那份配置, 被忽略的一方必须告警.
	 * 每个 (key, 被忽略的指纹) 只告警一次.
	 */
	private void warnIfParamsMismatch(String unique, club.dawdler.core.annotation.CircuitBreaker cb) {
		String incoming = fingerprint(cb);
		String effective = effectiveFingerprints.get(unique);
		if (effective == null || effective.equals(incoming) || incoming.equals(paramMismatchWarned.get(unique))) {
			return;
		}
		paramMismatchWarned.put(unique, incoming);
		logger.warn("Circuit breaker [{}] is shared by different annotations/parameters,"
				+ " the first-created configuration takes effect and the others are ignored."
				+ " Effective: [{}], ignored: [{}]", unique, effective, incoming);
	}

	private static String fingerprint(club.dawdler.core.annotation.CircuitBreaker cb) {
		return "intervalInMs=" + cb.intervalInMs() + ",windowsCount=" + cb.windowsCount()
				+ ",sleepWindowInMilliseconds=" + cb.sleepWindowInMilliseconds()
				+ ",requestVolumeThreshold=" + cb.requestVolumeThreshold()
				+ ",errorThresholdPercentage=" + cb.errorThresholdPercentage();
	}

	private static void logStateChange(String unique, CircuitBreaker.State from, CircuitBreaker.State to) {
		if (to == CircuitBreaker.State.OPEN) {
			logger.warn("Circuit breaker [{}] tripped open ({} -> {}), requests are rejected"
					+ " until the sleep window elapses", unique, from, to);
		} else if (to == CircuitBreaker.State.CLOSE) {
			logger.info("Circuit breaker [{}] closed ({} -> {}), traffic resumed", unique, from, to);
		} else {
			logger.info("Circuit breaker [{}] entered half-open probing ({} -> {}),"
					+ " a single trial request is admitted", unique, from, to);
		}
	}

	/**
	 * 异步调用的完成回放: future成功计成功, 失败按分类器计失败/忽略.
	 * 与同步路径complete(ticket, ...)完全同一套语义, 只是推迟到结果已知的那一刻.
	 */
	private static final class AsyncOutcomeRecorder implements club.dawdler.core.thread.InvokeFuture.OutcomeCallback {

		private final CircuitBreaker circuitBreaker;
		private final long ticket;
		private final ExceptionClassifier classifier;

		private AsyncOutcomeRecorder(CircuitBreaker circuitBreaker, long ticket, ExceptionClassifier classifier) {
			this.circuitBreaker = circuitBreaker;
			this.ticket = ticket;
			this.classifier = classifier;
		}

		@Override
		public void onOutcome(Throwable cause) {
			if (cause == null) {
				circuitBreaker.complete(ticket, false);
				return;
			}
			if (classifier.isFailure(cause)) {
				circuitBreaker.complete(ticket, true);
			} else {
				circuitBreaker.recordIgnored(ticket);
			}
		}

	}

	private static Object invokeFallback(Fallback fallback, Object[] args) throws Exception {
		if (fallback.staticMethod != null) {
			return fallback.staticMethod.invoke(null, args);
		}
		try {
			return fallback.boundDefaultMethod.invokeWithArguments(args);
		} catch (Throwable t) {
			throw new InvocationTargetException(t);
		}
	}

	private record FallbackKey(Class<?> proxyInterface, String fallbackMethod, List<Class<?>> parameterTypes) {
	}

	private static final class Fallback {
		private static final ClassValue<Object> LOCAL_RECEIVERS = new ClassValue<>() {
			@Override
			protected Object computeValue(Class<?> iface) {
				return Proxy.newProxyInstance(iface.getClassLoader(), new Class<?>[] { iface },
						(proxy, m, a) -> {
							throw new UnsupportedOperationException(
									"Other methods of the interface must not be invoked inside a fallback method"
											+ " (the remote service is unavailable while degrading): " + m.getName());
						});
			}
		};

		final Method staticMethod;
		final MethodHandle boundDefaultMethod;

		private Fallback(Method staticMethod, MethodHandle boundDefaultMethod) {
			this.staticMethod = staticMethod;
			this.boundDefaultMethod = boundDefaultMethod;
		}

		static Fallback create(FallbackKey key) {
			Class<?> iface = key.proxyInterface();
			Method method;
			try {
				method = iface.getMethod(key.fallbackMethod(), key.parameterTypes().toArray(new Class<?>[0]));
			} catch (NoSuchMethodException e) {
				throw new RuntimeException("Fallback method not found: " + key.fallbackMethod(), e);
			}
			if (Modifier.isStatic(method.getModifiers())) {
				return new Fallback(method, null);
			}
			if (!method.isDefault()) {
				throw new RuntimeException("Fallback method must be a static or default method of the interface: " + method);
			}
			try {
				MethodHandle handle = MethodHandles.privateLookupIn(iface, MethodHandles.lookup())
						.findSpecial(iface, method.getName(),
								MethodType.methodType(method.getReturnType(), method.getParameterTypes()), iface)
						.bindTo(localReceiver(iface));
				return new Fallback(null, handle);
			} catch (NoSuchMethodException e) {
				throw new RuntimeException("Fallback method not found: " + method, e);
			} catch (IllegalAccessException e) {
				throw new RuntimeException("Unable to access the default fallback method " + method
						+ ", in a modular deployment the package of the interface must be opened to the"
						+ " dawdler.circuit.breaker module", e);
			}
		}

		private static Object localReceiver(Class<?> iface) {
			return LOCAL_RECEIVERS.get(iface);
		}
	}

}
