From 76162f8b66b5aa77f736c0c845997650c7f6af13 Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Thu, 19 Feb 2026 14:14:13 +0530 Subject: [PATCH 01/13] feat(health,version): add health and version endpoints --- pom.xml | 35 +++- .../controller/health/HealthController.java | 83 ++++++++ .../controller/version/VersionController.java | 79 +++++++ .../mmu/service/health/HealthService.java | 194 ++++++++++++++++++ .../mmu/utils/JwtUserIdValidationFilter.java | 4 +- .../iemr/mmu/utils/mapper/SecurityConfig.java | 2 +- 6 files changed, 388 insertions(+), 9 deletions(-) create mode 100644 src/main/java/com/iemr/mmu/controller/health/HealthController.java create mode 100644 src/main/java/com/iemr/mmu/controller/version/VersionController.java create mode 100644 src/main/java/com/iemr/mmu/service/health/HealthService.java diff --git a/pom.xml b/pom.xml index a15dfc50..e4ae13ff 100644 --- a/pom.xml +++ b/pom.xml @@ -255,11 +255,7 @@ org.springframework.session spring-session-data-redis - - - org.springframework.boot - spring-boot-starter-actuator - + org.jacoco jacoco-maven-plugin @@ -292,7 +288,7 @@ - ${artifactId}-${version} + ${project.artifactId}-${project.version} org.apache.maven.plugins @@ -429,7 +425,6 @@ checkstyle.xml - UTF-8 true true false @@ -444,6 +439,32 @@ + + io.github.git-commit-id + git-commit-id-maven-plugin + 7.0.0 + + + get-the-git-infos + + revision + + initialize + + + + true + ${project.build.outputDirectory}/git.properties + + ^git.branch$ + ^git.commit.id.abbrev$ + ^git.build.version$ + ^git.build.time$ + + false + false + + org.springframework.boot spring-boot-maven-plugin diff --git a/src/main/java/com/iemr/mmu/controller/health/HealthController.java b/src/main/java/com/iemr/mmu/controller/health/HealthController.java new file mode 100644 index 00000000..0c44dcb5 --- /dev/null +++ b/src/main/java/com/iemr/mmu/controller/health/HealthController.java @@ -0,0 +1,83 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +package com.iemr.mmu.controller.health; + +import java.time.Instant; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.iemr.mmu.service.health.HealthService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + +@RestController +@RequestMapping("/health") +@Tag(name = "Health Check", description = "APIs for checking infrastructure health status") +public class HealthController { + + private static final Logger logger = LoggerFactory.getLogger(HealthController.class); + + private final HealthService healthService; + + public HealthController(HealthService healthService) { + this.healthService = healthService; + } + + @GetMapping + @Operation(summary = "Check infrastructure health", + description = "Returns the health status of MySQL, Redis, and other configured services") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "All checked components are UP"), + @ApiResponse(responseCode = "503", description = "One or more critical services are DOWN") + }) + public ResponseEntity> checkHealth() { + logger.info("Health check endpoint called"); + + try { + Map healthStatus = healthService.checkHealth(); + String overallStatus = (String) healthStatus.get("status"); + + HttpStatus httpStatus = "UP".equals(overallStatus) ? HttpStatus.OK : HttpStatus.SERVICE_UNAVAILABLE; + + logger.debug("Health check completed with status: {}", overallStatus); + return new ResponseEntity<>(healthStatus, httpStatus); + + } catch (Exception e) { + logger.error("Unexpected error during health check", e); + + Map errorResponse = Map.of( + "status", "DOWN", + "timestamp", Instant.now().toString() + ); + + return new ResponseEntity<>(errorResponse, HttpStatus.SERVICE_UNAVAILABLE); + } + } +} diff --git a/src/main/java/com/iemr/mmu/controller/version/VersionController.java b/src/main/java/com/iemr/mmu/controller/version/VersionController.java new file mode 100644 index 00000000..1c9fc7ec --- /dev/null +++ b/src/main/java/com/iemr/mmu/controller/version/VersionController.java @@ -0,0 +1,79 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ +package com.iemr.mmu.controller.version; + +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Operation; + +@RestController +public class VersionController { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); + + private static final String UNKNOWN_VALUE = "unknown"; + + @Operation(summary = "Get version information") + @GetMapping(value = "/version", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> versionInformation() { + Map response = new LinkedHashMap<>(); + try { + logger.info("version Controller Start"); + Properties gitProperties = loadGitProperties(); + response.put("buildTimestamp", gitProperties.getProperty("git.build.time", UNKNOWN_VALUE)); + response.put("version", gitProperties.getProperty("git.build.version", UNKNOWN_VALUE)); + response.put("branch", gitProperties.getProperty("git.branch", UNKNOWN_VALUE)); + response.put("commitHash", gitProperties.getProperty("git.commit.id.abbrev", UNKNOWN_VALUE)); + } catch (Exception e) { + logger.error("Failed to load version information", e); + response.put("buildTimestamp", UNKNOWN_VALUE); + response.put("version", UNKNOWN_VALUE); + response.put("branch", UNKNOWN_VALUE); + response.put("commitHash", UNKNOWN_VALUE); + } + logger.info("version Controller End"); + return ResponseEntity.ok(response); + } + + private Properties loadGitProperties() throws IOException { + Properties properties = new Properties(); + try (InputStream input = getClass().getClassLoader() + .getResourceAsStream("git.properties")) { + if (input != null) { + properties.load(input); + } + } + return properties; + } +} diff --git a/src/main/java/com/iemr/mmu/service/health/HealthService.java b/src/main/java/com/iemr/mmu/service/health/HealthService.java new file mode 100644 index 00000000..44ce6831 --- /dev/null +++ b/src/main/java/com/iemr/mmu/service/health/HealthService.java @@ -0,0 +1,194 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +package com.iemr.mmu.service.health; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Supplier; +import javax.sql.DataSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; + +@Service +public class HealthService { + + private static final Logger logger = LoggerFactory.getLogger(HealthService.class); + + private static final String STATUS_KEY = "status"; + private static final String STATUS_UP = "UP"; + private static final String STATUS_DOWN = "DOWN"; + + private static final long MYSQL_TIMEOUT_SECONDS = 3; + private static final long REDIS_TIMEOUT_SECONDS = 3; + + private final DataSource dataSource; + private final RedisTemplate redisTemplate; + private final ExecutorService executorService; + + public HealthService(DataSource dataSource, + @Autowired(required = false) RedisTemplate redisTemplate) { + this.dataSource = dataSource; + this.redisTemplate = redisTemplate; + this.executorService = Executors.newFixedThreadPool(2); + } + + public Map checkHealth() { + Map response = new LinkedHashMap<>(); + response.put("timestamp", Instant.now().toString()); + + Map> components = new LinkedHashMap<>(); + + // Check MySQL + Map mysqlStatus = new LinkedHashMap<>(); + performHealthCheck("MySQL", mysqlStatus, this::checkMySQLHealth); + components.put("mysql", mysqlStatus); + + // Check Redis if available + if (redisTemplate != null) { + Map redisStatus = new LinkedHashMap<>(); + performHealthCheck("Redis", redisStatus, this::checkRedisHealth); + components.put("redis", redisStatus); + } + + response.put("components", components); + + // Overall status: UP only if all components are UP + boolean allUp = components.values().stream() + .allMatch(this::isHealthy); + response.put(STATUS_KEY, allUp ? STATUS_UP : STATUS_DOWN); + + return response; + } + + private HealthCheckResult checkMySQLHealth() { + try (Connection connection = dataSource.getConnection(); + PreparedStatement stmt = connection.prepareStatement("SELECT 1 as health_check")) { + + stmt.setQueryTimeout((int) MYSQL_TIMEOUT_SECONDS); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + return new HealthCheckResult(true, null); + } + } + + return new HealthCheckResult(false, "No result from health check query"); + + } catch (Exception e) { + logger.warn("MySQL health check failed: {}", e.getMessage()); + return new HealthCheckResult(false, e.getMessage()); + } + } + + private HealthCheckResult checkRedisHealth() { + if (redisTemplate == null) { + return new HealthCheckResult(true, null); + } + + try { + CompletableFuture future = CompletableFuture.supplyAsync(() -> { + try { + return redisTemplate.execute((org.springframework.data.redis.core.RedisCallback) (connection) -> connection.ping()); + } catch (Exception e) { + return null; + } + }, executorService); + + String pong = future.get(REDIS_TIMEOUT_SECONDS, TimeUnit.SECONDS); + + if ("PONG".equals(pong)) { + return new HealthCheckResult(true, null); + } + + return new HealthCheckResult(false, "Redis PING failed"); + + } catch (TimeoutException e) { + logger.warn("Redis health check timed out"); + return new HealthCheckResult(false, "Redis health check timed out"); + } catch (Exception e) { + logger.warn("Redis health check failed: {}", e.getMessage()); + return new HealthCheckResult(false, e.getMessage()); + } + } + + private Map performHealthCheck(String componentName, + Map status, + Supplier checker) { + long startTime = System.currentTimeMillis(); + + try { + HealthCheckResult result = checker.get(); + long responseTime = System.currentTimeMillis() - startTime; + + status.put("responseTimeMs", responseTime); + + if (result.isHealthy) { + logger.debug("{} health check: UP ({}ms)", componentName, responseTime); + status.put(STATUS_KEY, STATUS_UP); + } else { + String safeError = result.error != null ? result.error : "Health check failed"; + logger.warn("{} health check failed: {}", componentName, safeError); + status.put(STATUS_KEY, STATUS_DOWN); + status.put("error", safeError); + } + + return status; + + } catch (Exception e) { + long responseTime = System.currentTimeMillis() - startTime; + logger.error("{} health check failed with exception: {}", componentName, e.getMessage(), e); + + status.put(STATUS_KEY, STATUS_DOWN); + status.put("responseTimeMs", responseTime); + status.put("error", "Health check failed with an unexpected error"); + + return status; + } + } + + private boolean isHealthy(Map componentStatus) { + return STATUS_UP.equals(componentStatus.get(STATUS_KEY)); + } + + private static class HealthCheckResult { + final boolean isHealthy; + final String error; + + HealthCheckResult(boolean isHealthy, String error) { + this.isHealthy = isHealthy; + this.error = error; + } + } +} diff --git a/src/main/java/com/iemr/mmu/utils/JwtUserIdValidationFilter.java b/src/main/java/com/iemr/mmu/utils/JwtUserIdValidationFilter.java index 4be94681..f5068825 100644 --- a/src/main/java/com/iemr/mmu/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/iemr/mmu/utils/JwtUserIdValidationFilter.java @@ -108,7 +108,9 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo || path.startsWith(contextPath + "/swagger-ui") || path.startsWith(contextPath + "/v3/api-docs") || path.startsWith(contextPath + "/user/refreshToken") - || path.startsWith(contextPath + "/public")) { + || path.startsWith(contextPath + "/public") + || path.equals(contextPath + "/version") + || path.equals(contextPath + "/health")) { logger.info("Skipping filter for path: " + path); filterChain.doFilter(servletRequest, servletResponse); return; diff --git a/src/main/java/com/iemr/mmu/utils/mapper/SecurityConfig.java b/src/main/java/com/iemr/mmu/utils/mapper/SecurityConfig.java index 3fe096d2..382ebcb8 100644 --- a/src/main/java/com/iemr/mmu/utils/mapper/SecurityConfig.java +++ b/src/main/java/com/iemr/mmu/utils/mapper/SecurityConfig.java @@ -39,7 +39,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti .csrf(csrf -> csrf.disable()) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(auth -> auth - .requestMatchers("/user/**").permitAll() + .requestMatchers("/user/**", "/health", "/version").permitAll() .anyRequest().authenticated() ) .exceptionHandling(ex -> ex From 34b49a77fa12c0d1e17e1caccf5b796f9d386f56 Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Thu, 19 Feb 2026 14:19:18 +0530 Subject: [PATCH 02/13] fix(health): restore interrupt flag when InterruptedException occurs --- src/main/java/com/iemr/mmu/service/health/HealthService.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/com/iemr/mmu/service/health/HealthService.java b/src/main/java/com/iemr/mmu/service/health/HealthService.java index 44ce6831..a0a7ed37 100644 --- a/src/main/java/com/iemr/mmu/service/health/HealthService.java +++ b/src/main/java/com/iemr/mmu/service/health/HealthService.java @@ -137,6 +137,10 @@ private HealthCheckResult checkRedisHealth() { } catch (TimeoutException e) { logger.warn("Redis health check timed out"); return new HealthCheckResult(false, "Redis health check timed out"); + } catch (InterruptedException e) { + logger.warn("Redis health check was interrupted"); + Thread.currentThread().interrupt(); + return new HealthCheckResult(false, "Redis health check was interrupted"); } catch (Exception e) { logger.warn("Redis health check failed: {}", e.getMessage()); return new HealthCheckResult(false, e.getMessage()); From deccb26c7bf4099553cad9a9cbbefb32903837f8 Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Thu, 19 Feb 2026 14:24:10 +0530 Subject: [PATCH 03/13] fix(health): shutdown executor on destroy and sanitize infra errors in /health --- .../com/iemr/mmu/service/health/HealthService.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/mmu/service/health/HealthService.java b/src/main/java/com/iemr/mmu/service/health/HealthService.java index a0a7ed37..7b4d6627 100644 --- a/src/main/java/com/iemr/mmu/service/health/HealthService.java +++ b/src/main/java/com/iemr/mmu/service/health/HealthService.java @@ -34,6 +34,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Supplier; +import jakarta.annotation.PreDestroy; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -64,6 +65,11 @@ public HealthService(DataSource dataSource, this.executorService = Executors.newFixedThreadPool(2); } + @PreDestroy + public void shutdown() { + executorService.shutdown(); + } + public Map checkHealth() { Map response = new LinkedHashMap<>(); response.put("timestamp", Instant.now().toString()); @@ -108,7 +114,7 @@ private HealthCheckResult checkMySQLHealth() { } catch (Exception e) { logger.warn("MySQL health check failed: {}", e.getMessage()); - return new HealthCheckResult(false, e.getMessage()); + return new HealthCheckResult(false, "MySQL connection failed"); } } @@ -143,7 +149,7 @@ private HealthCheckResult checkRedisHealth() { return new HealthCheckResult(false, "Redis health check was interrupted"); } catch (Exception e) { logger.warn("Redis health check failed: {}", e.getMessage()); - return new HealthCheckResult(false, e.getMessage()); + return new HealthCheckResult(false, "Redis connection failed"); } } From dd89ecca2753bd2ce8150d44f1919566e80343f3 Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Thu, 19 Feb 2026 14:30:11 +0530 Subject: [PATCH 04/13] fix(health): MySQL health check with timeout and sanitize errors --- .../mmu/service/health/HealthService.java | 44 ++++++++++++++----- 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/iemr/mmu/service/health/HealthService.java b/src/main/java/com/iemr/mmu/service/health/HealthService.java index 7b4d6627..1d4937fd 100644 --- a/src/main/java/com/iemr/mmu/service/health/HealthService.java +++ b/src/main/java/com/iemr/mmu/service/health/HealthService.java @@ -99,19 +99,35 @@ public Map checkHealth() { } private HealthCheckResult checkMySQLHealth() { - try (Connection connection = dataSource.getConnection(); - PreparedStatement stmt = connection.prepareStatement("SELECT 1 as health_check")) { - - stmt.setQueryTimeout((int) MYSQL_TIMEOUT_SECONDS); - - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - return new HealthCheckResult(true, null); + CompletableFuture future = CompletableFuture.supplyAsync(() -> { + try (Connection connection = dataSource.getConnection(); + PreparedStatement stmt = connection.prepareStatement("SELECT 1 as health_check")) { + + stmt.setQueryTimeout((int) MYSQL_TIMEOUT_SECONDS); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + return new HealthCheckResult(true, null); + } } + + return new HealthCheckResult(false, "No result from health check query"); + + } catch (Exception e) { + logger.warn("MySQL health check failed: {}", e.getMessage()); + return new HealthCheckResult(false, "MySQL connection failed"); } - - return new HealthCheckResult(false, "No result from health check query"); - + }, executorService); + + try { + return future.get(MYSQL_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (TimeoutException e) { + future.cancel(true); + logger.warn("MySQL health check timed out"); + return new HealthCheckResult(false, "MySQL health check timed out"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return new HealthCheckResult(false, "MySQL health check was interrupted"); } catch (Exception e) { logger.warn("MySQL health check failed: {}", e.getMessage()); return new HealthCheckResult(false, "MySQL connection failed"); @@ -123,8 +139,9 @@ private HealthCheckResult checkRedisHealth() { return new HealthCheckResult(true, null); } + CompletableFuture future = null; try { - CompletableFuture future = CompletableFuture.supplyAsync(() -> { + future = CompletableFuture.supplyAsync(() -> { try { return redisTemplate.execute((org.springframework.data.redis.core.RedisCallback) (connection) -> connection.ping()); } catch (Exception e) { @@ -141,6 +158,9 @@ private HealthCheckResult checkRedisHealth() { return new HealthCheckResult(false, "Redis PING failed"); } catch (TimeoutException e) { + if (future != null) { + future.cancel(true); + } logger.warn("Redis health check timed out"); return new HealthCheckResult(false, "Redis health check timed out"); } catch (InterruptedException e) { From c681a3fa6607295fc55e5db0ff636da2a48f3156 Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Fri, 20 Feb 2026 22:44:12 +0530 Subject: [PATCH 05/13] fix(health): harden advanced MySQL checks and throttle execution --- .../controller/health/HealthController.java | 5 +- .../mmu/service/health/HealthService.java | 486 ++++++++++++++---- 2 files changed, 402 insertions(+), 89 deletions(-) diff --git a/src/main/java/com/iemr/mmu/controller/health/HealthController.java b/src/main/java/com/iemr/mmu/controller/health/HealthController.java index 0c44dcb5..34b21ef3 100644 --- a/src/main/java/com/iemr/mmu/controller/health/HealthController.java +++ b/src/main/java/com/iemr/mmu/controller/health/HealthController.java @@ -54,7 +54,7 @@ public HealthController(HealthService healthService) { @Operation(summary = "Check infrastructure health", description = "Returns the health status of MySQL, Redis, and other configured services") @ApiResponses({ - @ApiResponse(responseCode = "200", description = "All checked components are UP"), + @ApiResponse(responseCode = "200", description = "Services are UP or DEGRADED (operational with warnings)"), @ApiResponse(responseCode = "503", description = "One or more critical services are DOWN") }) public ResponseEntity> checkHealth() { @@ -64,7 +64,8 @@ public ResponseEntity> checkHealth() { Map healthStatus = healthService.checkHealth(); String overallStatus = (String) healthStatus.get("status"); - HttpStatus httpStatus = "UP".equals(overallStatus) ? HttpStatus.OK : HttpStatus.SERVICE_UNAVAILABLE; + // Return 503 only if DOWN; 200 for both UP and DEGRADED (DEGRADED = operational with warnings) + HttpStatus httpStatus = "DOWN".equals(overallStatus) ? HttpStatus.SERVICE_UNAVAILABLE : HttpStatus.OK; logger.debug("Health check completed with status: {}", overallStatus); return new ResponseEntity<>(healthStatus, httpStatus); diff --git a/src/main/java/com/iemr/mmu/service/health/HealthService.java b/src/main/java/com/iemr/mmu/service/health/HealthService.java index 1d4937fd..1f766fea 100644 --- a/src/main/java/com/iemr/mmu/service/health/HealthService.java +++ b/src/main/java/com/iemr/mmu/service/health/HealthService.java @@ -36,9 +36,16 @@ import java.util.function.Supplier; import jakarta.annotation.PreDestroy; import javax.sql.DataSource; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; +import java.lang.management.ManagementFactory; +import javax.management.MBeanServer; +import javax.management.ObjectName; +import java.util.concurrent.locks.ReentrantReadWriteLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @@ -47,16 +54,46 @@ public class HealthService { private static final Logger logger = LoggerFactory.getLogger(HealthService.class); + // Status constants private static final String STATUS_KEY = "status"; private static final String STATUS_UP = "UP"; private static final String STATUS_DOWN = "DOWN"; - + private static final String STATUS_DEGRADED = "DEGRADED"; + private static final String SEVERITY_KEY = "severity"; + private static final String SEVERITY_OK = "OK"; + private static final String SEVERITY_WARNING = "WARNING"; + private static final String SEVERITY_CRITICAL = "CRITICAL"; + private static final String ERROR_KEY = "error"; + private static final String MESSAGE_KEY = "message"; + private static final String RESPONSE_TIME_KEY = "responseTimeMs"; private static final long MYSQL_TIMEOUT_SECONDS = 3; private static final long REDIS_TIMEOUT_SECONDS = 3; + + // Advanced checks configuration + private static final long ADVANCED_CHECKS_THROTTLE_SECONDS = 30; // Run at most once per 30 seconds + private static final long RESPONSE_TIME_THRESHOLD_MS = 2000; + + // Diagnostic event codes for concise logging + private static final String DIAGNOSTIC_LOCK_WAIT = "MYSQL_LOCK_WAIT"; + private static final String DIAGNOSTIC_DEADLOCK = "MYSQL_DEADLOCK"; + private static final String DIAGNOSTIC_SLOW_QUERIES = "MYSQL_SLOW_QUERIES"; + private static final String DIAGNOSTIC_POOL_EXHAUSTED = "MYSQL_POOL_EXHAUSTED"; + private static final String DIAGNOSTIC_LOG_TEMPLATE = "Diagnostic: {}"; private final DataSource dataSource; private final RedisTemplate redisTemplate; private final ExecutorService executorService; + + // Advanced checks throttling (thread-safe) + private volatile long lastAdvancedCheckTime = 0; + private volatile AdvancedCheckResult cachedAdvancedCheckResult = null; + private final ReentrantReadWriteLock advancedCheckLock = new ReentrantReadWriteLock(); + + // Deadlock check resilience - disable after first permission error + private volatile boolean deadlockCheckDisabled = false; + + // Advanced health checks enabled flag (defaulting to true) + private static final boolean ADVANCED_HEALTH_CHECKS_ENABLED = true; public HealthService(DataSource dataSource, @Autowired(required = false) RedisTemplate redisTemplate) { @@ -67,109 +104,116 @@ public HealthService(DataSource dataSource, @PreDestroy public void shutdown() { - executorService.shutdown(); + if (executorService != null && !executorService.isShutdown()) { + try { + executorService.shutdown(); + if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + logger.warn("ExecutorService did not terminate gracefully"); + } + } catch (InterruptedException e) { + executorService.shutdownNow(); + Thread.currentThread().interrupt(); + logger.warn("ExecutorService shutdown interrupted", e); + } + } } public Map checkHealth() { Map response = new LinkedHashMap<>(); response.put("timestamp", Instant.now().toString()); - Map> components = new LinkedHashMap<>(); - - // Check MySQL Map mysqlStatus = new LinkedHashMap<>(); - performHealthCheck("MySQL", mysqlStatus, this::checkMySQLHealth); - components.put("mysql", mysqlStatus); + Map redisStatus = new LinkedHashMap<>(); + + // Submit both checks concurrently + CompletableFuture mysqlFuture = CompletableFuture.runAsync( + () -> performHealthCheck("MySQL", mysqlStatus, this::checkMySQLHealthSync), executorService); + CompletableFuture redisFuture = CompletableFuture.runAsync( + () -> performHealthCheck("Redis", redisStatus, this::checkRedisHealthSync), executorService); - // Check Redis if available - if (redisTemplate != null) { - Map redisStatus = new LinkedHashMap<>(); - performHealthCheck("Redis", redisStatus, this::checkRedisHealth); - components.put("redis", redisStatus); + // Wait for both checks to complete with combined timeout + long maxTimeout = Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; + try { + CompletableFuture.allOf(mysqlFuture, redisFuture) + .get(maxTimeout, TimeUnit.SECONDS); + } catch (TimeoutException e) { + logger.warn("Health check aggregate timeout after {} seconds", maxTimeout); + mysqlFuture.cancel(true); + redisFuture.cancel(true); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + logger.warn("Health check was interrupted"); + mysqlFuture.cancel(true); + redisFuture.cancel(true); + } catch (Exception e) { + logger.warn("Health check execution error: {}", e.getMessage()); } + // Ensure timed-out or unfinished components are marked DOWN + ensurePopulated(mysqlStatus, "MySQL"); + ensurePopulated(redisStatus, "Redis"); + + Map> components = new LinkedHashMap<>(); + components.put("mysql", mysqlStatus); + components.put("redis", redisStatus); + response.put("components", components); - // Overall status: UP only if all components are UP - boolean allUp = components.values().stream() - .allMatch(this::isHealthy); - response.put(STATUS_KEY, allUp ? STATUS_UP : STATUS_DOWN); + // Compute overall status + String overallStatus = computeOverallStatus(components); + response.put(STATUS_KEY, overallStatus); return response; } - private HealthCheckResult checkMySQLHealth() { - CompletableFuture future = CompletableFuture.supplyAsync(() -> { - try (Connection connection = dataSource.getConnection(); - PreparedStatement stmt = connection.prepareStatement("SELECT 1 as health_check")) { - - stmt.setQueryTimeout((int) MYSQL_TIMEOUT_SECONDS); - - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - return new HealthCheckResult(true, null); - } + private void ensurePopulated(Map status, String componentName) { + if (!status.containsKey(STATUS_KEY)) { + status.put(STATUS_KEY, STATUS_DOWN); + status.put(SEVERITY_KEY, SEVERITY_CRITICAL); + status.put(ERROR_KEY, componentName + " health check did not complete in time"); + } + } + + private HealthCheckResult checkMySQLHealthSync() { + try (Connection connection = dataSource.getConnection(); + PreparedStatement stmt = connection.prepareStatement("SELECT 1 as health_check")) { + + stmt.setQueryTimeout((int) MYSQL_TIMEOUT_SECONDS); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + // Basic health check passed, now run advanced checks with throttling + boolean isDegraded = performAdvancedMySQLChecksWithThrottle(connection); + return new HealthCheckResult(true, null, isDegraded); } - - return new HealthCheckResult(false, "No result from health check query"); - - } catch (Exception e) { - logger.warn("MySQL health check failed: {}", e.getMessage()); - return new HealthCheckResult(false, "MySQL connection failed"); } - }, executorService); - - try { - return future.get(MYSQL_TIMEOUT_SECONDS, TimeUnit.SECONDS); - } catch (TimeoutException e) { - future.cancel(true); - logger.warn("MySQL health check timed out"); - return new HealthCheckResult(false, "MySQL health check timed out"); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return new HealthCheckResult(false, "MySQL health check was interrupted"); + + return new HealthCheckResult(false, "No result from health check query", false); + } catch (Exception e) { - logger.warn("MySQL health check failed: {}", e.getMessage()); - return new HealthCheckResult(false, "MySQL connection failed"); + logger.warn("MySQL health check failed: {}", e.getMessage(), e); + return new HealthCheckResult(false, "MySQL connection failed", false); } } - private HealthCheckResult checkRedisHealth() { + private HealthCheckResult checkRedisHealthSync() { if (redisTemplate == null) { - return new HealthCheckResult(true, null); + return new HealthCheckResult(true, "Redis not configured — skipped", false); } - CompletableFuture future = null; try { - future = CompletableFuture.supplyAsync(() -> { - try { - return redisTemplate.execute((org.springframework.data.redis.core.RedisCallback) (connection) -> connection.ping()); - } catch (Exception e) { - return null; - } - }, executorService); - - String pong = future.get(REDIS_TIMEOUT_SECONDS, TimeUnit.SECONDS); + String pong = redisTemplate.execute((org.springframework.data.redis.core.RedisCallback) (connection) -> connection.ping()); if ("PONG".equals(pong)) { - return new HealthCheckResult(true, null); + return new HealthCheckResult(true, null, false); } - return new HealthCheckResult(false, "Redis PING failed"); + return new HealthCheckResult(false, "Redis PING failed", false); - } catch (TimeoutException e) { - if (future != null) { - future.cancel(true); - } - logger.warn("Redis health check timed out"); - return new HealthCheckResult(false, "Redis health check timed out"); - } catch (InterruptedException e) { - logger.warn("Redis health check was interrupted"); - Thread.currentThread().interrupt(); - return new HealthCheckResult(false, "Redis health check was interrupted"); } catch (Exception e) { - logger.warn("Redis health check failed: {}", e.getMessage()); - return new HealthCheckResult(false, "Redis connection failed"); + logger.warn("Redis health check failed: {}", e.getMessage(), e); + return new HealthCheckResult(false, "Redis connection failed", false); } } @@ -182,16 +226,30 @@ private Map performHealthCheck(String componentName, HealthCheckResult result = checker.get(); long responseTime = System.currentTimeMillis() - startTime; - status.put("responseTimeMs", responseTime); - - if (result.isHealthy) { - logger.debug("{} health check: UP ({}ms)", componentName, responseTime); - status.put(STATUS_KEY, STATUS_UP); + // Determine status: DOWN (unhealthy), DEGRADED (healthy but with issues), or UP + String componentStatus; + if (!result.isHealthy) { + componentStatus = STATUS_DOWN; + } else if (result.isDegraded) { + componentStatus = STATUS_DEGRADED; } else { - String safeError = result.error != null ? result.error : "Health check failed"; - logger.warn("{} health check failed: {}", componentName, safeError); - status.put(STATUS_KEY, STATUS_DOWN); - status.put("error", safeError); + componentStatus = STATUS_UP; + } + status.put(STATUS_KEY, componentStatus); + + // Set response time + status.put(RESPONSE_TIME_KEY, responseTime); + + // Determine severity based on health, response time, and degradation flags + String severity = determineSeverity(result.isHealthy, responseTime, result.isDegraded); + status.put(SEVERITY_KEY, severity); + + // Include message or error based on health status + if (result.error != null) { + // Use MESSAGE_KEY for informational messages when healthy + // Use ERROR_KEY for actual error messages when unhealthy + String fieldKey = result.isHealthy ? MESSAGE_KEY : ERROR_KEY; + status.put(fieldKey, result.error); } return status; @@ -201,24 +259,278 @@ private Map performHealthCheck(String componentName, logger.error("{} health check failed with exception: {}", componentName, e.getMessage(), e); status.put(STATUS_KEY, STATUS_DOWN); - status.put("responseTimeMs", responseTime); - status.put("error", "Health check failed with an unexpected error"); + status.put(RESPONSE_TIME_KEY, responseTime); + status.put(SEVERITY_KEY, SEVERITY_CRITICAL); + status.put(ERROR_KEY, "Health check failed with an unexpected error"); return status; } } - private boolean isHealthy(Map componentStatus) { - return STATUS_UP.equals(componentStatus.get(STATUS_KEY)); + private String determineSeverity(boolean isHealthy, long responseTimeMs, boolean isDegraded) { + if (!isHealthy) { + return SEVERITY_CRITICAL; + } + + if (isDegraded) { + return SEVERITY_WARNING; + } + + if (responseTimeMs > RESPONSE_TIME_THRESHOLD_MS) { + return SEVERITY_WARNING; + } + + return SEVERITY_OK; + } + + private String computeOverallStatus(Map> components) { + boolean hasCritical = false; + boolean hasDegraded = false; + + for (Map componentStatus : components.values()) { + String status = (String) componentStatus.get(STATUS_KEY); + String severity = (String) componentStatus.get(SEVERITY_KEY); + + if (STATUS_DOWN.equals(status) || SEVERITY_CRITICAL.equals(severity)) { + hasCritical = true; + } + + if (STATUS_DEGRADED.equals(status)) { + hasDegraded = true; + } + + if (SEVERITY_WARNING.equals(severity)) { + hasDegraded = true; + } + } + + if (hasCritical) { + return STATUS_DOWN; + } + + if (hasDegraded) { + return STATUS_DEGRADED; + } + + return STATUS_UP; + } + + // Internal advanced health checks for MySQL - do not expose details in responses + private boolean performAdvancedMySQLChecksWithThrottle(Connection connection) { + if (!ADVANCED_HEALTH_CHECKS_ENABLED) { + return false; // Advanced checks disabled + } + + long currentTime = System.currentTimeMillis(); + + // Check throttle window - use read lock first for fast path + advancedCheckLock.readLock().lock(); + try { + if (cachedAdvancedCheckResult != null && + (currentTime - lastAdvancedCheckTime) < ADVANCED_CHECKS_THROTTLE_SECONDS * 1000) { + // Return cached result - within throttle window + return cachedAdvancedCheckResult.isDegraded; + } + } finally { + advancedCheckLock.readLock().unlock(); + } + + // Outside throttle window - acquire write lock and run checks + advancedCheckLock.writeLock().lock(); + try { + // Double-check after acquiring write lock + if (cachedAdvancedCheckResult != null && + (currentTime - lastAdvancedCheckTime) < ADVANCED_CHECKS_THROTTLE_SECONDS * 1000) { + return cachedAdvancedCheckResult.isDegraded; + } + + AdvancedCheckResult result = performAdvancedMySQLChecks(connection); + + // Cache the result + lastAdvancedCheckTime = currentTime; + cachedAdvancedCheckResult = result; + + return result.isDegraded; + } finally { + advancedCheckLock.writeLock().unlock(); + } + } + + private AdvancedCheckResult performAdvancedMySQLChecks(Connection connection) { + try { + boolean hasIssues = false; + + if (hasLockWaits(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_LOCK_WAIT); + hasIssues = true; + } + + if (hasDeadlocks(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_DEADLOCK); + hasIssues = true; + } + + if (hasSlowQueries(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_SLOW_QUERIES); + hasIssues = true; + } + + if (hasConnectionPoolExhaustion()) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_POOL_EXHAUSTED); + hasIssues = true; + } + + return new AdvancedCheckResult(hasIssues); + } catch (Exception e) { + logger.debug("Advanced MySQL checks encountered exception, marking degraded"); + return new AdvancedCheckResult(true); + } + } + + private boolean hasLockWaits(Connection connection) { + try (PreparedStatement stmt = connection.prepareStatement( + "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PROCESSLIST " + + "WHERE (state = 'Waiting for table metadata lock' " + + " OR state = 'Waiting for row lock' " + + " OR state = 'Waiting for lock') " + + "AND user NOT IN ('event_scheduler', 'system user', 'root')")) { + stmt.setQueryTimeout(2); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int lockCount = rs.getInt(1); + return lockCount > 0; + } + } + } catch (Exception e) { + logger.debug("Could not check for lock waits"); + } + return false; + } + + private boolean hasDeadlocks(Connection connection) { + // Skip deadlock check if already disabled due to permissions + if (deadlockCheckDisabled) { + return false; + } + + try (PreparedStatement stmt = connection.prepareStatement("SHOW ENGINE INNODB STATUS")) { + stmt.setQueryTimeout(2); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + String innodbStatus = rs.getString(3); + return innodbStatus != null && innodbStatus.contains("LATEST DETECTED DEADLOCK"); + } + } + } catch (java.sql.SQLException e) { + // Check if this is a permission error + if (e.getMessage() != null && + (e.getMessage().contains("Access denied") || + e.getMessage().contains("permission"))) { + // Disable this check permanently after first permission error + deadlockCheckDisabled = true; + logger.warn("Deadlock check disabled: Insufficient privileges"); + } else { + logger.debug("Could not check for deadlocks"); + } + } catch (Exception e) { + logger.debug("Could not check for deadlocks"); + } + return false; + } + + private boolean hasSlowQueries(Connection connection) { + try (PreparedStatement stmt = connection.prepareStatement( + "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PROCESSLIST " + + "WHERE command != 'Sleep' AND time > ? AND user NOT IN ('event_scheduler', 'system user')")) { + stmt.setQueryTimeout(2); + stmt.setInt(1, 10); // Queries running longer than 10 seconds + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int slowQueryCount = rs.getInt(1); + return slowQueryCount > 3; // Alert if more than 3 slow queries + } + } + } catch (Exception e) { + logger.debug("Could not check for slow queries"); + } + return false; + } + + private boolean hasConnectionPoolExhaustion() { + // Use HikariCP metrics if available + if (dataSource instanceof HikariDataSource hikariDataSource) { + try { + HikariPoolMXBean poolMXBean = hikariDataSource.getHikariPoolMXBean(); + + if (poolMXBean != null) { + int activeConnections = poolMXBean.getActiveConnections(); + int maxPoolSize = hikariDataSource.getMaximumPoolSize(); + + // Alert if > 80% of pool is exhausted + int threshold = (int) (maxPoolSize * 0.8); + return activeConnections > threshold; + } + } catch (Exception e) { + logger.debug("Could not retrieve HikariCP pool metrics"); + } + } + + // Fallback: try to get pool metrics via JMX if HikariCP is not directly available + return checkPoolMetricsViaJMX(); + } + + private boolean checkPoolMetricsViaJMX() { + try { + MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); + ObjectName objectName = new ObjectName("com.zaxxer.hikari:type=Pool (*)"); + var mBeans = mBeanServer.queryMBeans(objectName, null); + + for (var mBean : mBeans) { + if (evaluatePoolMetrics(mBeanServer, mBean.getObjectName())) { + return true; + } + } + } catch (Exception e) { + logger.debug("Could not access HikariCP pool metrics via JMX"); + } + + // No pool metrics available - disable this check + logger.debug("Pool exhaustion check disabled: HikariCP metrics unavailable"); + return false; + } + + private boolean evaluatePoolMetrics(MBeanServer mBeanServer, ObjectName objectName) { + try { + Integer activeConnections = (Integer) mBeanServer.getAttribute(objectName, "ActiveConnections"); + Integer maximumPoolSize = (Integer) mBeanServer.getAttribute(objectName, "MaximumPoolSize"); + + if (activeConnections != null && maximumPoolSize != null) { + int threshold = (int) (maximumPoolSize * 0.8); + return activeConnections > threshold; + } + } catch (Exception e) { + // Continue to next MBean + } + return false; + } + + private static class AdvancedCheckResult { + final boolean isDegraded; + + AdvancedCheckResult(boolean isDegraded) { + this.isDegraded = isDegraded; + } } private static class HealthCheckResult { final boolean isHealthy; final String error; + final boolean isDegraded; - HealthCheckResult(boolean isHealthy, String error) { + HealthCheckResult(boolean isHealthy, String error, boolean isDegraded) { this.isHealthy = isHealthy; this.error = error; + this.isDegraded = isDegraded; } } -} +} \ No newline at end of file From 796252dd36b1fdac8b1481d82a2d8d8bc48f4ebd Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Fri, 20 Feb 2026 22:47:01 +0530 Subject: [PATCH 06/13] fix(health): remove unused imports --- src/main/java/com/iemr/mmu/service/health/HealthService.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/iemr/mmu/service/health/HealthService.java b/src/main/java/com/iemr/mmu/service/health/HealthService.java index 1f766fea..6e8b918d 100644 --- a/src/main/java/com/iemr/mmu/service/health/HealthService.java +++ b/src/main/java/com/iemr/mmu/service/health/HealthService.java @@ -45,7 +45,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; From a51d91b69ab56d3d2755e67710aaa6725edb4bca Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Sat, 21 Feb 2026 09:14:34 +0530 Subject: [PATCH 07/13] fix(health): fux deadlock detection issue --- .../controller/health/HealthController.java | 2 +- .../mmu/service/health/HealthService.java | 33 ++++++++++--------- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/iemr/mmu/controller/health/HealthController.java b/src/main/java/com/iemr/mmu/controller/health/HealthController.java index 34b21ef3..3e43269c 100644 --- a/src/main/java/com/iemr/mmu/controller/health/HealthController.java +++ b/src/main/java/com/iemr/mmu/controller/health/HealthController.java @@ -58,7 +58,7 @@ public HealthController(HealthService healthService) { @ApiResponse(responseCode = "503", description = "One or more critical services are DOWN") }) public ResponseEntity> checkHealth() { - logger.info("Health check endpoint called"); + logger.debug("Health check endpoint called"); try { Map healthStatus = healthService.checkHealth(); diff --git a/src/main/java/com/iemr/mmu/service/health/HealthService.java b/src/main/java/com/iemr/mmu/service/health/HealthService.java index 6e8b918d..1c9b1c82 100644 --- a/src/main/java/com/iemr/mmu/service/health/HealthService.java +++ b/src/main/java/com/iemr/mmu/service/health/HealthService.java @@ -28,9 +28,10 @@ import java.time.Instant; import java.util.LinkedHashMap; import java.util.Map; -import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Supplier; @@ -122,23 +123,25 @@ public Map checkHealth() { Map response = new LinkedHashMap<>(); response.put("timestamp", Instant.now().toString()); - Map mysqlStatus = new LinkedHashMap<>(); - Map redisStatus = new LinkedHashMap<>(); + // Use ConcurrentHashMap to avoid data races during timeout + Map mysqlStatus = new ConcurrentHashMap<>(); + Map redisStatus = new ConcurrentHashMap<>(); - // Submit both checks concurrently - CompletableFuture mysqlFuture = CompletableFuture.runAsync( - () -> performHealthCheck("MySQL", mysqlStatus, this::checkMySQLHealthSync), executorService); - CompletableFuture redisFuture = CompletableFuture.runAsync( - () -> performHealthCheck("Redis", redisStatus, this::checkRedisHealthSync), executorService); + // Submit both checks concurrently using executorService for proper cancellation support + Future mysqlFuture = executorService.submit( + () -> performHealthCheck("MySQL", mysqlStatus, this::checkMySQLHealthSync)); + Future redisFuture = executorService.submit( + () -> performHealthCheck("Redis", redisStatus, this::checkRedisHealthSync)); // Wait for both checks to complete with combined timeout long maxTimeout = Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; try { - CompletableFuture.allOf(mysqlFuture, redisFuture) - .get(maxTimeout, TimeUnit.SECONDS); + // Get both futures with timeout - cancel(true) will interrupt the threads + mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); + redisFuture.get(maxTimeout, TimeUnit.SECONDS); } catch (TimeoutException e) { logger.warn("Health check aggregate timeout after {} seconds", maxTimeout); - mysqlFuture.cancel(true); + mysqlFuture.cancel(true); // NOW actually interrupts the thread redisFuture.cancel(true); } catch (InterruptedException e) { Thread.currentThread().interrupt(); @@ -421,11 +424,9 @@ private boolean hasDeadlocks(Connection connection) { } } } catch (java.sql.SQLException e) { - // Check if this is a permission error - if (e.getMessage() != null && - (e.getMessage().contains("Access denied") || - e.getMessage().contains("permission"))) { - // Disable this check permanently after first permission error + // Check if this is a permission error using SQL error codes + // 1142 = SELECT command denied; 1227 = SUPER privilege required + if (e.getErrorCode() == 1142 || e.getErrorCode() == 1227) { deadlockCheckDisabled = true; logger.warn("Deadlock check disabled: Insufficient privileges"); } else { From 0661a5d3b6ebfc96712cb3f1e4b96af7f1955f69 Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Sat, 21 Feb 2026 10:11:57 +0530 Subject: [PATCH 08/13] fix(health): fix deadline timeout issue --- .../com/iemr/mmu/service/health/HealthService.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/mmu/service/health/HealthService.java b/src/main/java/com/iemr/mmu/service/health/HealthService.java index 1c9b1c82..b98219f4 100644 --- a/src/main/java/com/iemr/mmu/service/health/HealthService.java +++ b/src/main/java/com/iemr/mmu/service/health/HealthService.java @@ -135,10 +135,19 @@ public Map checkHealth() { // Wait for both checks to complete with combined timeout long maxTimeout = Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; + long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(maxTimeout); + try { // Get both futures with timeout - cancel(true) will interrupt the threads mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); - redisFuture.get(maxTimeout, TimeUnit.SECONDS); + + // Calculate remaining time from shared deadline + long remainingNs = deadlineNs - System.nanoTime(); + if (remainingNs > 0) { + redisFuture.get(remainingNs, TimeUnit.NANOSECONDS); + } else { + redisFuture.cancel(true); + } } catch (TimeoutException e) { logger.warn("Health check aggregate timeout after {} seconds", maxTimeout); mysqlFuture.cancel(true); // NOW actually interrupts the thread From 3dacdd47a463927f6a7ccb5fb02056aec9ad05ab Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Sat, 21 Feb 2026 11:55:34 +0530 Subject: [PATCH 09/13] fix(health): scope PROCESSLIST lock-wait check to application DB user --- src/main/java/com/iemr/mmu/service/health/HealthService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/mmu/service/health/HealthService.java b/src/main/java/com/iemr/mmu/service/health/HealthService.java index b98219f4..6ea69086 100644 --- a/src/main/java/com/iemr/mmu/service/health/HealthService.java +++ b/src/main/java/com/iemr/mmu/service/health/HealthService.java @@ -404,7 +404,7 @@ private boolean hasLockWaits(Connection connection) { "WHERE (state = 'Waiting for table metadata lock' " + " OR state = 'Waiting for row lock' " + " OR state = 'Waiting for lock') " + - "AND user NOT IN ('event_scheduler', 'system user', 'root')")) { + "AND user = USER()")) { stmt.setQueryTimeout(2); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { From 7ed8c3d6cb3ba0f78f4fe64c7b97256c8f848f1b Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Sun, 22 Feb 2026 12:04:41 +0530 Subject: [PATCH 10/13] refactor(health): extract MySQL basic health query into helper method --- .../mmu/service/health/HealthService.java | 40 +------------------ 1 file changed, 1 insertion(+), 39 deletions(-) diff --git a/src/main/java/com/iemr/mmu/service/health/HealthService.java b/src/main/java/com/iemr/mmu/service/health/HealthService.java index 6ea69086..cc09fd45 100644 --- a/src/main/java/com/iemr/mmu/service/health/HealthService.java +++ b/src/main/java/com/iemr/mmu/service/health/HealthService.java @@ -75,7 +75,6 @@ public class HealthService { // Diagnostic event codes for concise logging private static final String DIAGNOSTIC_LOCK_WAIT = "MYSQL_LOCK_WAIT"; - private static final String DIAGNOSTIC_DEADLOCK = "MYSQL_DEADLOCK"; private static final String DIAGNOSTIC_SLOW_QUERIES = "MYSQL_SLOW_QUERIES"; private static final String DIAGNOSTIC_POOL_EXHAUSTED = "MYSQL_POOL_EXHAUSTED"; private static final String DIAGNOSTIC_LOG_TEMPLATE = "Diagnostic: {}"; @@ -89,9 +88,6 @@ public class HealthService { private volatile AdvancedCheckResult cachedAdvancedCheckResult = null; private final ReentrantReadWriteLock advancedCheckLock = new ReentrantReadWriteLock(); - // Deadlock check resilience - disable after first permission error - private volatile boolean deadlockCheckDisabled = false; - // Advanced health checks enabled flag (defaulting to true) private static final boolean ADVANCED_HEALTH_CHECKS_ENABLED = true; @@ -376,11 +372,6 @@ private AdvancedCheckResult performAdvancedMySQLChecks(Connection connection) { hasIssues = true; } - if (hasDeadlocks(connection)) { - logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_DEADLOCK); - hasIssues = true; - } - if (hasSlowQueries(connection)) { logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_SLOW_QUERIES); hasIssues = true; @@ -404,7 +395,7 @@ private boolean hasLockWaits(Connection connection) { "WHERE (state = 'Waiting for table metadata lock' " + " OR state = 'Waiting for row lock' " + " OR state = 'Waiting for lock') " + - "AND user = USER()")) { + "AND user = SUBSTRING_INDEX(USER(), '@', 1)")) { stmt.setQueryTimeout(2); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { @@ -418,35 +409,6 @@ private boolean hasLockWaits(Connection connection) { return false; } - private boolean hasDeadlocks(Connection connection) { - // Skip deadlock check if already disabled due to permissions - if (deadlockCheckDisabled) { - return false; - } - - try (PreparedStatement stmt = connection.prepareStatement("SHOW ENGINE INNODB STATUS")) { - stmt.setQueryTimeout(2); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - String innodbStatus = rs.getString(3); - return innodbStatus != null && innodbStatus.contains("LATEST DETECTED DEADLOCK"); - } - } - } catch (java.sql.SQLException e) { - // Check if this is a permission error using SQL error codes - // 1142 = SELECT command denied; 1227 = SUPER privilege required - if (e.getErrorCode() == 1142 || e.getErrorCode() == 1227) { - deadlockCheckDisabled = true; - logger.warn("Deadlock check disabled: Insufficient privileges"); - } else { - logger.debug("Could not check for deadlocks"); - } - } catch (Exception e) { - logger.debug("Could not check for deadlocks"); - } - return false; - } - private boolean hasSlowQueries(Connection connection) { try (PreparedStatement stmt = connection.prepareStatement( "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PROCESSLIST " + From 757a95444d4efde2b85d92703789de562449f7ef Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Sun, 22 Feb 2026 12:11:55 +0530 Subject: [PATCH 11/13] fix(health): avoid sharing JDBC connections across threads in advanced MySQL checks --- .../mmu/service/health/HealthService.java | 139 +++++++++++++----- 1 file changed, 99 insertions(+), 40 deletions(-) diff --git a/src/main/java/com/iemr/mmu/service/health/HealthService.java b/src/main/java/com/iemr/mmu/service/health/HealthService.java index cc09fd45..7acf515f 100644 --- a/src/main/java/com/iemr/mmu/service/health/HealthService.java +++ b/src/main/java/com/iemr/mmu/service/health/HealthService.java @@ -66,11 +66,18 @@ public class HealthService { private static final String ERROR_KEY = "error"; private static final String MESSAGE_KEY = "message"; private static final String RESPONSE_TIME_KEY = "responseTimeMs"; + + // Component names + private static final String MYSQL_COMPONENT = "MySQL"; + private static final String REDIS_COMPONENT = "Redis"; + + // Timeouts (in seconds) private static final long MYSQL_TIMEOUT_SECONDS = 3; private static final long REDIS_TIMEOUT_SECONDS = 3; // Advanced checks configuration - private static final long ADVANCED_CHECKS_THROTTLE_SECONDS = 30; // Run at most once per 30 seconds + private static final long ADVANCED_CHECKS_TIMEOUT_MS = 500L; // ms — enforced below + private static final long ADVANCED_CHECKS_THROTTLE_SECONDS = 30; private static final long RESPONSE_TIME_THRESHOLD_MS = 2000; // Diagnostic event codes for concise logging @@ -82,20 +89,26 @@ public class HealthService { private final DataSource dataSource; private final RedisTemplate redisTemplate; private final ExecutorService executorService; + private final ExecutorService advancedCheckExecutor; // Advanced checks throttling (thread-safe) private volatile long lastAdvancedCheckTime = 0; private volatile AdvancedCheckResult cachedAdvancedCheckResult = null; private final ReentrantReadWriteLock advancedCheckLock = new ReentrantReadWriteLock(); - // Advanced health checks enabled flag (defaulting to true) - private static final boolean ADVANCED_HEALTH_CHECKS_ENABLED = true; + @org.springframework.beans.factory.annotation.Value("${health.advanced.enabled:true}") + private boolean advancedHealthChecksEnabled; public HealthService(DataSource dataSource, @Autowired(required = false) RedisTemplate redisTemplate) { this.dataSource = dataSource; this.redisTemplate = redisTemplate; this.executorService = Executors.newFixedThreadPool(2); + this.advancedCheckExecutor = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "health-advanced-check"); + t.setDaemon(true); + return t; + }); } @PreDestroy @@ -113,53 +126,61 @@ public void shutdown() { logger.warn("ExecutorService shutdown interrupted", e); } } + if (advancedCheckExecutor != null && !advancedCheckExecutor.isShutdown()) { + advancedCheckExecutor.shutdownNow(); + } } public Map checkHealth() { Map response = new LinkedHashMap<>(); response.put("timestamp", Instant.now().toString()); - // Use ConcurrentHashMap to avoid data races during timeout Map mysqlStatus = new ConcurrentHashMap<>(); Map redisStatus = new ConcurrentHashMap<>(); - // Submit both checks concurrently using executorService for proper cancellation support - Future mysqlFuture = executorService.submit( - () -> performHealthCheck("MySQL", mysqlStatus, this::checkMySQLHealthSync)); - Future redisFuture = executorService.submit( - () -> performHealthCheck("Redis", redisStatus, this::checkRedisHealthSync)); - - // Wait for both checks to complete with combined timeout - long maxTimeout = Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; - long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(maxTimeout); - - try { - // Get both futures with timeout - cancel(true) will interrupt the threads - mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); + // Check if executor service is shutdown (during graceful shutdown) + if (executorService.isShutdown()) { + ensurePopulated(mysqlStatus, MYSQL_COMPONENT); + ensurePopulated(redisStatus, REDIS_COMPONENT); + // Fall through to build response with DOWN status + } else { + // Submit both checks concurrently using executorService for proper cancellation support + Future mysqlFuture = executorService.submit( + () -> performHealthCheck(MYSQL_COMPONENT, mysqlStatus, this::checkMySQLHealthSync)); + Future redisFuture = executorService.submit( + () -> performHealthCheck(REDIS_COMPONENT, redisStatus, this::checkRedisHealthSync)); - // Calculate remaining time from shared deadline - long remainingNs = deadlineNs - System.nanoTime(); - if (remainingNs > 0) { - redisFuture.get(remainingNs, TimeUnit.NANOSECONDS); - } else { + // Wait for both checks to complete with combined timeout (shared deadline) + long maxTimeout = Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; + long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(maxTimeout); + try { + mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); + long remainingNs = deadlineNs - System.nanoTime(); + if (remainingNs > 0) { + redisFuture.get(remainingNs, TimeUnit.NANOSECONDS); + } else { + redisFuture.cancel(true); + } + } catch (TimeoutException e) { + logger.warn("Health check aggregate timeout after {} seconds", maxTimeout); + mysqlFuture.cancel(true); + redisFuture.cancel(true); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + logger.warn("Health check was interrupted"); + mysqlFuture.cancel(true); + redisFuture.cancel(true); + // Mark components as DOWN before returning + } catch (Exception e) { + logger.warn("Health check execution error: {}", e.getMessage()); + mysqlFuture.cancel(true); redisFuture.cancel(true); } - } catch (TimeoutException e) { - logger.warn("Health check aggregate timeout after {} seconds", maxTimeout); - mysqlFuture.cancel(true); // NOW actually interrupts the thread - redisFuture.cancel(true); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - logger.warn("Health check was interrupted"); - mysqlFuture.cancel(true); - redisFuture.cancel(true); - } catch (Exception e) { - logger.warn("Health check execution error: {}", e.getMessage()); } // Ensure timed-out or unfinished components are marked DOWN - ensurePopulated(mysqlStatus, "MySQL"); - ensurePopulated(redisStatus, "Redis"); + ensurePopulated(mysqlStatus, MYSQL_COMPONENT); + ensurePopulated(redisStatus, REDIS_COMPONENT); Map> components = new LinkedHashMap<>(); components.put("mysql", mysqlStatus); @@ -191,7 +212,7 @@ private HealthCheckResult checkMySQLHealthSync() { try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { // Basic health check passed, now run advanced checks with throttling - boolean isDegraded = performAdvancedMySQLChecksWithThrottle(connection); + boolean isDegraded = performAdvancedMySQLChecksWithThrottle(); return new HealthCheckResult(true, null, isDegraded); } } @@ -323,8 +344,8 @@ private String computeOverallStatus(Map> components) } // Internal advanced health checks for MySQL - do not expose details in responses - private boolean performAdvancedMySQLChecksWithThrottle(Connection connection) { - if (!ADVANCED_HEALTH_CHECKS_ENABLED) { + private boolean performAdvancedMySQLChecksWithThrottle() { + if (!advancedHealthChecksEnabled) { return false; // Advanced checks disabled } @@ -351,7 +372,36 @@ private boolean performAdvancedMySQLChecksWithThrottle(Connection connection) { return cachedAdvancedCheckResult.isDegraded; } - AdvancedCheckResult result = performAdvancedMySQLChecks(connection); + AdvancedCheckResult result; + java.util.concurrent.CompletableFuture future = + java.util.concurrent.CompletableFuture + .supplyAsync(this::performAdvancedMySQLChecks, advancedCheckExecutor); + try { + result = future.get(ADVANCED_CHECKS_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (java.util.concurrent.TimeoutException ex) { + logger.debug("Advanced MySQL checks timed out after {}ms", ADVANCED_CHECKS_TIMEOUT_MS); + future.cancel(true); + result = new AdvancedCheckResult(true); // treat timeout as degraded + } catch (java.util.concurrent.ExecutionException ex) { + future.cancel(true); + // Check if the cause is an InterruptedException + if (ex.getCause() instanceof InterruptedException) { + Thread.currentThread().interrupt(); + logger.debug("Advanced MySQL checks were interrupted"); + } else { + logger.debug("Advanced MySQL checks failed: {}", ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage()); + } + result = new AdvancedCheckResult(true); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + logger.debug("Advanced MySQL checks interrupted"); + future.cancel(true); + result = new AdvancedCheckResult(true); + } catch (Exception ex) { + logger.debug("Advanced MySQL checks failed: {}", ex.getMessage()); + future.cancel(true); + result = new AdvancedCheckResult(true); + } // Cache the result lastAdvancedCheckTime = currentTime; @@ -363,7 +413,16 @@ private boolean performAdvancedMySQLChecksWithThrottle(Connection connection) { } } - private AdvancedCheckResult performAdvancedMySQLChecks(Connection connection) { + private AdvancedCheckResult performAdvancedMySQLChecks() { + try (Connection connection = dataSource.getConnection()) { + return performAdvancedCheckLogic(connection); + } catch (Exception e) { + logger.debug("Advanced MySQL checks could not obtain connection: {}", e.getMessage()); + return new AdvancedCheckResult(true); + } + } + + private AdvancedCheckResult performAdvancedCheckLogic(Connection connection) { try { boolean hasIssues = false; From a980c35d385cf5a85aca4a64ee60f22067c08ee1 Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Sun, 22 Feb 2026 21:04:41 +0530 Subject: [PATCH 12/13] fix(health): avoid blocking DB I/O under write lock and restore interrupt flag --- .../mmu/service/health/HealthService.java | 187 +++++++++--------- 1 file changed, 98 insertions(+), 89 deletions(-) diff --git a/src/main/java/com/iemr/mmu/service/health/HealthService.java b/src/main/java/com/iemr/mmu/service/health/HealthService.java index 7acf515f..688b714e 100644 --- a/src/main/java/com/iemr/mmu/service/health/HealthService.java +++ b/src/main/java/com/iemr/mmu/service/health/HealthService.java @@ -34,6 +34,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.concurrent.ExecutionException; import java.util.function.Supplier; import jakarta.annotation.PreDestroy; import javax.sql.DataSource; @@ -96,14 +97,14 @@ public class HealthService { private volatile AdvancedCheckResult cachedAdvancedCheckResult = null; private final ReentrantReadWriteLock advancedCheckLock = new ReentrantReadWriteLock(); - @org.springframework.beans.factory.annotation.Value("${health.advanced.enabled:true}") - private boolean advancedHealthChecksEnabled; + // Advanced checks always enabled + private static final boolean ADVANCED_HEALTH_CHECKS_ENABLED = true; public HealthService(DataSource dataSource, @Autowired(required = false) RedisTemplate redisTemplate) { this.dataSource = dataSource; this.redisTemplate = redisTemplate; - this.executorService = Executors.newFixedThreadPool(2); + this.executorService = Executors.newFixedThreadPool(6); this.advancedCheckExecutor = Executors.newSingleThreadExecutor(r -> { Thread t = new Thread(r, "health-advanced-check"); t.setDaemon(true); @@ -138,47 +139,10 @@ public Map checkHealth() { Map mysqlStatus = new ConcurrentHashMap<>(); Map redisStatus = new ConcurrentHashMap<>(); - // Check if executor service is shutdown (during graceful shutdown) - if (executorService.isShutdown()) { - ensurePopulated(mysqlStatus, MYSQL_COMPONENT); - ensurePopulated(redisStatus, REDIS_COMPONENT); - // Fall through to build response with DOWN status - } else { - // Submit both checks concurrently using executorService for proper cancellation support - Future mysqlFuture = executorService.submit( - () -> performHealthCheck(MYSQL_COMPONENT, mysqlStatus, this::checkMySQLHealthSync)); - Future redisFuture = executorService.submit( - () -> performHealthCheck(REDIS_COMPONENT, redisStatus, this::checkRedisHealthSync)); - - // Wait for both checks to complete with combined timeout (shared deadline) - long maxTimeout = Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; - long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(maxTimeout); - try { - mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); - long remainingNs = deadlineNs - System.nanoTime(); - if (remainingNs > 0) { - redisFuture.get(remainingNs, TimeUnit.NANOSECONDS); - } else { - redisFuture.cancel(true); - } - } catch (TimeoutException e) { - logger.warn("Health check aggregate timeout after {} seconds", maxTimeout); - mysqlFuture.cancel(true); - redisFuture.cancel(true); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - logger.warn("Health check was interrupted"); - mysqlFuture.cancel(true); - redisFuture.cancel(true); - // Mark components as DOWN before returning - } catch (Exception e) { - logger.warn("Health check execution error: {}", e.getMessage()); - mysqlFuture.cancel(true); - redisFuture.cancel(true); - } + if (!executorService.isShutdown()) { + performHealthChecks(mysqlStatus, redisStatus); } - // Ensure timed-out or unfinished components are marked DOWN ensurePopulated(mysqlStatus, MYSQL_COMPONENT); ensurePopulated(redisStatus, REDIS_COMPONENT); @@ -187,14 +151,56 @@ public Map checkHealth() { components.put("redis", redisStatus); response.put("components", components); - - // Compute overall status - String overallStatus = computeOverallStatus(components); - response.put(STATUS_KEY, overallStatus); + response.put(STATUS_KEY, computeOverallStatus(components)); return response; } + private void performHealthChecks(Map mysqlStatus, Map redisStatus) { + Future mysqlFuture = null; + Future redisFuture = null; + try { + mysqlFuture = executorService.submit( + () -> performHealthCheck(MYSQL_COMPONENT, mysqlStatus, this::checkMySQLHealthSync)); + redisFuture = executorService.submit( + () -> performHealthCheck(REDIS_COMPONENT, redisStatus, this::checkRedisHealthSync)); + + awaitHealthChecks(mysqlFuture, redisFuture); + } catch (TimeoutException e) { + logger.warn("Health check aggregate timeout after {} seconds", getMaxTimeout()); + cancelFutures(mysqlFuture, redisFuture); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + logger.warn("Health check was interrupted"); + cancelFutures(mysqlFuture, redisFuture); + } catch (Exception e) { + logger.warn("Health check execution error: {}", e.getMessage()); + } + } + + private void awaitHealthChecks(Future mysqlFuture, Future redisFuture) throws TimeoutException, InterruptedException, ExecutionException { + long maxTimeout = getMaxTimeout(); + long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(maxTimeout); + + mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); + long remainingNs = deadlineNs - System.nanoTime(); + + if (remainingNs > 0) { + redisFuture.get(remainingNs, TimeUnit.NANOSECONDS); + } else { + redisFuture.cancel(true); + } + } + + private long getMaxTimeout() { + return Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; + } + + private void cancelFutures(Future mysqlFuture, Future redisFuture) { + if (mysqlFuture != null) mysqlFuture.cancel(true); + if (redisFuture != null) redisFuture.cancel(true); + } + private void ensurePopulated(Map status, String componentName) { if (!status.containsKey(STATUS_KEY)) { status.put(STATUS_KEY, STATUS_DOWN); @@ -204,25 +210,24 @@ private void ensurePopulated(Map status, String componentName) { } private HealthCheckResult checkMySQLHealthSync() { + boolean basicPassed = false; try (Connection connection = dataSource.getConnection(); PreparedStatement stmt = connection.prepareStatement("SELECT 1 as health_check")) { stmt.setQueryTimeout((int) MYSQL_TIMEOUT_SECONDS); try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - // Basic health check passed, now run advanced checks with throttling - boolean isDegraded = performAdvancedMySQLChecksWithThrottle(); - return new HealthCheckResult(true, null, isDegraded); - } + basicPassed = rs.next(); } - - return new HealthCheckResult(false, "No result from health check query", false); - } catch (Exception e) { logger.warn("MySQL health check failed: {}", e.getMessage(), e); return new HealthCheckResult(false, "MySQL connection failed", false); } + if (!basicPassed) { + return new HealthCheckResult(false, "No result from health check query", false); + } + boolean isDegraded = performAdvancedMySQLChecksWithThrottle(); + return new HealthCheckResult(true, null, isDegraded); } private HealthCheckResult checkRedisHealthSync() { @@ -345,7 +350,7 @@ private String computeOverallStatus(Map> components) // Internal advanced health checks for MySQL - do not expose details in responses private boolean performAdvancedMySQLChecksWithThrottle() { - if (!advancedHealthChecksEnabled) { + if (!ADVANCED_HEALTH_CHECKS_ENABLED) { return false; // Advanced checks disabled } @@ -371,47 +376,51 @@ private boolean performAdvancedMySQLChecksWithThrottle() { (currentTime - lastAdvancedCheckTime) < ADVANCED_CHECKS_THROTTLE_SECONDS * 1000) { return cachedAdvancedCheckResult.isDegraded; } - - AdvancedCheckResult result; - java.util.concurrent.CompletableFuture future = - java.util.concurrent.CompletableFuture - .supplyAsync(this::performAdvancedMySQLChecks, advancedCheckExecutor); - try { - result = future.get(ADVANCED_CHECKS_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } catch (java.util.concurrent.TimeoutException ex) { - logger.debug("Advanced MySQL checks timed out after {}ms", ADVANCED_CHECKS_TIMEOUT_MS); - future.cancel(true); - result = new AdvancedCheckResult(true); // treat timeout as degraded - } catch (java.util.concurrent.ExecutionException ex) { - future.cancel(true); - // Check if the cause is an InterruptedException - if (ex.getCause() instanceof InterruptedException) { - Thread.currentThread().interrupt(); - logger.debug("Advanced MySQL checks were interrupted"); - } else { - logger.debug("Advanced MySQL checks failed: {}", ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage()); - } - result = new AdvancedCheckResult(true); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - logger.debug("Advanced MySQL checks interrupted"); - future.cancel(true); - result = new AdvancedCheckResult(true); - } catch (Exception ex) { - logger.debug("Advanced MySQL checks failed: {}", ex.getMessage()); - future.cancel(true); - result = new AdvancedCheckResult(true); - } - - // Cache the result + } finally { + advancedCheckLock.writeLock().unlock(); + } + + // Submit task without holding the write lock + Future future = advancedCheckExecutor.submit(this::performAdvancedMySQLChecks); + AdvancedCheckResult result = handleAdvancedChecksFuture(future); + + // Re-acquire write lock only to update the cache atomically + advancedCheckLock.writeLock().lock(); + try { lastAdvancedCheckTime = currentTime; cachedAdvancedCheckResult = result; - return result.isDegraded; } finally { advancedCheckLock.writeLock().unlock(); } } + + private AdvancedCheckResult handleAdvancedChecksFuture(Future future) { + try { + return future.get(ADVANCED_CHECKS_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (TimeoutException ex) { + logger.debug("Advanced MySQL checks timed out after {}ms", ADVANCED_CHECKS_TIMEOUT_MS); + future.cancel(true); + return new AdvancedCheckResult(true); // treat timeout as degraded + } catch (ExecutionException ex) { + future.cancel(true); + if (ex.getCause() instanceof InterruptedException) { + Thread.currentThread().interrupt(); + logger.debug("Advanced MySQL checks were interrupted"); + } else { + logger.debug("Advanced MySQL checks failed: {}", ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage()); + } + return new AdvancedCheckResult(true); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + logger.debug("Advanced MySQL checks interrupted"); + future.cancel(true); + return new AdvancedCheckResult(true); + } catch (Exception ex) { + logger.debug("Advanced MySQL checks failed: {}", ex.getMessage()); + future.cancel(true); + return new AdvancedCheckResult(true); + } private AdvancedCheckResult performAdvancedMySQLChecks() { try (Connection connection = dataSource.getConnection()) { From a8323806407b005db1c4b117963de7a03df6f0f2 Mon Sep 17 00:00:00 2001 From: DurgaPrasad-54 Date: Sun, 22 Feb 2026 21:22:38 +0530 Subject: [PATCH 13/13] fix: add missing close brace --- .../mmu/service/health/HealthService.java | 33 +++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/iemr/mmu/service/health/HealthService.java b/src/main/java/com/iemr/mmu/service/health/HealthService.java index 688b714e..c695b0d5 100644 --- a/src/main/java/com/iemr/mmu/service/health/HealthService.java +++ b/src/main/java/com/iemr/mmu/service/health/HealthService.java @@ -29,6 +29,7 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -96,6 +97,7 @@ public class HealthService { private volatile long lastAdvancedCheckTime = 0; private volatile AdvancedCheckResult cachedAdvancedCheckResult = null; private final ReentrantReadWriteLock advancedCheckLock = new ReentrantReadWriteLock(); + private final AtomicBoolean advancedCheckInProgress = new AtomicBoolean(false); // Advanced checks always enabled private static final boolean ADVANCED_HEALTH_CHECKS_ENABLED = true; @@ -380,18 +382,28 @@ private boolean performAdvancedMySQLChecksWithThrottle() { advancedCheckLock.writeLock().unlock(); } - // Submit task without holding the write lock - Future future = advancedCheckExecutor.submit(this::performAdvancedMySQLChecks); - AdvancedCheckResult result = handleAdvancedChecksFuture(future); - - // Re-acquire write lock only to update the cache atomically - advancedCheckLock.writeLock().lock(); + // Only one thread may submit; others fall back to the (stale) cache + if (!advancedCheckInProgress.compareAndSet(false, true)) { + advancedCheckLock.readLock().lock(); + try { + return cachedAdvancedCheckResult != null && cachedAdvancedCheckResult.isDegraded; + } finally { + advancedCheckLock.readLock().unlock(); + } + } try { - lastAdvancedCheckTime = currentTime; - cachedAdvancedCheckResult = result; - return result.isDegraded; + Future future = advancedCheckExecutor.submit(this::performAdvancedMySQLChecks); + AdvancedCheckResult result = handleAdvancedChecksFuture(future); + advancedCheckLock.writeLock().lock(); + try { + lastAdvancedCheckTime = System.currentTimeMillis(); + cachedAdvancedCheckResult = result; + return result.isDegraded; + } finally { + advancedCheckLock.writeLock().unlock(); + } } finally { - advancedCheckLock.writeLock().unlock(); + advancedCheckInProgress.set(false); } } @@ -420,6 +432,7 @@ private AdvancedCheckResult handleAdvancedChecksFuture(Future