59 lines
1.8 KiB
Java
59 lines
1.8 KiB
Java
package ru.mtusi.messenger.service;
|
|
|
|
import com.zaxxer.hikari.HikariDataSource;
|
|
import lombok.RequiredArgsConstructor;
|
|
import org.springframework.jdbc.core.JdbcTemplate;
|
|
import org.springframework.stereotype.Service;
|
|
import ru.mtusi.messenger.dto.HealthDTO;
|
|
import ru.mtusi.messenger.exception.ServiceUnavailableException;
|
|
|
|
import javax.sql.DataSource;
|
|
|
|
@Service
|
|
@RequiredArgsConstructor
|
|
public class HealthService {
|
|
|
|
private final JdbcTemplate jdbcTemplate;
|
|
private final DataSource dataSource;
|
|
private final io.minio.MinioClient minio;
|
|
private final ru.mtusi.messenger.config.properties.S3Properties s3;
|
|
|
|
public HealthDTO readiness() {
|
|
requirePoolAvailable();
|
|
requireDatabaseReachable();
|
|
try {
|
|
if (!minio.bucketExists(io.minio.BucketExistsArgs.builder().bucket(s3.bucket()).build()))
|
|
throw new ServiceUnavailableException("Storage unavailable");
|
|
} catch (Exception e) {
|
|
throw new ServiceUnavailableException("Storage unavailable");
|
|
}
|
|
return ok();
|
|
}
|
|
|
|
public HealthDTO liveness() {
|
|
return ok();
|
|
}
|
|
|
|
private void requirePoolAvailable() {
|
|
if (dataSource instanceof HikariDataSource hikari) {
|
|
var pool = hikari.getHikariPoolMXBean();
|
|
if (pool != null && pool.getActiveConnections() >= hikari.getMaximumPoolSize()) {
|
|
throw new ServiceUnavailableException("Database connection pool exhausted");
|
|
}
|
|
}
|
|
}
|
|
|
|
private void requireDatabaseReachable() {
|
|
try {
|
|
jdbcTemplate.queryForObject("SELECT 1", Integer.class);
|
|
} catch (Exception e) {
|
|
throw new ServiceUnavailableException("Database unavailable");
|
|
}
|
|
}
|
|
|
|
private HealthDTO ok() {
|
|
HealthDTO h = new HealthDTO();
|
|
h.setStatus(HealthDTO.StatusEnum.OK);
|
|
return h;
|
|
}
|
|
} |