Compare commits

..

5 Commits

Author SHA1 Message Date
joungmin
ea8db4bef3 docs(changelog): v0.1.22 P4-3 인증/지도 결함 기록 2026-06-15 14:29:10 +09:00
joungmin
ed076411ed fix: P4-3 인증 메시지 + 지도 cleanup/터치/접근성 (#266+#278)
#266 (인증):
- AuthService.loginGoogle: catch-all에서 e.getMessage() 노출 → "Invalid Google token"
  고정 메시지 + 상세는 log.warn (Google verifier 내부 오류 정보 누출 차단)

#278 (지도):
- boundsTimerRef 언마운트 cleanup (unmounted setState 경고 + 메모리 누수 방지)
- '내 위치' 버튼 36×36 → 44×44 + aria-label='내 위치로 이동' + touch-manipulation
- dead code 제거 (indexRef set-only, restaurantMap 미사용)

#277 (health) — 결함 모두 후속 분리 (deep health, version, 테스트, rate limit)

후속 분리:
- #338 (deep health/version/Actuator)
- #339 (hex → brand-* 토큰 + 마커 ARIA + 테스트)
- #340 (다중 audience verifier + AuthService 테스트)

Refs: #266 #277 #278
2026-06-15 14:25:53 +09:00
joungmin
865cd86aff docs(changelog): v0.1.21 데몬/캐시/통계 결함 기록 2026-06-15 14:22:13 +09:00
joungmin
c6428e5d5f fix(infra): P4-2 데몬/캐시/통계 결함 (#275+#276+#274)
#275 (데몬):
- DaemonConfigService.updateConfig: 정수 필드 가드 (비숫자/0/음수 → 400)
- DaemonScheduler: 외부 호출(scan/process) try-finally로 updateLastX 보장
  (예외 시에도 다음 cron까지 backoff)
- DaemonController.getConfig: AuthUtil.requireAdmin() 추가 (운영 설정 노출 차단)

#276 (캐시):
- CacheService 생성자: ping을 try-with-resources로 자원 누수 차단,
  ConnectionFactory null 가드
- makeKey: null/빈 parts 가드 (잘못된 키 생성 방지)

#274 (통계):
- SiteVisitStats: int → long (21억 누적 시 오버플로 방지)
- StatsMapper: getTodayVisits/getTotalVisits long 반환
- StatsService.recordVisit: 자정 경계 동시성 DataIntegrityViolationException
  1회 재시도, 2회 실패 시 1건 손실 수용 (운영 영향 미미)

후속 분리:
- #336 (#275 분산 락 + DTO + 테스트)
- #337 (#276 SCAN + 자동복구 + 메트릭)
- #338 (#274 봇/레이트리밋 + Redis INCR + 테스트)

Refs: #275 #276 #274
2026-06-15 14:20:14 +09:00
joungmin
5579c5b00f docs(changelog): v0.1.20 백엔드 CRUD 결함 기록 (#290+#294+#295) 2026-06-15 14:16:41 +09:00
10 changed files with 116 additions and 28 deletions

View File

@@ -6,6 +6,27 @@
## 2026-06-15 ## 2026-06-15
### 🔐 P4-3 인증 메시지 + 지도 접근성 (v0.1.22)
- #266: Google verifier 실패 메시지 고정 + log.warn (정보 누출 차단)
- #278: boundsTimerRef cleanup, '내 위치' 44px + aria-label, dead code 제거
- #277: 결함 모두 후속(#338) — deep health/version/테스트는 별도
- 후속 분리: #338(deep health), #339(브랜드 토큰화/마커 ARIA), #340(다중 audience)
- Refs: #266 #277 #278 (close)
### ⚙️ P4-2 데몬/캐시/통계 결함 (v0.1.21)
- #275: updateConfig 가드(1+ 정수), Scheduler try-finally updateLastX, GET config admin-only
- #276: ping try-with-resources + ConnectionFactory null 가드, makeKey null 가드
- #274: SiteVisitStats int → long, recordVisit DataIntegrityViolationException 1회 재시도
- 후속 분리: #335 (분산락), #336 (SCAN/자동복구), #337 (봇/레이트리밋)
- Refs: #275 #276 #274 (close)
### 🧱 P4-1 백엔드 CRUD 결함 (v0.1.20)
- #294: MemoService/ReviewService 동시성 DuplicateKeyException 가드, rating 0~5 검증, getAvgRating NVL
- #295: 유니크 충돌 typed exception, channel_id "UC..." 형식 명시 분기, findByChannelId 컬럼 보완, body null 가드
- #290: @PreDestroy executor shutdown, 캐시 silent → log.warn + cache.del, tabling/catchtable URL 스킴 화이트리스트
- 후속 분리: #332(#290), #333(#295), #334(#294) — DTO/DDG/세분화/테스트
- Refs: #290 #294 #295 (close)
### 🔍 #293 검색/벡터 결함 7건 (v0.1.19) ### 🔍 #293 검색/벡터 결함 7건 (v0.1.19)
- SearchController: q 빈값 400 가드 (`%%` 응답 폭발 차단) - SearchController: q 빈값 400 가드 (`%%` 응답 폭발 차단)
- SearchService: LIKE 와일드카드 escape (%, _, \), hybrid 모드에서 sem 결과에도 채널 부착 - SearchService: LIKE 와일드카드 escape (%, _, \), hybrid 모드에서 sem 결과에도 채널 부착

View File

@@ -19,6 +19,8 @@ public class DaemonController {
@GetMapping("/config") @GetMapping("/config")
public DaemonConfig getConfig() { public DaemonConfig getConfig() {
// #275 — 데몬 운영 설정은 admin 전용 (이전: 공개 노출 — 정보 누출 위험)
AuthUtil.requireAdmin();
DaemonConfig config = daemonConfigService.getConfig(); DaemonConfig config = daemonConfigService.getConfig();
return config != null ? config : DaemonConfig.builder().build(); return config != null ? config : DaemonConfig.builder().build();
} }

View File

@@ -10,6 +10,7 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class SiteVisitStats { public class SiteVisitStats {
private int today; // #274 — long으로 변경 (21억 이상 누적 시 int 오버플로 방지)
private int total; private long today;
private long total;
} }

View File

@@ -7,7 +7,7 @@ public interface StatsMapper {
void recordVisit(); void recordVisit();
int getTodayVisits(); long getTodayVisits();
int getTotalVisits(); long getTotalVisits();
} }

View File

@@ -6,6 +6,8 @@ import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.json.gson.GsonFactory;
import com.tasteby.domain.UserInfo; import com.tasteby.domain.UserInfo;
import com.tasteby.security.JwtTokenProvider; import com.tasteby.security.JwtTokenProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -17,6 +19,8 @@ import java.util.Map;
@Service @Service
public class AuthService { public class AuthService {
private static final Logger log = LoggerFactory.getLogger(AuthService.class);
private final UserService userService; private final UserService userService;
private final JwtTokenProvider jwtProvider; private final JwtTokenProvider jwtProvider;
private final GoogleIdTokenVerifier verifier; private final GoogleIdTokenVerifier verifier;
@@ -58,7 +62,10 @@ public class AuthService {
} catch (ResponseStatusException e) { } catch (ResponseStatusException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Google token: " + e.getMessage()); // #266 — 외부에는 고정 메시지만, 상세는 로그로 (Google verifier 내부 네트워크/공개키
// 조회 실패 메시지가 클라이언트에 노출되지 않도록)
log.warn("Google token verification failed: {}", e.getMessage());
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Google token");
} }
} }

View File

@@ -27,8 +27,15 @@ public class CacheService {
this.redis = redis; this.redis = redis;
this.mapper = mapper; this.mapper = mapper;
this.ttl = Duration.ofSeconds(ttlSeconds); this.ttl = Duration.ofSeconds(ttlSeconds);
try { // #276 — ping 연결 자원 누수 방지: try-with-resources
redis.getConnectionFactory().getConnection().ping(); var factory = redis.getConnectionFactory();
if (factory == null) {
log.warn("Redis ConnectionFactory is null, caching disabled");
disabled = true;
return;
}
try (var conn = factory.getConnection()) {
conn.ping();
log.info("Redis connected"); log.info("Redis connected");
} catch (Exception e) { } catch (Exception e) {
log.warn("Redis unavailable ({}), caching disabled", e.getMessage()); log.warn("Redis unavailable ({}), caching disabled", e.getMessage());
@@ -37,6 +44,13 @@ public class CacheService {
} }
public String makeKey(String... parts) { public String makeKey(String... parts) {
// #276 — null/빈 파트로 "tasteby::" 같은 잘못된 키 생성 방지
if (parts == null || parts.length == 0) {
throw new IllegalArgumentException("makeKey requires at least one part");
}
for (String p : parts) {
if (p == null) throw new IllegalArgumentException("makeKey parts must not be null");
}
return PREFIX + String.join(":", parts); return PREFIX + String.join(":", parts);
} }

View File

@@ -2,7 +2,9 @@ package com.tasteby.service;
import com.tasteby.domain.DaemonConfig; import com.tasteby.domain.DaemonConfig;
import com.tasteby.mapper.DaemonConfigMapper; import com.tasteby.mapper.DaemonConfigMapper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.util.Map; import java.util.Map;
@@ -27,20 +29,33 @@ public class DaemonConfigService {
current.setScanEnabled(Boolean.TRUE.equals(body.get("scan_enabled"))); current.setScanEnabled(Boolean.TRUE.equals(body.get("scan_enabled")));
} }
if (body.containsKey("scan_interval_min")) { if (body.containsKey("scan_interval_min")) {
current.setScanIntervalMin(((Number) body.get("scan_interval_min")).intValue()); // #275 — 0/음수 입력으로 30초 사이클 폭주 방지. ClassCastException 대신 400.
current.setScanIntervalMin(requirePositiveInt(body.get("scan_interval_min"), "scan_interval_min"));
} }
if (body.containsKey("process_enabled")) { if (body.containsKey("process_enabled")) {
current.setProcessEnabled(Boolean.TRUE.equals(body.get("process_enabled"))); current.setProcessEnabled(Boolean.TRUE.equals(body.get("process_enabled")));
} }
if (body.containsKey("process_interval_min")) { if (body.containsKey("process_interval_min")) {
current.setProcessIntervalMin(((Number) body.get("process_interval_min")).intValue()); current.setProcessIntervalMin(requirePositiveInt(body.get("process_interval_min"), "process_interval_min"));
} }
if (body.containsKey("process_limit")) { if (body.containsKey("process_limit")) {
current.setProcessLimit(((Number) body.get("process_limit")).intValue()); current.setProcessLimit(requirePositiveInt(body.get("process_limit"), "process_limit"));
} }
mapper.updateConfig(current); mapper.updateConfig(current);
} }
/** #275 — 양의 정수 가드. 비숫자/0/음수는 400. */
private static int requirePositiveInt(Object raw, String field) {
if (!(raw instanceof Number n)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, field + "은(는) 정수여야 합니다");
}
int v = n.intValue();
if (v < 1) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, field + "은(는) 1 이상이어야 합니다 (폭주 방지)");
}
return v;
}
public void updateLastScan() { public void updateLastScan() {
mapper.updateLastScan(); mapper.updateLastScan();
} }

View File

@@ -50,8 +50,13 @@ public class DaemonScheduler {
Instant lastScan = config.getLastScanAt() != null ? config.getLastScanAt().toInstant() : null; Instant lastScan = config.getLastScanAt() != null ? config.getLastScanAt().toInstant() : null;
if (lastScan == null || Instant.now().isAfter(lastScan.plus(config.getScanIntervalMin(), ChronoUnit.MINUTES))) { if (lastScan == null || Instant.now().isAfter(lastScan.plus(config.getScanIntervalMin(), ChronoUnit.MINUTES))) {
log.info("Running scheduled channel scan..."); log.info("Running scheduled channel scan...");
int newVideos = youTubeService.scanAllChannels(); int newVideos = 0;
try {
newVideos = youTubeService.scanAllChannels();
} finally {
// #275 — 외부 호출 예외 시에도 last_scan_at을 갱신해 다음 cron까지의 backoff를 보장
daemonConfigService.updateLastScan(); daemonConfigService.updateLastScan();
}
if (newVideos > 0) { if (newVideos > 0) {
cacheService.flush(); cacheService.flush();
log.info("Scan completed: {} new videos", newVideos); log.info("Scan completed: {} new videos", newVideos);
@@ -63,8 +68,12 @@ public class DaemonScheduler {
Instant lastProcess = config.getLastProcessAt() != null ? config.getLastProcessAt().toInstant() : null; Instant lastProcess = config.getLastProcessAt() != null ? config.getLastProcessAt().toInstant() : null;
if (lastProcess == null || Instant.now().isAfter(lastProcess.plus(config.getProcessIntervalMin(), ChronoUnit.MINUTES))) { if (lastProcess == null || Instant.now().isAfter(lastProcess.plus(config.getProcessIntervalMin(), ChronoUnit.MINUTES))) {
log.info("Running scheduled video processing (limit={})...", config.getProcessLimit()); log.info("Running scheduled video processing (limit={})...", config.getProcessLimit());
int restaurants = pipelineService.processPending(config.getProcessLimit()); int restaurants = 0;
try {
restaurants = pipelineService.processPending(config.getProcessLimit());
} finally {
daemonConfigService.updateLastProcess(); daemonConfigService.updateLastProcess();
}
if (restaurants > 0) { if (restaurants > 0) {
cacheService.flush(); cacheService.flush();
log.info("Processing completed: {} restaurants extracted", restaurants); log.info("Processing completed: {} restaurants extracted", restaurants);

View File

@@ -2,11 +2,16 @@ package com.tasteby.service;
import com.tasteby.domain.SiteVisitStats; import com.tasteby.domain.SiteVisitStats;
import com.tasteby.mapper.StatsMapper; import com.tasteby.mapper.StatsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class StatsService { public class StatsService {
private static final Logger log = LoggerFactory.getLogger(StatsService.class);
private final StatsMapper mapper; private final StatsMapper mapper;
public StatsService(StatsMapper mapper) { public StatsService(StatsMapper mapper) {
@@ -14,7 +19,19 @@ public class StatsService {
} }
public void recordVisit() { public void recordVisit() {
// #274 — 자정 경계 동시성: 두 트랜잭션이 동시에 'NOT MATCHED' 판정 → 둘 다 INSERT
// → PK/UNIQUE 충돌 시 한 쪽 500. 1회 재시도(다음엔 MATCHED → UPDATE 분기).
try {
mapper.recordVisit(); mapper.recordVisit();
} catch (DataIntegrityViolationException e) {
log.debug("recordVisit conflict (midnight race), retry once: {}", e.getMessage());
try {
mapper.recordVisit();
} catch (DataIntegrityViolationException retryFail) {
// 두 번째 시도도 실패: 카운트 1건 손실은 수용 (운영 영향 미미)
log.warn("recordVisit double-conflict, dropping one count: {}", retryFail.getMessage());
}
}
} }
public SiteVisitStats getVisits() { public SiteVisitStats getVisits() {

View File

@@ -67,8 +67,7 @@ type RestaurantProps = { restaurant: Restaurant };
type RestaurantFeature = Supercluster.PointFeature<RestaurantProps>; type RestaurantFeature = Supercluster.PointFeature<RestaurantProps>;
function useSupercluster(restaurants: Restaurant[]) { function useSupercluster(restaurants: Restaurant[]) {
const indexRef = useRef<Supercluster<{ restaurant: Restaurant }> | null>(null); // #278 — indexRef 제거 (set만 되고 read 없는 dead code)
const points: RestaurantFeature[] = useMemo( const points: RestaurantFeature[] = useMemo(
() => () =>
restaurants.map((r) => ({ restaurants.map((r) => ({
@@ -86,7 +85,6 @@ function useSupercluster(restaurants: Restaurant[]) {
minPoints: 2, minPoints: 2,
}); });
sc.load(points); sc.load(points);
indexRef.current = sc;
return sc; return sc;
}, [points]); }, [points]);
@@ -129,12 +127,7 @@ function MapContent({ restaurants, selected, onSelectRestaurant, flyTo, activeCh
const channelColors = useMemo(() => getChannelColorMap(restaurants), [restaurants]); const channelColors = useMemo(() => getChannelColorMap(restaurants), [restaurants]);
const { getClusters, getExpansionZoom } = useSupercluster(restaurants); const { getClusters, getExpansionZoom } = useSupercluster(restaurants);
// Build a lookup for restaurants by id // #278 — restaurantMap 제거 (빌드만 되고 렌더에서 사용 안 됨, dead code)
const restaurantMap = useMemo(() => {
const m: Record<string, Restaurant> = {};
restaurants.forEach((r) => { m[r.id] = r; });
return m;
}, [restaurants]);
const clusters = useMemo(() => { const clusters = useMemo(() => {
if (!bounds) return []; if (!bounds) return [];
@@ -273,7 +266,7 @@ function MapContent({ restaurants, selected, onSelectRestaurant, flyTo, activeCh
textDecoration: isClosed ? "line-through" : "none", textDecoration: isClosed ? "line-through" : "none",
}} }}
> >
<span className="material-symbols-rounded" style={{ fontSize: 14, marginRight: 3, verticalAlign: "middle", color: "#E8720C" }}>{getCuisineIcon(r.cuisine_type)}</span> <span className="material-symbols-rounded" style={{ fontSize: 14, width: 14, height: 14, overflow: "hidden", display: "inline-flex", alignItems: "center", justifyContent: "center", marginRight: 3, verticalAlign: "middle", color: "#E8720C" }}>{getCuisineIcon(r.cuisine_type)}</span>
{r.name} {r.name}
</div> </div>
<div <div
@@ -298,7 +291,7 @@ function MapContent({ restaurants, selected, onSelectRestaurant, flyTo, activeCh
> >
<div style={{ backgroundColor: "#ffffff", color: "#171717", colorScheme: "light" }} className="max-w-xs p-1"> <div style={{ backgroundColor: "#ffffff", color: "#171717", colorScheme: "light" }} className="max-w-xs p-1">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<h3 className="font-bold text-base" style={{ color: "#171717" }}><span className="material-symbols-rounded" style={{ fontSize: 18, verticalAlign: "middle", color: "#E8720C", marginRight: 4 }}>{getCuisineIcon(infoTarget.cuisine_type)}</span>{infoTarget.name}</h3> <h3 className="font-bold text-base" style={{ color: "#171717" }}><span className="material-symbols-rounded" style={{ fontSize: 18, width: 18, height: 18, overflow: "hidden", display: "inline-flex", alignItems: "center", justifyContent: "center", verticalAlign: "middle", color: "#E8720C", marginRight: 4 }}>{getCuisineIcon(infoTarget.cuisine_type)}</span>{infoTarget.name}</h3>
{infoTarget.business_status === "CLOSED_PERMANENTLY" && ( {infoTarget.business_status === "CLOSED_PERMANENTLY" && (
<span className="px-1.5 py-0.5 bg-red-100 text-red-700 rounded text-[10px] font-semibold"></span> <span className="px-1.5 py-0.5 bg-red-100 text-red-700 rounded text-[10px] font-semibold"></span>
)} )}
@@ -357,6 +350,13 @@ export default function MapView({ restaurants, selected, onSelectRestaurant, onB
}, 150); }, 150);
}, [onBoundsChanged]); }, [onBoundsChanged]);
// #278 — 언마운트 시 디바운스 타이머 정리 (메모리 누수 + unmounted setState 경고 방지)
useEffect(() => {
return () => {
if (boundsTimerRef.current) clearTimeout(boundsTimerRef.current);
};
}, []);
return ( return (
<APIProvider apiKey={API_KEY}> <APIProvider apiKey={API_KEY}>
<Map <Map
@@ -380,10 +380,12 @@ export default function MapView({ restaurants, selected, onSelectRestaurant, onB
{onMyLocation && ( {onMyLocation && (
<button <button
onClick={onMyLocation} onClick={onMyLocation}
className="absolute top-2 right-2 w-9 h-9 bg-surface rounded-lg shadow-md flex items-center justify-center text-gray-600 dark:text-gray-300 hover:text-brand-500 dark:hover:text-brand-400 transition-colors z-10" aria-label="내 위치로 이동"
// #278 — 44×44px 터치 영역 확보 (이전 36px)
className="absolute top-2 right-2 w-11 h-11 bg-surface rounded-lg shadow-md flex items-center justify-center text-gray-600 dark:text-gray-300 hover:text-brand-500 dark:hover:text-brand-400 transition-colors z-10 touch-manipulation"
title="내 위치" title="내 위치"
> >
<Icon name="my_location" size={20} /> <Icon name="my_location" size={22} />
</button> </button>
)} )}
{channelNames.length > 0 && ( {channelNames.length > 0 && (