261104_02_HOT: 트랜젝션 누수 관련 긴급 조치 #8

Merged
gitadmin merged 1 commits from develop into master 2026-11-04 17:19:28 +09:00
4 changed files with 104 additions and 2 deletions
Showing only changes of commit 47c598a61c - Show all commits

View File

@@ -7,6 +7,7 @@ import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
@@ -19,6 +20,13 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@EnableConfigurationProperties(KartDatabaseProperties.class)
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
public class KartMyBatisConfig {
private final long leakDetectionThreshold;
public KartMyBatisConfig(
@Value("${spring.datasource.hikari.leak-detection-threshold:0}") long leakDetectionThreshold) {
this.leakDetectionThreshold = leakDetectionThreshold;
}
@Bean(destroyMethod = "close")
public HikariDataSource konDataSource(KartDatabaseProperties properties, Validator validator) {
return dataSource("kon", properties.getKon(), validator);
@@ -53,6 +61,7 @@ public class KartMyBatisConfig {
dataSource.setMaximumPoolSize(source.getMaximumPoolSize());
dataSource.setMinimumIdle(0);
dataSource.setConnectionTimeout(10000);
dataSource.setLeakDetectionThreshold(leakDetectionThreshold);
dataSource.setInitializationFailTimeout(-1);
return dataSource;
}

View File

@@ -11,6 +11,7 @@ import com.kri.kart.server.dto.derived.DerivedSaveRequestDto;
import com.kri.kart.server.dto.project.ProjectRefDto;
import com.kri.kart.server.persistence.repository.DerivedRepository;
import com.kri.kart.server.service.derived.DerivedComputationService;
import com.kri.kart.server.service.derived.DerivedRecalculationGuard;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
@@ -28,6 +29,7 @@ public class DerivedManagementService {
private final DerivedComputationService derivedComputationService;
private final LogService logService;
private final ObjectMapper objectMapper;
private final DerivedRecalculationGuard derivedRecalculationGuard;
private final PlatformTransactionManager konTransactionManager;
private final PlatformTransactionManager konkiwiTransactionManager;
@@ -37,6 +39,7 @@ public class DerivedManagementService {
DerivedComputationService derivedComputationService,
LogService logService,
ObjectMapper objectMapper,
DerivedRecalculationGuard derivedRecalculationGuard,
@Qualifier("konTransactionManager") PlatformTransactionManager konTransactionManager,
@Qualifier("konkiwiTransactionManager")
PlatformTransactionManager konkiwiTransactionManager) {
@@ -45,6 +48,7 @@ public class DerivedManagementService {
this.derivedComputationService = derivedComputationService;
this.logService = logService;
this.objectMapper = objectMapper;
this.derivedRecalculationGuard = derivedRecalculationGuard;
this.konTransactionManager = konTransactionManager;
this.konkiwiTransactionManager = konkiwiTransactionManager;
}
@@ -152,7 +156,7 @@ public class DerivedManagementService {
if (idkey == null || idkey.isBlank() || idkey.length() > 512) {
throw BusinessException.badRequest("응답자 ID를 확인해 주세요.");
}
return transaction(
return derivedRecalculationGuard.execute(project, () -> transaction(
project,
() -> {
requireProject(project);
@@ -166,7 +170,7 @@ public class DerivedManagementService {
matched += calculate(project, definition, idkey, derivedIds);
}
return new DerivedCalculationDto(definitions.size(), matched);
});
}));
}
/** Stored derived variable IDs; uploaded response columns with these IDs are not imported. */

View File

@@ -0,0 +1,86 @@
package com.kri.kart.server.service.derived;
import com.kri.common.feature.web.BusinessException;
import com.kri.kart.server.common.enums.ProjectType;
import com.kri.kart.server.config.KartDatabaseProperties;
import com.kri.kart.server.dto.project.ProjectRefDto;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
/** Wait before borrowing JDBC connections; database locks still enforce cross-instance safety. */
@Component
@ConditionalOnProperty(prefix = "kri.kart.database", name = "enabled", havingValue = "true")
public class DerivedRecalculationGuard {
private final ConcurrentHashMap<ProjectRefDto, ProjectGate> projects = new ConcurrentHashMap<>();
private final Semaphore kon;
private final Semaphore konkiwi;
private final long waitNanos;
@Autowired
public DerivedRecalculationGuard(KartDatabaseProperties properties) {
this(properties, TimeUnit.SECONDS.toNanos(10));
}
DerivedRecalculationGuard(KartDatabaseProperties properties, long waitNanos) {
// Reserve one connection for access checks and other operations when pool size permits.
this.kon = new Semaphore(Math.max(1, properties.getKon().getMaximumPoolSize() - 1), true);
this.konkiwi = new Semaphore(Math.max(1, properties.getKonkiwi().getMaximumPoolSize() - 1), true);
this.waitNanos = waitNanos;
}
public <T> T execute(ProjectRefDto project, Supplier<T> action) {
long deadline = System.nanoTime() + waitNanos;
ProjectGate gate = projects.compute(project, (key, current) -> {
ProjectGate selected = current == null ? new ProjectGate() : current;
selected.users++;
return selected;
});
Semaphore source = project.projectType() == ProjectType.KON ? kon : konkiwi;
boolean projectAcquired = false;
boolean sourceAcquired = false;
try {
projectAcquired = gate.permit.tryAcquire(remaining(deadline), TimeUnit.NANOSECONDS);
if (!projectAcquired) {
throw busy();
}
sourceAcquired = source.tryAcquire(remaining(deadline), TimeUnit.NANOSECONDS);
if (!sourceAcquired) {
throw busy();
}
return action.get();
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
throw busy();
} finally {
if (sourceAcquired) {
source.release();
}
if (projectAcquired) {
gate.permit.release();
}
projects.computeIfPresent(project, (key, current) -> --current.users == 0 ? null : current);
}
}
private long remaining(long deadline) {
return Math.max(0, deadline - System.nanoTime());
}
private BusinessException busy() {
return BusinessException.of(
HttpStatus.SERVICE_UNAVAILABLE, "DERIVED_RECALCULATION_BUSY",
"파생변수 재계산 요청이 많습니다. 잠시 후 다시 요청해 주세요.");
}
private static final class ProjectGate {
private final Semaphore permit = new Semaphore(1, true);
// Accessed only inside ConcurrentHashMap.compute/computeIfPresent for the project.
private int users;
}
}

View File

@@ -3,6 +3,9 @@ server:
forward-headers-strategy: framework
spring:
datasource:
hikari:
leak-detection-threshold: 30000
application:
name: kart-server
profiles: