Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,17 @@ shadcn/ui bileşenleri ihtiyaç oldukça tek tek eklenir, toplu kurulmaz.
Spring Security adım 3'te geldi (bkz. Kimlik doğrulama); eklenirken
açık uçlar tek tek `permitAll` ile sayıldı, varsayılan "hepsi kilitli"
bırakılmadı.
- **`/api/health` veritabanını da yoklar.** `DatabaseProbe` `SELECT 1`
atar (sorgu zaman aşımı 2 sn): erişilebilirse 200 `{"status":"up"}`,
değilse 503 `{"status":"down","db":"down"}`. Hata ayrıntısı yanıtta değil
logda, stack trace'siz (compose 15 sn'de bir yokluyor). GET ve HEAD açık:
UptimeRobot HEAD atıyor. Hikari `connection-timeout` 2 sn: DB erişilemezken
health ve API istekleri 30 sn yerine ~2 sn'de hata verir. Deploy'daki
200 beklemesi böylece DB bağlantısını da doğrular; DB düşükken compose
backend'i `unhealthy` gösterir, ona bağlı servis olmadığı için zincirleme
etkisi yok. Testler: `HealthControllerTest` (gerçek port, çünkü MockMvc
HEAD'de gövdeyi atmıyor), `HealthDatabaseDownTest` (kendi konteynerini
durdurur).
- **`question.payload` ve `question_progress.attempts` JSONB kalır.**
`keyConcepts`, `anchors`, `followUps` gibi iç içe alanlara SQL sorgusu
atmayacağız; bu yüzden ilişkisel olarak parçalanmadılar. `category` ve
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ SecurityFilterChain apiFilterChain(HttpSecurity http, JsonAuthenticationEntryPoi
.authorizeHttpRequests(auth -> auth
// Uygulama hesapsız da çalışır: sağlık ve soru uçları herkese açık.
.requestMatchers(HttpMethod.GET, "/api/health", "/api/questions").permitAll()
// Uptime izleyicileri (UptimeRobot) sağlık ucunu HEAD ile yokluyor.
.requestMatchers(HttpMethod.HEAD, "/api/health").permitAll()
// Bu iki uç kimliğini cookie'den alır, Bearer token'ı yoktur.
.requestMatchers(HttpMethod.POST, "/api/auth/refresh", "/api/auth/logout").permitAll()
// Bir uç hata verdiğinde konteyner isteği /error'a ERROR
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.meteucar.mulakatslot.health;

import java.time.Duration;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
* Veritabanına SELECT 1 atarak erişilebilir olup olmadığını söyler.
*
* Sorgu zaman aşımı yalnızca bağlantı alındıktan sonrasını kapsar. DB hiç
* erişilemezken süre bağlantı beklerken geçer; onu Hikari'nin
* connection-timeout'u (application.yml, 2 sn) sınırlar.
*/
@Component
class DatabaseProbe {

static final Duration QUERY_TIMEOUT = Duration.ofSeconds(2);

private static final Logger log = LoggerFactory.getLogger(DatabaseProbe.class);

private final JdbcTemplate jdbcTemplate;

DatabaseProbe(DataSource dataSource) {
// Paylaşılan JdbcTemplate'in zaman aşımını değiştirmemek için kendi örneği.
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.jdbcTemplate.setQueryTimeout((int) QUERY_TIMEOUT.toSeconds());
}

boolean isUp() {
try {
jdbcTemplate.queryForObject("SELECT 1", Integer.class);
return true;
} catch (RuntimeException e) {
// Sağlık ucu sık yoklanıyor (compose 15 sn'de bir); DB düşükken
// her seferinde stack trace basmamak için yalnızca sınıf ve mesaj.
log.warn("Sağlık kontrolü: veritabanına erişilemedi ({}: {})",
e.getClass().getSimpleName(), e.getMessage());
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,31 @@
package com.meteucar.mulakatslot.health;

import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* Uygulama ayakta ve veritabanına erişiyorsa 200, erişemiyorsa 503.
* Hata ayrıntısı yanıtta değil logda (DatabaseProbe). HEAD istekleri de
* buraya gelir; Spring gövdeyi atar.
*/
@RestController
public class HealthController {

private final DatabaseProbe databaseProbe;

HealthController(DatabaseProbe databaseProbe) {
this.databaseProbe = databaseProbe;
}

@GetMapping("/api/health")
public Map<String, String> health() {
return Map.of("status", "up");
public ResponseEntity<Map<String, String>> health() {
if (databaseProbe.isUp()) {
return ResponseEntity.ok(Map.of("status", "up"));
}
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(Map.of("status", "down", "db", "down"));
}
}
4 changes: 4 additions & 0 deletions backend/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ spring:
url: ${DB_URL}
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
hikari:
# Varsayılan 30 sn. DB erişilemezken /api/health ve API istekleri
# 30 sn takılı kalmasın, ~2 sn'de hata versin.
connection-timeout: 2s

jpa:
# true olursa view render edilene kadar connection pool'u meşgul eder,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.meteucar.mulakatslot.health;

import static org.assertj.core.api.Assertions.assertThat;

import com.meteucar.mulakatslot.TestcontainersConfiguration;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Import;

/**
* Sağlık ucu token'sız GET ve HEAD ile çalışır; HEAD gövdesiz döner.
*
* Gerçek sunucuya istek atılır: HEAD'de gövdeyi Spring değil servlet
* konteyneri atıyor, MockMvc gövdeyi olduğu gibi döndürürdü.
*/
@Import(TestcontainersConfiguration.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class HealthControllerTest {

private final HttpClient client = HttpClient.newHttpClient();

@LocalServerPort
private int port;

@Test
void getReturnsUp() throws Exception {
HttpResponse<String> response = send("GET");

assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.body()).isEqualTo("{\"status\":\"up\"}");
}

@Test
void headReturnsOkWithoutBody() throws Exception {
HttpResponse<String> response = send("HEAD");

assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.body()).isEmpty();
}

private HttpResponse<String> send(String method) throws Exception {
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/api/health"))
.method(method, HttpRequest.BodyPublishers.noBody())
.build();
return client.send(request, HttpResponse.BodyHandlers.ofString());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.meteucar.mulakatslot.health;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.testcontainers.postgresql.PostgreSQLContainer;
import org.testcontainers.utility.DockerImageName;

/**
* Veritabanı erişilemezken sağlık ucu 503 döner ve hata ayrıntısı sızdırmaz.
*
* Paylaşılan TestcontainersConfiguration konteyneri durdurulamaz (diğer test
* sınıfları da kullanıyor); bu sınıf kendi konteynerini açar, test içinde
* durdurur ve context'i kapatır.
*/
@Import(HealthDatabaseDownTest.OwnPostgres.class)
@SpringBootTest
@AutoConfigureMockMvc
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class HealthDatabaseDownTest {

@TestConfiguration(proxyBeanMethods = false)
static class OwnPostgres {

@Bean
@ServiceConnection
PostgreSQLContainer healthDownPostgres() {
return new PostgreSQLContainer(DockerImageName.parse("postgres:latest"));
}
}

@Autowired
private MockMvc mockMvc;

@Autowired
private PostgreSQLContainer postgres;

@Test
void returnsServiceUnavailableWhenDatabaseIsDown() throws Exception {
mockMvc.perform(get("/api/health"))
.andExpect(status().isOk());

postgres.stop();

mockMvc.perform(get("/api/health"))
.andExpect(status().isServiceUnavailable())
.andExpect(jsonPath("$.status").value("down"))
.andExpect(jsonPath("$.db").value("down"))
.andExpect(jsonPath("$.length()").value(2));
}
}
3 changes: 3 additions & 0 deletions docs/deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ kullanıcısı, `/opt/mulakat`. Kalan adımlar:
curl -i https://slot.meteucar.com/api/health
ssh <VPS_USER>@<VPS_HOST> 'cd /opt/mulakat && docker compose -f docker-compose.prod.yml ps'
```
`/api/health` veritabanına da `SELECT 1` atar: 200 uygulamanın ve
DB bağlantısının ayakta olduğunu, 503 `{"status":"down","db":"down"}`
DB'ye erişilemediğini gösterir (ayrıntı backend logunda).
`docker compose ps` çıktısında üç servis de `healthy` olmalı. Dışarıdan
8081/8082'ye erişilemediğini de kontrol et:
`curl -m 5 http://<VPS_HOST>:8082/api/health` zaman aşımına uğramalı.
Expand Down
Loading