package vip.mate.goal.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import vip.mate.audit.service.AuditEventService; import vip.mate.exception.MateClawException; import vip.mate.goal.config.GoalProperties; import vip.mate.goal.model.GoalCreateRequest; import vip.mate.goal.model.GoalCriteriaCodec; import vip.mate.goal.model.GoalCriterion; import vip.mate.goal.model.GoalEntity; import vip.mate.goal.model.GoalResponse; import vip.mate.goal.model.GoalEvaluationResult; import vip.mate.goal.model.GoalEventEntity; import vip.mate.goal.model.GoalEventType; import vip.mate.goal.model.GoalStatus; import vip.mate.goal.model.GoalUpdateRequest; import vip.mate.goal.repository.GoalEventMapper; import vip.mate.goal.repository.GoalMapper; import java.time.Duration; import java.time.LocalDateTime; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * Default implementation. Concurrency safety relies on: *
This replaces the earlier single-shot wrapper capture which could
* not recover from the very first CAS miss — once {@code oldVersion}
* went stale, all subsequent retries with the same wrapper were
* doomed. Refetching per attempt is the correct shape for optimistic
* locking: read, build delta against the read, CAS on the read's
* version.
*/
private GoalEntity retryOptimistic(Long id, String op, UpdateBuilder builder) {
for (int i = 0; i < OPTIMISTIC_LOCK_MAX_RETRIES; i++) {
GoalEntity fresh = goalMapper.selectById(id);
if (fresh == null) {
throw new MateClawException("err.goal.not_found", 404,
"Goal not found: " + id);
}
LambdaUpdateWrapper