package com.example.mtusi_messenger.service; import org.springframework.boot.availability.ApplicationAvailability; import org.springframework.boot.availability.AvailabilityChangeEvent; import org.springframework.boot.availability.ReadinessState; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.EventListener; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import java.util.concurrent.atomic.AtomicBoolean; @Service public class ReadinessService { private final JdbcTemplate jdbc; private final StringRedisTemplate redis; private final ApplicationAvailability availability; private final ApplicationEventPublisher events; private final AtomicBoolean dependencyUnavailable = new AtomicBoolean(false); private final AtomicBoolean shuttingDown = new AtomicBoolean(false); public ReadinessService( JdbcTemplate jdbc, StringRedisTemplate redis, ApplicationAvailability availability, ApplicationEventPublisher events ) { this.jdbc = jdbc; this.redis = redis; this.availability = availability; this.events = events; } public boolean probeDependencies() { try { // Redis is an optional cache. Ping only warms the lazy connection; // its failure must not make the authoritative API unavailable. redis.execute((RedisCallback) connection -> connection.ping()); } catch (DataAccessException ignored) { // PostgreSQL remains the source of truth. } try { // The schema-level probe also proves that the separate lab4 migration // completed before this replica is allowed to serve business traffic. jdbc.queryForObject("SELECT count(*) FROM attachments", Long.class); markDependenciesAvailable(); return true; } catch (DataAccessException e) { markDependenciesUnavailable(); return false; } } public boolean acceptsBusinessTraffic() { return !shuttingDown.get() && !dependencyUnavailable.get() && availability.getReadinessState() == ReadinessState.ACCEPTING_TRAFFIC; } @EventListener(ContextClosedEvent.class) void onContextClosed() { shuttingDown.set(true); } private void markDependenciesUnavailable() { dependencyUnavailable.set(true); AvailabilityChangeEvent.publish(events, this, ReadinessState.REFUSING_TRAFFIC); } private void markDependenciesAvailable() { boolean recovered = dependencyUnavailable.getAndSet(false); if (recovered && !shuttingDown.get()) { AvailabilityChangeEvent.publish(events, this, ReadinessState.ACCEPTING_TRAFFIC); } } }