/*
 * 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.distributed.transaction.aspect;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import club.dawdler.core.rpc.context.RpcContext;
import club.dawdler.distributed.transaction.TransactionStatus;
import club.dawdler.distributed.transaction.annotation.DistributedTransaction;
import club.dawdler.distributed.transaction.context.DistributedTransactionContext;
import club.dawdler.distributed.transaction.exception.DistributedTransactionCanceledException;
import club.dawdler.distributed.transaction.interceptor.TransactionInterceptInvoker;
import club.dawdler.distributed.transaction.interceptor.TransactionInterceptInvokerHolder;
import club.dawdler.distributed.transaction.message.MessageSender;
import club.dawdler.distributed.transaction.message.MessageSenderProvider;
import club.dawdler.distributed.transaction.repository.TransactionRepository;
import club.dawdler.distributed.transaction.repository.TransactionRepositoryProvider;
import club.dawdler.util.JsonProcessUtil;

/**
 * @author jackson.song
 * @version V1.0
 * aop拦截器 根据事务注解来做事务处理
 */
@Aspect
public class DistributedTransactionAspect {
	private static Logger logger = LoggerFactory.getLogger(DistributedTransactionAspect.class);

	private TransactionRepository transactionRepository = TransactionRepositoryProvider.getInstance()
			.getTransactionRepository();

	private MessageSender messageSender = MessageSenderProvider.getInstance().getMessageSender();

	@Pointcut("@annotation(club.dawdler.distributed.transaction.annotation.DistributedTransaction)")
	public void compensableService() {
	}

	@Around("compensableService()")
	public Object interceptCompensableMethod(ProceedingJoinPoint pjp) throws Throwable {
		MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
		Method method = methodSignature.getMethod();
		DistributedTransaction dt = method.getAnnotation(DistributedTransaction.class);
		DistributedTransactionContext dc = DistributedTransactionContext.getDistributedTransactionContext();
		if (logger.isDebugEnabled()) {
			logger.debug("transaction start method:{} action:{}", method.getName(), dt.action());
		}
		if (dt.sponsor()) {
			if (dc != null) {
				throw new IllegalStateException(
						"This transaction have the sponsor # globalTxId:\t" + dc.getGlobalTxId());
			}
			String globalTxId = UUID.randomUUID().toString();
			dc = new DistributedTransactionContext(globalTxId);
			dc.init();
			DistributedTransactionContext.setDistributedTransactionContext(dc);
			String action = dt.action();
			dc.setAction(action);
			dc.setTransactionTimeoutSeconds(dt.transactionTimeoutSeconds());
			Object obj = null;
			try {
				// begin失败快速失败: 业务尚未执行无需cancel收尾;
				// 若因同id全局事务已存在而失败, 更不得对其误发cancel取消他人的事务
				transactionRepository.beginGlobalTransaction(globalTxId);
			} catch (Throwable e) {
				DistributedTransactionContext.removeDistributedTransactionContext();
				throw e;
			}
			try {
				if (logger.isDebugEnabled()) {
					logger.debug("transaction proceed sponsor:{} action:{}", dc.getGlobalTxId(), action);
				}
				obj = pjp.proceed();
			} catch (Throwable e) {
				if (!dc.isIntervene()) {
					try {
						if (logger.isDebugEnabled()) {
							logger.debug("transaction proceed exception cancel sponsor:{} action:{} ",
									dc.getGlobalTxId(), action);
						}
						cancel(action, globalTxId);
					} catch (Throwable cancelEx) {
						logger.error("distributed_transaction_cancel sponsor:{} action:{}", dc.getGlobalTxId(),
								action, cancelEx);
					}
				}
				if (logger.isDebugEnabled()) {
					logger.debug("transaction proceed exception sponsor:{} action:{} ", dc.getGlobalTxId(), action);
				}
				throw e;
			} finally {
				DistributedTransactionContext.removeDistributedTransactionContext();
			}
			if (!dc.isIntervene()) {
				if (dc.isCancel()) {
					try {
						cancel(action, globalTxId);
					} catch (Throwable e) {
						// 决策/通知失败不影响向调用方传达取消结果, 全局仍在trying时由定时器兜底强制取消
						logger.error("distributed_transaction_cancel sponsor:{} action:{}", dc.getGlobalTxId(),
								action, e);
					}
					throw new DistributedTransactionCanceledException(globalTxId);
				} else {
					if (logger.isDebugEnabled()) {
						logger.debug("transaction proceed confirm sponsor:{} action:{} ", dc.getGlobalTxId(), action);
					}
					try {
						confirm(action, globalTxId);
					} catch (DistributedTransactionCanceledException e) {
						throw e;
					} catch (Throwable e) {
						logger.error("distributed_transaction_confirm sponsor:{} action:{}", dc.getGlobalTxId(),
								action, e);
						throw e;
					}
				}
			}
			return obj;
		} else {
			if (dc != null) {
				if (!dc.isCancel()) {
					String globalTxId = dc.getGlobalTxId();
					DistributedTransactionContext branchContext = new DistributedTransactionContext(globalTxId);
					branchContext.init();
					branchContext.setAction(dt.action());
					branchContext.setStatus(TransactionStatus.TRYING);
					int transactionTimeoutSeconds = transactionRepository.resolveTransactionTimeoutSeconds(dc,
							dt.transactionTimeoutSeconds()); 
					branchContext.setDeadline(dc.getAddtime() + transactionTimeoutSeconds);
					Object[] args = pjp.getArgs();
					Parameter[] parameters = method.getParameters();
					Map<String, Object> datas = new HashMap<>(16);
					String[] parameterNames = ParameterNames.resolve(method);
					for (int i = 0; i < parameters.length; i++) {
						datas.put(parameterNames != null ? parameterNames[i] : parameters[i].getName(), args[i]);
					}
					branchContext.setDatas(datas);
					Object obj = null;
					Throwable error = null;
					boolean success = true;
					String fenceToken = null;
					try {
						if (logger.isDebugEnabled()) {
							logger.debug("transaction proceed globalTxid:{} branchTxId:{} action:{} create to redis",
									branchContext.getGlobalTxId(), branchContext.getBranchTxId(),
									branchContext.getAction());
						}
						transactionRepository.create(branchContext);
						// try持有分支补偿栅栏后才执行业务, 与补偿者互斥:
						// 注册后决策才被落定(如定时器强制取消)、补偿正在执行时,
						// 迟到的try不得再写业务数据(防悬挂); 获取不到栅栏按取消快速失败
						fenceToken = transactionRepository.acquireCompensationFence(globalTxId,
								branchContext.getBranchTxId());
						if (fenceToken == null) {
							throw new DistributedTransactionCanceledException(globalTxId);
						}
						warnFenceTtlShorterThanTransactionTimeout(transactionTimeoutSeconds, globalTxId,
								branchContext.getBranchTxId());
						RpcContext.getContext().setAttachment(
								DistributedTransactionContext.DISTRIBUTED_TRANSACTION_CONTEXT_KEY, branchContext);
						TransactionInterceptInvoker invoker = TransactionInterceptInvokerHolder
								.getTransactionInterceptInvoker();
						if (invoker != null) {
							obj = invoker.invoke(pjp, dc);
						} else {
							obj = pjp.proceed();
						}
					} catch (Throwable e) {
						error = e;
						success = false;
					} finally {
						releaseTryFenceQuietly(globalTxId, branchContext.getBranchTxId(), fenceToken);
					}
					if (!success) {
						if (logger.isDebugEnabled()) {
							logger.debug("transaction proceed failed globalTxid:{} branchTxId:{} action:{}",
									branchContext.getGlobalTxId(), branchContext.getBranchTxId(),
									branchContext.getAction());
						}
						dc.setCancel(true);
						// RPC等待超时只代表发起端放弃等待, 服务端try可能迟到提交(悬挂窗口):
						// 落定cancel前best-effort标记try结果未知, 补偿端空回滚成功后凭标记推迟删除到deadline复核
						markTryOutcomeUnknownQuietly(globalTxId, branchContext.getBranchTxId(), error);
						if (!dc.isIntervene()) {
							// 分支失败立即落定cancel决策并通知补偿: 发起方进程若在收尾前崩溃,
							// 全局已定格cancel, 在途/迟到的try注册被关闭拒绝, 已注册分支立即回滚,
							// 不必等定时器按deadline兜底; 同向幂等, 与发起方收尾互不冲突
							decideCancelQuietly(branchContext.getAction(), globalTxId);
						}
						if (error != null) {
							throw error;
						}
					}
					return obj;
				}
				logger.warn("this transaction was cancel,globalTxid:{}.", dc.getGlobalTxId());
				throw new DistributedTransactionCanceledException(dc.getGlobalTxId());
			} else {
				logger.warn(
						"distributed_transaction_without_sponsor_context type:{} method:{}, running without transaction protection.",
						method.getDeclaringClass().getName(), method.getName());
				return pjp.proceed();
			}
		}

	}

	public void confirm(String action, String globalTxId) throws Exception {
		confirmOrCancel(action, globalTxId, TransactionStatus.CONFIRM);
	}

	public void cancel(String action, String globalTxId) throws Exception {
		confirmOrCancel(action, globalTxId, TransactionStatus.CANCEL);
	}

	private void confirmOrCancel(String action, String globalTxId, String status) throws Exception {
		String decision = transactionRepository.decideGlobalTransaction(globalTxId, status);
		if (!status.equals(decision)) {
			if (TransactionStatus.CANCEL.equals(decision)) {
				throw new DistributedTransactionCanceledException(globalTxId);
			}
			throw new IllegalStateException("Global transaction already confirmed: " + globalTxId);
		}
		Map<String, Object> data = new HashMap<>(8);
		data.put("status", status);
		data.put("action", action);
		data.put("globalTxId", globalTxId);
		try {
			sendMessageQuietly(JsonProcessUtil.beanToJson(data), status, globalTxId);
		} catch (Exception e) {
			logger.error("serialize decided transaction notification failed. globalTxId:{}", globalTxId, e);
		}
	}

	/**
	 * 分支失败时立即落定cancel决策并投递补偿消息(同向重入幂等).
	 * 发起方进程在收尾前崩溃时全局已定格cancel, 在途/迟到的try注册被关闭拒绝,
	 * 已注册分支立即回滚, 不必等定时器按deadline兜底强制取消.
	 * 决策或消息失败仅告警不掩盖原始业务异常, 仍由发起方收尾与定时器兜底.
	 */
	private void decideCancelQuietly(String action, String globalTxId) {
		try {
			String decision = transactionRepository.decideGlobalTransaction(globalTxId, TransactionStatus.CANCEL);
			if (!TransactionStatus.CANCEL.equals(decision)) {
				logger.error("branch failure can not rollback, global transaction already confirmed. globalTxId:{} action:{}",
						globalTxId, action);
				return;
			}
			Map<String, Object> data = new HashMap<>(8);
			data.put("status", TransactionStatus.CANCEL);
			data.put("action", action);
			data.put("globalTxId", globalTxId);
			sendMessageQuietly(JsonProcessUtil.beanToJson(data), TransactionStatus.CANCEL, globalTxId);
		} catch (Throwable e) {
			logger.error(
					"branch failure decide cancel failed, sponsor cleanup or compensation timer will redeliver. globalTxId:{} action:{}",
					globalTxId, action, e);
		}
	}

	private void sendMessageQuietly(String msg, String status, String globalTxId) {
		try {
			messageSender.send(msg);
		} catch (Throwable e) {
			logger.error("distributed_transaction_{}_message_send_failed, timer will redeliver. globalTxId:{}",
					status, globalTxId, e);
		}
	}

	/**
	 * 释放try执行前持有的分支补偿栅栏(令牌匹配才释放, 未持有直接跳过).
	 * 发起方进程若在try执行中崩溃, 栅栏随TTL自然过期放行补偿, 不会悬挂互斥.
	 */
	private void releaseTryFenceQuietly(String globalTxId, String branchTxId, String fenceToken) {
		if (fenceToken == null) {
			return;
		}
		try {
			transactionRepository.releaseCompensationFence(globalTxId, branchTxId, fenceToken);
		} catch (Throwable e) {
			logger.warn(
					"release try fence failed, it will expire by ttl. globalTxId:{} branchTxId:{}",
					globalTxId, branchTxId, e);
		}
	}

	/**
	 * 分支失败且异常为RPC等待超时(InvokeFuture超时的既定信号)时best-effort标记try结果未知.
	 * 标记失败仅告警不阻断取消收尾: 无标记时补偿端回到旧行为(空回滚成功即删除),
	 * 迟到提交窗口留存但日志可查; RpcRemoteException(服务端已执行并抛出)与
	 * 连接类失败(未送达)按已知不提交处理, 不标记.
	 */
	private void markTryOutcomeUnknownQuietly(String globalTxId, String branchTxId, Throwable error) {
		if (error == null || !isRpcWaitTimeout(error)) {
			return;
		}
		try {
			boolean marked = transactionRepository.markTryOutcomeUnknown(globalTxId, branchTxId);
			if (!marked) {
				logger.warn(
						"mark try outcome unknown skipped, branch or global record gone. globalTxId:{} branchTxId:{}",
						globalTxId, branchTxId);
			}
		} catch (Throwable e) {
			logger.warn(
					"mark try outcome unknown failed, empty-rollback delete guard degrades, check late try commits manually. globalTxId:{} branchTxId:{}",
					globalTxId, branchTxId, e);
		}
	}

	/**
	 * 沿cause链识别RPC等待超时: InvokeFuture.getResult(timeout)超时统一包装为
	 * java.util.concurrent.TimeoutException后抛出, 任意层的包装异常均视为超时信号
	 */
	private static boolean isRpcWaitTimeout(Throwable error) {
		Throwable current = error;
		while (current != null) {
			if (current instanceof java.util.concurrent.TimeoutException) {
				return true;
			}
			current = current.getCause();
		}
		return false;
	}

	/**
	 * 事务超时越过栅栏TTL时告警: try尚在执行而栅栏先行过期, 补偿者会并发进入执行cancel
	 */
	private void warnFenceTtlShorterThanTransactionTimeout(int transactionTimeoutSeconds, String globalTxId,
			String branchTxId) {
		int fenceTtlSeconds = transactionRepository.getCompensationFenceTtlSeconds();
		if (fenceTtlSeconds > 0 && transactionTimeoutSeconds > fenceTtlSeconds) {
			logger.warn(
					"transactionTimeoutSeconds({}s) exceeds compensation fence ttl({}s), fence would expire before the slowest allowed try finishes, compensator may run cancel concurrently with a still-running try. globalTxId:{} branchTxId:{}",
					transactionTimeoutSeconds, fenceTtlSeconds, globalTxId, branchTxId);
		}
	}

}
