diff --git a/.github/workflows/ci-cd_dev.yml b/.github/workflows/ci-cd_dev.yml index c7b1cc3..89cf968 100644 --- a/.github/workflows/ci-cd_dev.yml +++ b/.github/workflows/ci-cd_dev.yml @@ -60,10 +60,8 @@ jobs: if: github.event_name == 'push' runs-on: ubuntu-latest steps: - - name: Deploy to CapRover - uses: caprover/deploy-from-github@v1.1.2 - with: - server: ${{ secrets.CAPROVER_SERVER }} - app: ${{ secrets.CAPROVER_DEV_APP_NAME }} - token: ${{ secrets.CAPROVER_DEV_APP_TOKEN }} - image: ${{ env.DOCKER_IMAGE }}:latest + - name: Trigger Coolify deploy + run: | + curl --fail --show-error --silent --request GET \ + "${{ secrets.COOLIFY_URL }}/api/v1/deploy?uuid=${{ secrets.COOLIFY_DEV_RESOURCE_UUID }}&force=true" \ + --header "Authorization: Bearer ${{ secrets.COOLIFY_API_TOKEN }}" diff --git a/.github/workflows/ci-cd_prod.yml b/.github/workflows/ci-cd_prod.yml index c0b2e27..e04cd81 100644 --- a/.github/workflows/ci-cd_prod.yml +++ b/.github/workflows/ci-cd_prod.yml @@ -59,10 +59,8 @@ jobs: if: github.event_name == 'push' runs-on: ubuntu-latest steps: - - name: Deploy to CapRover - uses: caprover/deploy-from-github@v1.1.2 - with: - server: ${{ secrets.CAPROVER_SERVER }} - app: ${{ secrets.CAPROVER_PROD_APP_NAME }} - token: ${{ secrets.CAPROVER_PROD_APP_TOKEN }} - image: ${{ env.DOCKER_IMAGE }}:latest + - name: Trigger Coolify deploy + run: | + curl --fail --show-error --silent --request GET \ + "${{ secrets.COOLIFY_URL }}/api/v1/deploy?uuid=${{ secrets.COOLIFY_PROD_RESOURCE_UUID }}&force=true" \ + --header "Authorization: Bearer ${{ secrets.COOLIFY_API_TOKEN }}" diff --git a/CLAUDE.md b/CLAUDE.md index e93eadf..257d148 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ - **JPA + QueryDSL** (MySQL) - **Spring Security** (JWT + Google OAuth2) - **Firebase Cloud Messaging** (푸시 알림) -- **AWS S3** (이미지 업로드) +- **Cloudflare R2** (이미지 업로드, AWS SDK v2 S3 호환 API) - **Apache POI** (Excel 생성) ## 빌드 & 실행 @@ -72,13 +72,63 @@ domain/{name}/ ## 서비스 의존성 ``` -ItemService → ItemRepository, S3Service -MemberService → MemberRepository, TokenProvider, PayerService -NotificationService → NotificationRepository, FCMService, MemberService -PayerService → PayerRepository, MemberRepository, ExcelGenerator -RentalService → RentalRepository, NotificationService +ItemService → ItemRepository, FileStorageService(R2Service) +MemberService → MemberRepository, TokenProvider, PayerService +NotificationService → NotificationRepository, NotificationPushOutboxService +NotificationPushOutboxService → NotificationPushOutboxRepository +PushNotificationSender → FCMService, MemberService, NotificationPushOutboxService +PayerService → PayerRepository, MemberRepository, ExcelGenerator +RentalService → RentalRepository, ApplicationEventPublisher ``` +### 알림 발송 구조 + +`RentalService`가 이벤트를 발행하면 `NotificationEventHandler`가 커밋 이후 비동기로 받아 처리한다. + +``` +RentalService → 이벤트 발행 + └ NotificationEventHandler (@Async + AFTER_COMMIT, 트랜잭션 없음) + ├ NotificationService.createNotification() # 알림 + 아웃박스 저장 (한 트랜잭션, 즉시 커밋) + └ PushNotificationSender.dispatch() # 트랜잭션 밖에서 FCM 호출 + +PushRetryScheduler (@Scheduled, 30초 간격) + └ PushNotificationSender.dispatch() # 미발송 건 재시도 (같은 경로) +``` + +- **푸시 발송은 트랜잭션 밖에서 수행한다** — 네트워크 I/O가 DB 커넥션을 점유하지 않도록, 그리고 푸시 실패가 저장된 알림을 롤백시키지 않도록 분리 +- **`PushNotificationSender`는 예외를 전파하지 않는다** — 한 수신자의 실패가 다른 수신자에게 영향을 주면 안 됨 +- **FCM 실패는 `PushResult`로 구분한다** — `InvalidToken`(토큰 제거) / `Retryable`(재시도 대상) / `Permanent`(재시도 무의미) +- **`@Async`는 알림 전용 실행기(`notificationTaskExecutor`)를 사용한다** — `AsyncConfig`에 정의 + +### 푸시 재시도 (아웃박스) + +발송 대상을 `notification_push_outbox`에 **수신자 단위 row**로 남긴다. 알림과 같은 트랜잭션에서 저장되므로 프로세스가 재시작돼도 발송 대상이 남는다. + +``` +PENDING ─┬─ 발송 성공 ──────────────→ SENT + ├─ Retryable 실패 ─ 백오프 → PENDING (재시도 횟수 소진 시 FAILED) + ├─ InvalidToken/Permanent → FAILED + └─ 생성 후 1시간 경과 ─────→ EXPIRED +``` + +- **유효 시간(TTL)은 10분** — 사용자 알림은 지금 과방에 갈지를 결정하는 정보고, 관리자 알림도 학생이 기다리는 상태에서 처리해야 하는 일이라 둘 다 실시간성이 중요하다. 지나면 `EXPIRED`로 포기하며, 인앱 알림은 이미 저장돼 있으므로 정보가 사라지는 것은 아니다 +- **백오프는 `30초 → 2분 → 5분`, 최대 3회** — 누적 7분 30초로 유효 시간 안에 들어온다 +- **다음 재시도 시각이 TTL을 넘기면 예약하지 않고 즉시 포기한다** — 어차피 만료될 시도를 기다리지 않는다 +- **즉시 발송과 재시도가 같은 경로를 탄다** — 새 row의 `nextRetryAt`은 60초 뒤로 잡혀, 즉시 시도와 폴러가 겹치지 않는다 +- **메시지 본문은 저장하지 않는다** — 연결된 `Notification`의 status와 formatValues로 재구성 +- 인스턴스를 여러 대로 늘리면 조회에 잠금(`FOR UPDATE SKIP LOCKED`)이나 ShedLock이 필요하다 + +**보관 정책** — `PushOutboxPurgeScheduler`가 매일 새벽 4시(KST)에 정리한다. + +| 상태 | 보존 기간 | +|---|---| +| `SENT` | 7일 | +| `FAILED`, `EXPIRED` | 30일 (실패 원인 확인용) | +| `PENDING` | 삭제하지 않음 | + +- **배치(500건)로 나눠 삭제하고 배치마다 트랜잭션을 끊는다** — 락 구간을 짧게 유지 +- **한 회 처리량 상한(20배치)에 도달하면 경고 로그를 남긴다** — 남은 건이 있다는 사실이 묻히지 않도록 + ## 대여 상태 머신 ``` @@ -173,7 +223,7 @@ global/ ├── exception/ # ApiException, ErrorCode, GlobalExceptionHandler ├── external/ │ ├── fcm/ # FCMConfig, FCMService -│ └── s3/ # S3Config, S3Service +│ └── r2/ # R2Config, R2Service (FileStorageService 구현체) ├── logging/ # LoggingFilter ├── security/ │ ├── jwt/ # TokenProvider, TokenAuthenticationFilter diff --git a/README.md b/README.md new file mode 100644 index 0000000..5b985e0 --- /dev/null +++ b/README.md @@ -0,0 +1,242 @@ +# 빌릴게 (Billilge) — 국민대학교 소프트웨어융합대학 복지물품 대여 서비스 + +> 학생회실 방문·엑셀 대조에 의존하던 복지물품 대여를 **온라인 신청, 납부자 검증, 재고·대여 상태 관리, 관리자 알림**으로 연결한 서비스입니다. +> +> **이 저장소는 빌릴게 백엔드**를 다룹니다. 개발 후 실제 학생회 운영 과정에서 발생한 정책·안정성·성능 문제를 지속적으로 개선하고 있습니다. + +## 1. 프로젝트 소개 + +국민대학교 소프트웨어융합대학 학생회는 우산, 충전기 등 학생들이 잠시 필요로 하는 물품을 대여합니다. 하지만 기존 운영 방식에서는 학생이 물품 현황을 확인하거나 신청하려면 학생회실을 방문해야 했고, 운영진은 학생회비 납부 여부와 재고·대여 기록을 엑셀 및 수작업으로 관리해야 했습니다. + +빌릴게는 이러한 과정을 시스템으로 옮겨 **학생은 방문 전에 대여를 신청하고, 운영진은 승인·대여·반납 업무에 집중**할 수 있도록 만들었습니다. 단순 신청 폼에서 끝내지 않고, 학생회 정책과 실제 운영 흐름을 서버의 비즈니스 규칙으로 구현했습니다. + +### 해결하고자 한 문제 + + +| 기존 문제 | 빌릴게의 해결 방향 | +| ---------------------------- | ----------------------- | +| 방문해야만 확인할 수 있는 물품·재고 | 물품 목록 및 재고 현황 온라인 제공 | +| 운영진이 엑셀에서 직접 확인하던 회비 납부 여부 | 가입·납부자 명단 연동을 통한 자격 확인 | +| 신청·승인·수령·반납 상태를 사람마다 다르게 기록 | 대여 상태와 처리 이력의 일원화 | +| 근무자가 현장에 상주하거나 반복 안내해야 하는 부담 | 사전 신청, 관리자 대시보드 및 알림 제공 | +| 학기별 정책 변경에 따른 반복적인 코드 수정 | 시험 기간 등 운영 설정의 데이터화 | + + +### 운영 성과 + + +| 지표 | 결과 | +| ----------------- | ------------------------------------------------------- | +| 연간 대여 이용 | **101건 → 178건** (**약 76% 증가**, 도입 첫해 전후 비교) | +| 누적 대여 이용 | **668건** (2026년 10월 15일 기준, 서비스 운영 집계) | +| 관리자 알림 모델 | 동일 공지를 관리자 수만큼 저장하던 방식에서 **공지 1건 저장**으로 변경 | +| 납부자 목록 조회 API p95 | 약 47% 감소 (스테이징 환경에서 SQL 콘솔 로깅 제거 전후) | + + +> 이용 건수는 학생회 운영 집계에 기반한 지표입니다. API 지연 수치는 **가상 사용자 100명 · 5분 · 납부자 약 2,000건** 조건에서 측정한 특정 API(`GET /admin/members/payers`) 결과로, 서비스 전체 응답 속도를 의미하지 않습니다. 비동기 로깅 도입의 추가 개선량은 별도 측정이 필요합니다. [관련 PR #152](https://github.com/billilge/backend/pull/152) + +## 2. 주요 기능 + +### 학생 + +- Google OAuth2 로그인 및 JWT 기반 인증 +- 복지물품 목록·재고 조회, 대여 신청 및 신청 취소 +- 대여 진행 상태 및 이력 조회, 반납 신청 +- 신청·승인·반려·반납 관련 인앱 알림 및 FCM 푸시 + +### 운영진 + +- 신청 승인·반려, 대여·반납 상태 관리 및 처리자 기록 +- 물품 등록·수정·재고 관리, 관리자 대시보드 +- 학생회비 납부자 명단 관리와 엑셀 다운로드 +- 관리자 권한 구분(`ADMIN`, `WORKER`, `GA`) 및 관리 기능 접근 통제 +- 시험 기간 등 운영 정책 설정, 디스플레이 일정·포스터 관리 + +## 3. 서비스 정책과 도메인 설계 + +### 3.1 학생회비 납부자 검증: 불완전한 원천 데이터와 오인증 위험 + +**문제** — 운영 명단은 학번의 일부가 마스킹되거나 누락될 수 있고, 이름만으로 검증하면 동명이인에게 잘못 대여 자격을 부여할 수 있습니다. 회원가입 흐름에 엑셀의 불완전한 데이터 모델을 그대로 옮길 수 없었습니다. + +**설계** — 납부자(`Payer`)와 서비스 회원(`Member`)을 분리하고, 회원가입 시 이름·입학연도로 납부자 후보를 조회한 다음 후보 수와 학번 일치 여부를 검토합니다. 이름 하나만으로 납부자를 확정하지 않으며, 납부자 명단의 등록·삭제에 따라 회원의 `isFeePaid`도 갱신합니다. 이름과 입학연도 조회, 전체 학번 비교, 마스킹 값(`XXXX`) 처리 분기를 별도로 둔 것이 특징입니다. + +**의사결정** — 인증 정보와 회비 납부 기록은 출처·갱신 주기가 다르므로 하나의 회원 엔티티로 합치지 않았습니다. 다만 현재 코드는 모든 부분 누락 사례를 일반화해 해결하는 정교한 신원확인 시스템이 아니며, 명단 형식과 매칭 예외 케이스에 대한 추가 검증이 필요합니다. + +- 구현: [`PayerService.isPayer()`](https://github.com/billilge/backend/blob/develop/src/main/kotlin/site/billilge/api/backend/domain/payer/service/PayerService.kt) + +### 3.2 대여 정책을 서버에서 검증 + +대여 신청은 화면의 버튼 표시 여부에 의존하지 않고 **서버에서 자격·재고·시간 규칙을 확인**합니다. + + +| 정책 | 현재 동작 | +| ------ | -------------------------------------------------- | +| 이용 자격 | 학생회비 납부자로 등록된 회원만 신청 가능 | +| 수량 | 신청 수량이 가용 재고를 초과하면 거절 | +| 중복 대여 | 동일 회원의 동일 물품 대여 중복 검증 (`ignoreDuplicate` 예외 경로 존재) | +| 운영 시간 | 주말·지난 시각·설정된 시간 범위 외 신청 제한 (기본 로직 10\~17시) | +| 시험 기간 | DB에 등록한 시작·종료일 동안 대여 신청 제한 | +| 관리자 등록 | 관리자 수기 등록은 일반 학생 신청과 별도의 처리 흐름 제공 | +| 소모품 | 반환 재고 복원을 하지 않고 지급 완료 상태로 처리 | + + +시험 기간의 시작·종료일은 `ConfigValue`에 저장해 운영진이 변경할 수 있도록 했습니다. **정책을 소스코드 상수에서 운영 데이터로 분리**한 사례입니다. + +> 현재 구현의 대여 시간 검사는 `hour > 17`만 거절하므로 **17시대 시각을 허용**합니다. 운영 정책을 ‘17:00까지’로 정의하려면 분 단위 경계까지 추가 확인해야 합니다. + +- 구현: [`RentalService`](https://github.com/billilge/backend/blob/develop/src/main/kotlin/site/billilge/api/backend/domain/rental/service/RentalService.kt), [`ConfigValueService`](https://github.com/billilge/backend/blob/develop/src/main/kotlin/site/billilge/api/backend/domain/configvalue/service/ConfigValueService.kt) + +### 3.3 대여 상태 관리 + +![대여 상태 흐름](images/rental-status-flow.png) + +- **승인 시 재고 차감**, **반납 완료 시 재고 복원**(소모품은 제외) +- 관리자 처리자(`worker`)와 상태별 로그(`RentalStatusWorkerLog`) 저장 +- 소모품은 대여 중 상태 대신 최종 완료 상태로 전환하는 별도 규칙 적용 + +> 다이어그램은 정상 흐름을 이해하기 위한 대표 경로입니다. 실제 코드는 상태 변경 API로 처리하며, 모든 상태 간 전이를 전용 상태 머신이 강제하는 것은 아닙니다. + +## 4. 기술적 문제 해결 + +### 4.1 관리자 알림의 데이터 모델 재정의 + +**문제** — 관리자가 약 40명인 환경에서 동일한 대여 공지를 관리자별로 저장하면 **하나의 사건으로부터 여러 개의 동일한 알림 레코드**가 생성됩니다. 또한 푸시를 대여 요청 흐름에서 동기 발송하면 FCM 호출 시간이 응답 지연으로 이어집니다. + +**해결** — 관리자 알림은 개인에게 귀속된 메시지가 아니라 운영진 모두가 보는 **공통 공지**라는 점에 착안했습니다. + +- `Notification.member = null`인 관리자 공지 레코드를 **1건만 저장** +- 푸시 전송은 별도의 수신자 목록과 발송 Outbox로 관리 +- 대여 트랜잭션 커밋 후 `@TransactionalEventListener(AFTER_COMMIT)` + `@Async`로 후속 알림 작업 실행 + +**효과** — 동일 공지의 중복 저장을 제거하고 대여 비즈니스 트랜잭션과 알림 후속 처리를 분리했습니다. [관련 PR #93](https://github.com/billilge/backend/pull/93), [#116](https://github.com/billilge/backend/pull/116) + +### 4.2 FCM 실패에 대비한 Outbox 기반 재시도 + +**문제** — 단순 비동기화만으로는 FCM 일시 장애·네트워크 오류 발생 시 푸시가 조용히 누락될 수 있습니다. 이전 구현에서는 외부 호출이 알림 저장 트랜잭션 안에 있어 DB 커넥션 점유가 길어지고, 예외가 저장된 인앱 알림까지 롤백시킬 가능성도 있었습니다. + +**해결** — 알림 저장, 발송 대상 기록, 외부 네트워크 호출의 책임과 트랜잭션 경계를 분리했습니다. + +![푸시 알림 발송 시퀀스](images/push-notification-sequence.png) + + +| 설계 요소 | 결정과 이유 | +| ------ | --------------------------------------------------------- | +| 저장 원자성 | **Notification + 수신자별 Outbox**를 같은 트랜잭션에서 저장 | +| 외부 API | FCM 호출을 DB 트랜잭션 밖에서 수행해 커넥션 장기 점유 및 알림 롤백 방지 | +| 실패 분류 | `Success` / `InvalidToken` / `Retryable` / `Permanent` 구분 | +| 재시도 | 30초 → 2분 → 5분 백오프, 최대 3회 재시도 | +| 유효 시간 | **10분 TTL** 이후 `EXPIRED` 처리: 늦은 푸시보다 인앱 알림 확인을 우선 | +| 보관 | 전송 완료 7일, 실패·만료 30일 후 배치 정리 | +| 작업 실행 | 전용 스레드 풀(코어 4, 최대 8, 큐 500)과 종료 대기 설정 | + + +**트레이드오프** — 10분을 넘긴 푸시는 이미 지나간 대여 안내를 뒤늦게 전달할 수 있어 의도적으로 포기합니다. 인앱 알림은 남겨 둡니다. 또한 **대여 커밋 이후의 인메모리 이벤트 처리까지 Outbox로 원자화한 것은 아니므로**, 커밋 직후 프로세스가 종료되는 경우 알림 생성 자체가 누락될 가능성은 남아 있습니다. 다중 인스턴스에서 재시도 스케줄러가 동시에 실행되는 문제도 추가적인 잠금 설계가 필요합니다. + +- 구현: [`NotificationEventHandler`](https://github.com/billilge/backend/blob/develop/src/main/kotlin/site/billilge/api/backend/domain/notification/handler/NotificationEventHandler.kt), [`NotificationPushOutbox`](https://github.com/billilge/backend/blob/develop/src/main/kotlin/site/billilge/api/backend/domain/notification/entity/NotificationPushOutbox.kt) +- 설계 변경: [PR #145](https://github.com/billilge/backend/pull/145), [TTL 조정 PR #149](https://github.com/billilge/backend/pull/149) + +## 5. 아키텍처 및 기술 스택 + +### 백엔드 구조 + +```text +Controller ── HTTP 요청·응답, 인증 정보 추출 + ↓ +Facade ── DTO 변환, 여러 도메인 Service 조합 + ↓ +Service ── 도메인 규칙, 트랜잭션 경계 + ↓ +Repository ── Spring Data JPA, QueryDSL 기반 데이터 접근 +``` + +주요 도메인은 `member`, `payer`, `item`, `rental`, `notification`, `configvalue`, `display`로 나누었습니다. **Service에서 타 도메인 Repository를 직접 호출하지 않고 Facade에서 조합**하는 것을 기본 규칙으로 삼았습니다(일부 예외 존재). + +### 기술 스택 (현재 `develop` 브랜치 기준) + + +| 영역 | 기술 | +| ------------------ | ------------------------------------------------------------------ | +| Language / Runtime | **Kotlin 1.9.25, JDK 21** | +| Framework | **Spring Boot 3.4.1**, Spring MVC | +| Persistence | **Spring Data JPA, Hibernate, QueryDSL 5.0** | +| Database | **MySQL**, HikariCP / 테스트용 H2 | +| Security | Spring Security, Google OAuth2, JWT | +| Messaging | Firebase Cloud Messaging, Spring Application Event, `@Async`, 스케줄러 | +| File Storage | **Cloudflare R2** (AWS S3 → MinIO → R2 이전) | +| Documentation | Springdoc OpenAPI / Swagger UI | +| Build & Deploy | Gradle Kotlin DSL, Docker, Docker Hub, GitHub Actions, Coolify | +| Logging | Kotlin Logging, Logback AsyncAppender | + + +### 배포 흐름 + +```text +GitHub push (develop / main) + → GitHub Actions: Gradle 빌드 + → Docker 이미지 빌드·Docker Hub push + → Coolify API 배포 트리거 + → 개발 / 운영 서버 배포 +``` + +기존 CapRover에서 **Coolify**로 배포 트리거를 전환했고, 파일 저장소는 **S3 → MinIO**로 이전했습니다. 배포 파이프라인은 현재 `latest` 태그를 사용하므로, 추적·롤백 편의성을 높이기 위한 불변 이미지 태그 도입은 후속 개선 과제입니다. [PR #156](https://github.com/billilge/backend/pull/156), [PR #113](https://github.com/billilge/backend/pull/113) + +## 6. 실행 방법 + +**요구 환경:** JDK 21, MySQL, Cloudflare R2, Google OAuth2 및 Firebase 자격증명. + +```bash +# 프로젝트 클론 +git clone https://github.com/billilge/backend.git +cd backend + +# 빌드 (CI와 동일하게 테스트 실행 제외) +./gradlew clean build -x test + +# 개발 프로파일 실행 (사전 환경변수·외부 서비스 설정 필요) +profile=dev ./gradlew bootRun +``` + +주요 환경변수는 `DB_URL`, `DB_USERNAME`, `DB_PASSWORD`, `JWT_SECRET_KEY`, `JWT_ISSUER`, `OAUTH2_GOOGLE_CLIENT_ID`, `OAUTH2_GOOGLE_CLIENT_SECRET`, `R2_ENDPOINT`, `R2_ACCESS_KEY`, `R2_SECRET_KEY`, `R2_BUCKET`, `R2_PUBLIC_URL`, `CORS_ALLOWED_ORIGINS`, `SWAGGER_SERVER_BASE_URL`, `LOGIN_REDIRECT_URL`입니다. Firebase 서비스 계정 설정도 필요합니다. 실제 값은 저장소에 커밋하지 않습니다. + +- API 명세: 앱 실행 후 `/swagger` (Swagger UI), `/api-docs` (OpenAPI JSON) +- 자세한 프로파일 설정: [`application-dev.yml`](https://github.com/billilge/backend/blob/develop/src/main/resources/application-dev.yml) + +## 7. 개발자 + + + + + + +
+ + 황수민 프로필
+ 황수민 +

+ Backend · Infra +
+ + 이정욱 프로필
+ 이정욱 +

+ Backend +
+ +### 황수민 — 백엔드 · 인프라 + +- **기반 설계** — 프로젝트 초기 세팅, JPA 엔티티 설계, Controller–Facade–Service 계층 구조와 QueryDSL 기반 조회 도입 +- **인증·회원** — Google OAuth2 로그인, JWT 인증, 회원가입 시 학생회비 납부자 판별 (3.1) +- **운영진 기능** — 물품·회원·관리자 관리, 관리자 역할 분리(`ADMIN`, `WORKER`, `GA`), 대시보드, 대여 상태 변경과 처리자 기록, 납부자 명단 관리·엑셀 다운로드 +- **대여 정책** — 승인 시 재고 차감, 소모품 처리, 주말·시험 기간 제한, 운영 설정(`ConfigValue`) DB화 (3.2, 3.3) +- **알림** — FCM 푸시 구축, 관리자 공지형 알림 재설계, 이벤트 기반 발행 전환, Outbox 기반 재시도 (4.1, 4.2) +- **인프라·성능** — Docker·GitHub Actions 배포, CapRover → Coolify 전환, S3 → MinIO 이전, 납부자 조회 지연 진단과 로깅 개선 +- **디스플레이** — 디스플레이용 포스터·일정 API + +### 이정욱 — 백엔드 + +- **사용자 대여** — 대여 신청 API(중복 대여 검증, 한국 시간 기준 대여 시간 검증), 대여 이력 조회, 신청 취소, 반납 신청, 반납 필요 물품 조회 +- **사용자 알림** — 알림 목록 조회, 개별 알림 읽음 처리, 알림 타입 정의 +- **물품** — 물품 검색 조회 API +- **문서화** — Swagger API 명세 작성 + +> 프론트엔드는 [billilge/frontend](https://github.com/billilge/frontend), 관리자 웹은 [billilge/admin](https://github.com/billilge/admin) 저장소에서 확인할 수 있습니다. \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index b60b484..4b8b3dd 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -47,7 +47,7 @@ dependencies { implementation("org.thymeleaf.extras:thymeleaf-extras-springsecurity6") - implementation("io.minio:minio:8.5.7") + implementation("software.amazon.awssdk:s3:2.54.15") implementation("javax.xml.bind:jaxb-api:2.3.1") implementation("org.apache.tika:tika-core:2.9.2") implementation("org.apache.tika:tika-parsers-standard-package:2.9.2") diff --git a/images/push-notification-sequence.png b/images/push-notification-sequence.png new file mode 100644 index 0000000..aa737d5 Binary files /dev/null and b/images/push-notification-sequence.png differ diff --git a/images/rental-status-flow.png b/images/rental-status-flow.png new file mode 100644 index 0000000..aa688fe Binary files /dev/null and b/images/rental-status-flow.png differ diff --git a/src/main/kotlin/site/billilge/api/backend/domain/notification/dto/PushDispatchTarget.kt b/src/main/kotlin/site/billilge/api/backend/domain/notification/dto/PushDispatchTarget.kt new file mode 100644 index 0000000..95d0c3c --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/domain/notification/dto/PushDispatchTarget.kt @@ -0,0 +1,17 @@ +package site.billilge.api.backend.domain.notification.dto + +import site.billilge.api.backend.domain.notification.enums.NotificationStatus + +/** + * 아웃박스 한 건을 발송하는 데 필요한 값. + * + * FCM 호출은 트랜잭션 밖에서 이뤄지므로 엔티티 대신 이 값만 꺼내 넘긴다. + */ +data class PushDispatchTarget( + val outboxId: Long, + val receiverId: Long, + val studentId: String, + val fcmToken: String?, + val status: NotificationStatus, + val formatValues: List, +) diff --git a/src/main/kotlin/site/billilge/api/backend/domain/notification/entity/NotificationPushOutbox.kt b/src/main/kotlin/site/billilge/api/backend/domain/notification/entity/NotificationPushOutbox.kt new file mode 100644 index 0000000..ddb79f3 --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/domain/notification/entity/NotificationPushOutbox.kt @@ -0,0 +1,146 @@ +package site.billilge.api.backend.domain.notification.entity + +import jakarta.persistence.* +import org.hibernate.annotations.OnDelete +import org.hibernate.annotations.OnDeleteAction +import org.springframework.data.annotation.CreatedDate +import org.springframework.data.annotation.LastModifiedDate +import org.springframework.data.jpa.domain.support.AuditingEntityListener +import site.billilge.api.backend.domain.member.entity.Member +import site.billilge.api.backend.domain.notification.enums.PushDeliveryStatus +import java.time.Duration +import java.time.LocalDateTime + +/** + * 푸시 발송 대기열. + * + * 알림 저장과 같은 트랜잭션에서 수신자 수만큼 생성된다. 발송 실패 시 상태와 재시도 시각만 + * 갱신되므로 프로세스가 재시작돼도 발송 대상이 남는다. + * + * 메시지 본문은 저장하지 않는다 — 연결된 [Notification]의 status와 formatValues로 재구성한다. + */ +@Entity +@Table( + name = "notification_push_outbox", + indexes = [ + Index(name = "idx_push_outbox_delivery", columnList = "delivery_status, next_retry_at"), + Index(name = "idx_push_outbox_purge", columnList = "delivery_status, created_at"), + ] +) +@EntityListeners(AuditingEntityListener::class) +class NotificationPushOutbox( + @JoinColumn(name = "notification_id", nullable = false) + @ManyToOne(fetch = FetchType.LAZY) + @OnDelete(action = OnDeleteAction.CASCADE) + val notification: Notification, + + @JoinColumn(name = "receiver_id", nullable = false) + @ManyToOne(fetch = FetchType.LAZY) + @OnDelete(action = OnDeleteAction.CASCADE) + val receiver: Member, +) { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "notification_push_outbox_id", nullable = false) + val id: Long? = null + + @Enumerated(EnumType.STRING) + @Column(name = "delivery_status", nullable = false) + var deliveryStatus: PushDeliveryStatus = PushDeliveryStatus.PENDING + protected set + + @Column(name = "retry_count", nullable = false) + var retryCount: Int = 0 + protected set + + /** + * 폴러는 이 시각이 지난 건만 집어간다. + * + * 생성 직후에는 이벤트 핸들러가 즉시 1회 발송을 시도하므로, 그 시도와 폴러가 겹쳐 + * 중복 발송되지 않도록 첫 대상 시각을 뒤로 미뤄 둔다. + */ + @Column(name = "next_retry_at", nullable = false) + var nextRetryAt: LocalDateTime = LocalDateTime.now().plus(FIRST_POLL_DELAY) + protected set + + @Column(name = "last_error", length = MAX_ERROR_LENGTH) + var lastError: String? = null + protected set + + @CreatedDate + @Column(name = "created_at", nullable = false, updatable = false) + var createdAt: LocalDateTime = LocalDateTime.now() + protected set + + @LastModifiedDate + @Column(name = "updated_at", nullable = false) + var updatedAt: LocalDateTime = LocalDateTime.now() + protected set + + fun markSent() { + deliveryStatus = PushDeliveryStatus.SENT + lastError = null + } + + /** 재시도해도 결과가 같은 실패 — 더 시도하지 않는다 */ + fun markFailed(reason: String) { + deliveryStatus = PushDeliveryStatus.FAILED + lastError = reason.take(MAX_ERROR_LENGTH) + } + + fun markExpired() { + deliveryStatus = PushDeliveryStatus.EXPIRED + } + + /** + * 재시도 가능한 실패를 기록하고 다음 시도 시각을 뒤로 민다. + * 재시도 횟수를 모두 썼거나 유효 시간이 지났으면 발송을 포기한다. + */ + fun recordRetryableFailure(reason: String, now: LocalDateTime = LocalDateTime.now()) { + lastError = reason.take(MAX_ERROR_LENGTH) + + if (isExpired(now)) { + markExpired() + return + } + + if (retryCount >= BACKOFF_SECONDS.size) { + deliveryStatus = PushDeliveryStatus.FAILED + return + } + + val nextAttemptAt = now.plusSeconds(BACKOFF_SECONDS[retryCount]) + + // 다음 시도 시각이 이미 유효 시간을 넘긴다면 기다릴 이유가 없다 + if (isExpired(nextAttemptAt)) { + markExpired() + return + } + + nextRetryAt = nextAttemptAt + retryCount++ + } + + fun isPending(): Boolean = deliveryStatus == PushDeliveryStatus.PENDING + + fun isExpired(now: LocalDateTime = LocalDateTime.now()): Boolean = + now.isAfter(createdAt.plus(TIME_TO_LIVE)) + + companion object { + /** 즉시 발송 시도와 폴러가 겹치지 않도록 두는 간격 */ + private val FIRST_POLL_DELAY: Duration = Duration.ofSeconds(60) + + /** + * 늦게 도착하는 푸시는 의미가 없으므로 10분까지만 재시도한다. + * + * 사용자 알림은 지금 과방에 갈지를 결정하는 정보고, 관리자 알림도 학생이 기다리는 + * 상태에서 처리해야 하는 일이라 둘 다 실시간성이 중요하다. + */ + private val TIME_TO_LIVE: Duration = Duration.ofMinutes(10) + + /** 재시도 간격(초) — 배열 길이가 곧 최대 재시도 횟수. 누적 7분 30초로 유효 시간 안에 들어온다 */ + private val BACKOFF_SECONDS = longArrayOf(30, 120, 300) + + private const val MAX_ERROR_LENGTH = 500 + } +} diff --git a/src/main/kotlin/site/billilge/api/backend/domain/notification/enums/PushDeliveryStatus.kt b/src/main/kotlin/site/billilge/api/backend/domain/notification/enums/PushDeliveryStatus.kt new file mode 100644 index 0000000..5d74ae6 --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/domain/notification/enums/PushDeliveryStatus.kt @@ -0,0 +1,15 @@ +package site.billilge.api.backend.domain.notification.enums + +enum class PushDeliveryStatus { + /** 발송 대기 — 폴러가 재시도 대상으로 집어간다 */ + PENDING, + + /** 발송 완료 */ + SENT, + + /** 재시도 횟수를 모두 썼거나 재시도해도 소용없는 실패 */ + FAILED, + + /** 유효 시간이 지나 발송을 포기함 — 늦게 도착하는 푸시는 의미가 없다 */ + EXPIRED, +} diff --git a/src/main/kotlin/site/billilge/api/backend/domain/notification/handler/NotificationEventHandler.kt b/src/main/kotlin/site/billilge/api/backend/domain/notification/handler/NotificationEventHandler.kt index 21fdd1c..8b6c62a 100644 --- a/src/main/kotlin/site/billilge/api/backend/domain/notification/handler/NotificationEventHandler.kt +++ b/src/main/kotlin/site/billilge/api/backend/domain/notification/handler/NotificationEventHandler.kt @@ -2,28 +2,34 @@ package site.billilge.api.backend.domain.notification.handler import org.springframework.scheduling.annotation.Async import org.springframework.stereotype.Component -import org.springframework.transaction.annotation.Propagation -import org.springframework.transaction.annotation.Transactional import org.springframework.transaction.event.TransactionPhase import org.springframework.transaction.event.TransactionalEventListener +import site.billilge.api.backend.domain.member.entity.Member import site.billilge.api.backend.domain.member.service.MemberService import site.billilge.api.backend.domain.notification.enums.NotificationStatus import site.billilge.api.backend.domain.notification.service.NotificationService +import site.billilge.api.backend.domain.notification.service.PushNotificationSender import site.billilge.api.backend.domain.rental.enums.RentalStatus import site.billilge.api.backend.domain.rental.event.* +/** + * 알림 저장(DB)과 푸시 발송(FCM)을 분리해 호출한다. + * + * 핸들러 자체에는 트랜잭션을 걸지 않는다. 알림 저장은 NotificationService의 짧은 트랜잭션에서 + * 즉시 커밋되고, 그 뒤 트랜잭션 밖에서 푸시를 보낸다. 푸시가 실패해도 저장된 알림은 남는다. + */ @Component class NotificationEventHandler( private val notificationService: NotificationService, + private val pushNotificationSender: PushNotificationSender, private val memberService: MemberService, ) { @Async - @Transactional(propagation = Propagation.REQUIRES_NEW) @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) fun handleRentalApplied(event: RentalAppliedEvent) { val member = memberService.findById(event.memberId) - notificationService.sendNotification( + notifyUser( member, NotificationStatus.USER_RENTAL_APPLY, listOf(event.itemName), @@ -31,7 +37,7 @@ class NotificationEventHandler( ) if (!event.isDevMode) { - notificationService.sendNotificationToAdmin( + notifyAdmins( NotificationStatus.ADMIN_RENTAL_APPLY, listOf( member.name, @@ -45,12 +51,11 @@ class NotificationEventHandler( } @Async - @Transactional(propagation = Propagation.REQUIRES_NEW) @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) fun handleRentalCancelled(event: RentalCancelledEvent) { val member = memberService.findById(event.memberId) - notificationService.sendNotificationToAdmin( + notifyAdmins( NotificationStatus.ADMIN_RENTAL_CANCEL, listOf(member.name, member.studentId, event.itemName), needPush = true, @@ -58,19 +63,18 @@ class NotificationEventHandler( } @Async - @Transactional(propagation = Propagation.REQUIRES_NEW) @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) fun handleReturnApplied(event: ReturnAppliedEvent) { val member = memberService.findById(event.memberId) - notificationService.sendNotification( + notifyUser( member, NotificationStatus.USER_RETURN_APPLY, listOf(event.itemName), needPush = true, ) - notificationService.sendNotificationToAdmin( + notifyAdmins( NotificationStatus.ADMIN_RETURN_APPLY, listOf(member.name, member.studentId, event.itemName), needPush = true, @@ -78,7 +82,6 @@ class NotificationEventHandler( } @Async - @Transactional(propagation = Propagation.REQUIRES_NEW) @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) fun handleRentalStatusChanged(event: RentalStatusChangedEvent) { val member = memberService.findById(event.memberId) @@ -91,6 +94,36 @@ class NotificationEventHandler( else -> return } - notificationService.sendNotification(member, notificationStatus, listOf(event.itemName), needPush) + notifyUser(member, notificationStatus, listOf(event.itemName), needPush) + } + + private fun notifyUser( + member: Member, + status: NotificationStatus, + formatValues: List, + needPush: Boolean, + ) { + val outboxIds = notificationService.createNotification( + member, + status, + formatValues, + pushReceivers = if (needPush) listOf(member) else emptyList(), + ) + + pushNotificationSender.dispatch(outboxIds) + } + + private fun notifyAdmins( + status: NotificationStatus, + formatValues: List, + needPush: Boolean, + ) { + val outboxIds = notificationService.createAdminNotification( + status, + formatValues, + pushReceivers = if (needPush) memberService.findAllWorkers() else emptyList(), + ) + + pushNotificationSender.dispatch(outboxIds) } } diff --git a/src/main/kotlin/site/billilge/api/backend/domain/notification/repository/NotificationPushOutboxRepository.kt b/src/main/kotlin/site/billilge/api/backend/domain/notification/repository/NotificationPushOutboxRepository.kt new file mode 100644 index 0000000..c335bc8 --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/domain/notification/repository/NotificationPushOutboxRepository.kt @@ -0,0 +1,36 @@ +package site.billilge.api.backend.domain.notification.repository + +import org.springframework.data.domain.Pageable +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.data.jpa.repository.Query +import site.billilge.api.backend.domain.notification.entity.NotificationPushOutbox +import site.billilge.api.backend.domain.notification.enums.PushDeliveryStatus +import java.time.LocalDateTime + +interface NotificationPushOutboxRepository : JpaRepository { + @Query( + """ + SELECT o.id FROM NotificationPushOutbox o + WHERE o.deliveryStatus = :deliveryStatus AND o.nextRetryAt <= :now + ORDER BY o.nextRetryAt ASC + """ + ) + fun findDispatchTargetIds( + deliveryStatus: PushDeliveryStatus, + now: LocalDateTime, + pageable: Pageable + ): List + + /** 정렬하지 않는다 — 보존 기간이 지난 건을 모두 지우므로 삭제 순서는 중요하지 않다 */ + @Query( + """ + SELECT o.id FROM NotificationPushOutbox o + WHERE o.deliveryStatus IN :deliveryStatuses AND o.createdAt < :createdBefore + """ + ) + fun findPurgeTargetIds( + deliveryStatuses: Collection, + createdBefore: LocalDateTime, + pageable: Pageable + ): List +} diff --git a/src/main/kotlin/site/billilge/api/backend/domain/notification/scheduler/PushOutboxPurgeScheduler.kt b/src/main/kotlin/site/billilge/api/backend/domain/notification/scheduler/PushOutboxPurgeScheduler.kt new file mode 100644 index 0000000..5d86c7d --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/domain/notification/scheduler/PushOutboxPurgeScheduler.kt @@ -0,0 +1,71 @@ +package site.billilge.api.backend.domain.notification.scheduler + +import io.github.oshai.kotlinlogging.KotlinLogging +import org.springframework.scheduling.annotation.Scheduled +import org.springframework.stereotype.Component +import site.billilge.api.backend.domain.notification.enums.PushDeliveryStatus +import site.billilge.api.backend.domain.notification.service.NotificationPushOutboxService +import java.time.LocalDateTime + +private val log = KotlinLogging.logger {} + +/** + * 보존 기간이 지난 발송 대기열을 정리한다. + * + * 발송이 끝난 건은 폴러가 다시 조회하지 않지만, 알림 한 건마다 수신자 수만큼 쌓이므로 + * 방치하면 재시도 대상 조회가 느려진다. + * + * 재시도 폴러와 같은 스케줄러 스레드를 쓰므로, 한 회 처리량에 상한을 두어 폴러가 밀리지 않게 한다. + */ +@Component +class PushOutboxPurgeScheduler( + private val notificationPushOutboxService: NotificationPushOutboxService, +) { + @Scheduled(cron = "\${notification.push.outbox.purge-cron:0 0 4 * * *}", zone = "Asia/Seoul") + fun purgeExpiredOutbox() { + val now = LocalDateTime.now() + + val sentCount = purge(SENT_STATUSES, now.minusDays(SENT_RETENTION_DAYS)) + val givenUpCount = purge(GIVEN_UP_STATUSES, now.minusDays(GIVEN_UP_RETENTION_DAYS)) + + if (sentCount == 0 && givenUpCount == 0) return + + log.info { "푸시 아웃박스 정리 완료 (발송 완료 ${sentCount}건, 발송 포기 ${givenUpCount}건 삭제)" } + } + + private fun purge(deliveryStatuses: List, createdBefore: LocalDateTime): Int { + var deletedCount = 0 + + repeat(MAX_BATCHES_PER_RUN) { + val deleted = notificationPushOutboxService.deletePurgeTargetBatch( + deliveryStatuses, + createdBefore, + BATCH_SIZE + ) + + deletedCount += deleted + + if (deleted < BATCH_SIZE) return deletedCount + } + + log.warn { + "정리 대상이 한 회 처리량(${MAX_BATCHES_PER_RUN * BATCH_SIZE}건)을 채웠습니다. " + + "남은 건은 다음 주기에 정리됩니다. statuses=$deliveryStatuses" + } + + return deletedCount + } + + companion object { + private val SENT_STATUSES = listOf(PushDeliveryStatus.SENT) + + /** 실패 원인(last_error)을 들여다볼 여지를 남기기 위해 더 오래 보관한다 */ + private val GIVEN_UP_STATUSES = listOf(PushDeliveryStatus.FAILED, PushDeliveryStatus.EXPIRED) + + private const val SENT_RETENTION_DAYS = 7L + private const val GIVEN_UP_RETENTION_DAYS = 30L + + private const val BATCH_SIZE = 500 + private const val MAX_BATCHES_PER_RUN = 20 + } +} diff --git a/src/main/kotlin/site/billilge/api/backend/domain/notification/scheduler/PushRetryScheduler.kt b/src/main/kotlin/site/billilge/api/backend/domain/notification/scheduler/PushRetryScheduler.kt new file mode 100644 index 0000000..0b500af --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/domain/notification/scheduler/PushRetryScheduler.kt @@ -0,0 +1,44 @@ +package site.billilge.api.backend.domain.notification.scheduler + +import io.github.oshai.kotlinlogging.KotlinLogging +import org.springframework.scheduling.annotation.Scheduled +import org.springframework.stereotype.Component +import site.billilge.api.backend.domain.notification.service.NotificationPushOutboxService +import site.billilge.api.backend.domain.notification.service.PushNotificationSender +import site.billilge.api.backend.global.external.fcm.PushResult + +private val log = KotlinLogging.logger {} + +/** + * 발송되지 못한 푸시를 주기적으로 재시도한다. + * + * fixedDelay라 이전 주기가 끝난 뒤에 다음 주기가 시작된다 — 발송이 밀려도 중복 실행되지 않는다. + */ +@Component +class PushRetryScheduler( + private val notificationPushOutboxService: NotificationPushOutboxService, + private val pushNotificationSender: PushNotificationSender, +) { + @Scheduled( + initialDelayString = "\${notification.push.retry.initial-delay-ms:60000}", + fixedDelayString = "\${notification.push.retry.poll-interval-ms:30000}", + ) + fun retryFailedPushes() { + val targetIds = notificationPushOutboxService.findRetryTargetIds(BATCH_SIZE) + + if (targetIds.isEmpty()) return + + val results = pushNotificationSender.dispatch(targetIds) + val sentCount = results.count { result -> result == PushResult.Success } + + log.info { "푸시 재시도 ${results.size}건 처리 (성공 $sentCount, 실패 ${results.size - sentCount})" } + + if (targetIds.size == BATCH_SIZE) { + log.warn { "재시도 대상이 한 주기 처리량(${BATCH_SIZE}건)을 채웠습니다. 남은 건은 다음 주기에 처리됩니다." } + } + } + + companion object { + private const val BATCH_SIZE = 100 + } +} diff --git a/src/main/kotlin/site/billilge/api/backend/domain/notification/service/NotificationPushOutboxService.kt b/src/main/kotlin/site/billilge/api/backend/domain/notification/service/NotificationPushOutboxService.kt new file mode 100644 index 0000000..ffde208 --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/domain/notification/service/NotificationPushOutboxService.kt @@ -0,0 +1,128 @@ +package site.billilge.api.backend.domain.notification.service + +import io.github.oshai.kotlinlogging.KotlinLogging +import org.springframework.data.domain.PageRequest +import org.springframework.data.repository.findByIdOrNull +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import site.billilge.api.backend.domain.member.entity.Member +import site.billilge.api.backend.domain.notification.dto.PushDispatchTarget +import site.billilge.api.backend.domain.notification.entity.Notification +import site.billilge.api.backend.domain.notification.entity.NotificationPushOutbox +import site.billilge.api.backend.domain.notification.enums.PushDeliveryStatus +import site.billilge.api.backend.domain.notification.repository.NotificationPushOutboxRepository +import site.billilge.api.backend.global.external.fcm.PushResult +import java.time.LocalDateTime + +private val log = KotlinLogging.logger {} + +@Service +@Transactional(readOnly = true) +class NotificationPushOutboxService( + private val notificationPushOutboxRepository: NotificationPushOutboxRepository, +) { + /** + * 발송 대기열에 수신자 수만큼 등록한다. + * + * 알림 저장 트랜잭션에 참여하므로, 알림과 발송 대상은 함께 저장되거나 함께 롤백된다. + */ + @Transactional + fun register(notification: Notification, receivers: List): List { + return receivers + .filter { receiver -> receiver.hasFcmToken() } + .map { receiver -> + notificationPushOutboxRepository.save(NotificationPushOutbox(notification, receiver)).id!! + } + } + + fun findRetryTargetIds(limit: Int): List { + return notificationPushOutboxRepository.findDispatchTargetIds( + PushDeliveryStatus.PENDING, + LocalDateTime.now(), + PageRequest.of(0, limit) + ) + } + + /** + * 발송에 필요한 값을 꺼내 온다. 이미 처리됐거나 유효 시간이 지난 건은 null을 반환한다. + */ + @Transactional + fun findDispatchTarget(outboxId: Long): PushDispatchTarget? { + val outbox = notificationPushOutboxRepository.findByIdOrNull(outboxId) ?: return null + + if (!outbox.isPending()) return null + + if (outbox.isExpired()) { + outbox.markExpired() + log.warn { "(outboxId=$outboxId) 유효 시간이 지나 푸시 발송을 포기합니다." } + return null + } + + val receiver = outbox.receiver + val notification = outbox.notification + + return PushDispatchTarget( + outboxId = outboxId, + receiverId = receiver.id!!, + studentId = receiver.studentId, + fcmToken = receiver.fcmToken, + status = notification.status, + formatValues = notification.formatValueList, + ) + } + + @Transactional + fun applyResult(outboxId: Long, result: PushResult) { + val outbox = notificationPushOutboxRepository.findByIdOrNull(outboxId) ?: return + + when (result) { + PushResult.Success -> outbox.markSent() + PushResult.InvalidToken -> outbox.markFailed(INVALID_TOKEN_REASON) + is PushResult.Permanent -> outbox.markFailed(result.reason) + is PushResult.Retryable -> outbox.recordRetryableFailure(result.reason) + } + + if (outbox.deliveryStatus == PushDeliveryStatus.FAILED || outbox.deliveryStatus == PushDeliveryStatus.EXPIRED) { + log.error { + "(outboxId=$outboxId) 푸시 발송을 포기합니다. " + + "status=${outbox.deliveryStatus}, retryCount=${outbox.retryCount}, reason=${outbox.lastError}" + } + } + } + + /** + * 보존 기간이 지난 건을 배치 크기만큼 삭제하고 삭제한 수를 반환한다. + * + * 한 번에 다 지우면 락 구간이 길어지므로, 호출부가 반환값을 보고 반복 호출한다. + * 배치마다 트랜잭션이 끊기도록 이 메서드가 트랜잭션 경계를 잡는다. + */ + @Transactional + fun deletePurgeTargetBatch( + deliveryStatuses: Collection, + createdBefore: LocalDateTime, + batchSize: Int, + ): Int { + val targetIds = notificationPushOutboxRepository.findPurgeTargetIds( + deliveryStatuses, + createdBefore, + PageRequest.of(0, batchSize) + ) + + if (targetIds.isEmpty()) return 0 + + notificationPushOutboxRepository.deleteAllByIdInBatch(targetIds) + + return targetIds.size + } + + private fun Member.hasFcmToken(): Boolean { + if (fcmToken != null) return true + + log.warn { "(studentId=$studentId) FCM Token is null" } + return false + } + + companion object { + private const val INVALID_TOKEN_REASON = "INVALID_TOKEN" + } +} diff --git a/src/main/kotlin/site/billilge/api/backend/domain/notification/service/NotificationService.kt b/src/main/kotlin/site/billilge/api/backend/domain/notification/service/NotificationService.kt index 74896cf..ab8683c 100644 --- a/src/main/kotlin/site/billilge/api/backend/domain/notification/service/NotificationService.kt +++ b/src/main/kotlin/site/billilge/api/backend/domain/notification/service/NotificationService.kt @@ -1,26 +1,19 @@ package site.billilge.api.backend.domain.notification.service -import io.github.oshai.kotlinlogging.KotlinLogging import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import site.billilge.api.backend.domain.member.entity.Member -import site.billilge.api.backend.domain.member.enums.Role -import site.billilge.api.backend.domain.member.service.MemberService import site.billilge.api.backend.domain.notification.entity.Notification import site.billilge.api.backend.domain.notification.enums.NotificationStatus import site.billilge.api.backend.domain.notification.exception.NotificationErrorCode import site.billilge.api.backend.domain.notification.repository.NotificationRepository import site.billilge.api.backend.global.exception.ApiException -import site.billilge.api.backend.global.external.fcm.FCMService - -private val log = KotlinLogging.logger {} @Service @Transactional(readOnly = true) class NotificationService( private val notificationRepository: NotificationRepository, - private val fcmService: FCMService, - private val memberService: MemberService, + private val notificationPushOutboxService: NotificationPushOutboxService, ) { fun getNotifications(memberId: Long?): List { return notificationRepository.findAllUserNotificationsByMemberId(memberId!!) @@ -44,71 +37,44 @@ class NotificationService( return notificationRepository.findAllAdminNotificationsByMemberId(memberId!!) } + /** + * 알림을 저장하고 푸시 발송 대상을 대기열에 등록한다. 등록된 아웃박스 ID를 반환한다. + * + * 알림과 발송 대상이 하나의 트랜잭션에서 저장되므로, 커밋된 이후에는 발송이 누락되더라도 + * 대기열에 남아 재시도된다. + */ @Transactional - fun sendNotification( - member: Member, - status: NotificationStatus, - formatValues: List, - needPush: Boolean = false, - ) { - val notification = Notification( - member = member, - status = status, - formatValues = formatValues.joinToString(",") - ) - - notificationRepository.save(notification) - - if (needPush) { - sendPushNotification(member, status, formatValues) - } - } - - private fun sendPushNotification( + fun createNotification( member: Member, status: NotificationStatus, formatValues: List, - ) { - val studentId = member.studentId - - if (member.fcmToken == null) { - log.warn { "(studentId=${studentId}) FCM Token is null" } - return - } - - val isTokenValid = fcmService.sendPushNotification( - member.fcmToken!!, - status.title, - status.formattedMessage(*formatValues.toTypedArray()), - status.link, - studentId + pushReceivers: List = emptyList(), + ): List { + val notification = notificationRepository.save( + Notification( + member = member, + status = status, + formatValues = formatValues.joinToString(",") + ) ) - if (!isTokenValid) { - memberService.clearFcmToken(member.id!!) - } + return notificationPushOutboxService.register(notification, pushReceivers) } @Transactional - fun sendNotificationToAdmin( - type: NotificationStatus, + fun createAdminNotification( + status: NotificationStatus, formatValues: List, - needPush: Boolean = false - ) { - val admins = memberService.findAllWorkers() - - val notification = Notification( - status = type, - formatValues = formatValues.joinToString(",") + pushReceivers: List = emptyList(), + ): List { + val notification = notificationRepository.save( + Notification( + status = status, + formatValues = formatValues.joinToString(",") + ) ) - notificationRepository.save(notification) - - if (needPush) { - admins.forEach { admin -> - sendPushNotification(admin, type, formatValues) - } - } + return notificationPushOutboxService.register(notification, pushReceivers) } fun getNotificationCount(memberId: Long?): Int { diff --git a/src/main/kotlin/site/billilge/api/backend/domain/notification/service/PushNotificationSender.kt b/src/main/kotlin/site/billilge/api/backend/domain/notification/service/PushNotificationSender.kt new file mode 100644 index 0000000..1ed1223 --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/domain/notification/service/PushNotificationSender.kt @@ -0,0 +1,68 @@ +package site.billilge.api.backend.domain.notification.service + +import io.github.oshai.kotlinlogging.KotlinLogging +import org.springframework.stereotype.Component +import site.billilge.api.backend.domain.member.service.MemberService +import site.billilge.api.backend.domain.notification.dto.PushDispatchTarget +import site.billilge.api.backend.global.external.fcm.FCMService +import site.billilge.api.backend.global.external.fcm.PushResult + +private val log = KotlinLogging.logger {} + +/** + * 아웃박스에 등록된 푸시를 발송한다. + * + * 알림 저장 트랜잭션 바깥에서 호출된다. 네트워크 I/O가 DB 커넥션을 붙잡지 않도록 + * @Transactional을 걸지 않으며, 발송 실패를 예외로 전파하지 않는다. + * 한 수신자의 실패가 다른 수신자에게 영향을 주면 안 되기 때문이다. + * + * 알림 발생 직후의 즉시 발송과 [PushRetryScheduler]의 재시도가 이 경로를 공유한다. + */ +@Component +class PushNotificationSender( + private val fcmService: FCMService, + private val memberService: MemberService, + private val notificationPushOutboxService: NotificationPushOutboxService, +) { + fun dispatch(outboxIds: List): List { + return outboxIds.mapNotNull { outboxId -> dispatchOne(outboxId) } + } + + /** 이미 처리됐거나 유효 시간이 지난 건은 건너뛰고 null을 반환한다 */ + private fun dispatchOne(outboxId: Long): PushResult? { + val target = notificationPushOutboxService.findDispatchTarget(outboxId) ?: return null + + val result = send(target) + + notificationPushOutboxService.applyResult(outboxId, result) + + if (result == PushResult.InvalidToken) { + memberService.clearFcmToken(target.receiverId) + } + + return result + } + + private fun send(target: PushDispatchTarget): PushResult { + val fcmToken = target.fcmToken + ?: return PushResult.Permanent(TOKEN_NOT_REGISTERED_REASON) + + return try { + fcmService.sendPushNotification( + fcmToken, + target.status.title, + target.status.formattedMessage(*target.formatValues.toTypedArray()), + target.status.link, + target.studentId + ) + } catch (e: Exception) { + // 메시지 포맷 인자 개수 불일치 등 발송 이전 단계에서 발생하는 오류 + log.error(e) { "(studentId=${target.studentId}) 푸시 메시지 생성 실패: ${e.message}" } + PushResult.Permanent(e.javaClass.simpleName) + } + } + + companion object { + private const val TOKEN_NOT_REGISTERED_REASON = "FCM_TOKEN_NOT_REGISTERED" + } +} diff --git a/src/main/kotlin/site/billilge/api/backend/domain/payer/entity/Payer.kt b/src/main/kotlin/site/billilge/api/backend/domain/payer/entity/Payer.kt index 8198a1d..c0f7220 100644 --- a/src/main/kotlin/site/billilge/api/backend/domain/payer/entity/Payer.kt +++ b/src/main/kotlin/site/billilge/api/backend/domain/payer/entity/Payer.kt @@ -5,7 +5,7 @@ import jakarta.persistence.* @Entity @Table( name = "payer", - indexes = [Index(name = "idx_payer_name_enrollment_year", columnList = "name, enrollment_year")] + indexes = [Index(name = "idx_payer_enrollment_year_name", columnList = "enrollment_year DESC, name")] ) class Payer( @Column(nullable = false) diff --git a/src/main/kotlin/site/billilge/api/backend/domain/payer/repository/PayerRepository.kt b/src/main/kotlin/site/billilge/api/backend/domain/payer/repository/PayerRepository.kt index 091cdd8..114cc80 100644 --- a/src/main/kotlin/site/billilge/api/backend/domain/payer/repository/PayerRepository.kt +++ b/src/main/kotlin/site/billilge/api/backend/domain/payer/repository/PayerRepository.kt @@ -13,7 +13,9 @@ interface PayerRepository : JpaRepository { @Query("select p from Payer p where p.id in :ids") fun findAllByIds(@Param("ids") ids: List): List - @Query("SELECT p FROM Payer p WHERE p.name LIKE CONCAT('%', :name, '%') ORDER BY p.enrollmentYear DESC, p.name") + // 정렬은 Pageable의 Sort에만 맡긴다. 여기에 ORDER BY를 같이 두면 Spring Data가 + // Sort를 지우지 않고 뒤에 이어붙여 정렬 키가 중복된다. (PayerService.resolveSort 참고) + @Query("SELECT p FROM Payer p WHERE p.name LIKE CONCAT('%', :name, '%')") fun findAllByNameContaining(@Param("name") name: String, pageable: Pageable): Page fun findAllByEnrollmentYear(enrollmentYear: String): List diff --git a/src/main/kotlin/site/billilge/api/backend/domain/payer/service/PayerService.kt b/src/main/kotlin/site/billilge/api/backend/domain/payer/service/PayerService.kt index 9e3d767..e475bf4 100644 --- a/src/main/kotlin/site/billilge/api/backend/domain/payer/service/PayerService.kt +++ b/src/main/kotlin/site/billilge/api/backend/domain/payer/service/PayerService.kt @@ -65,10 +65,42 @@ class PayerService( val pageRequest = PageRequest.of( pageableCondition.pageNo, pageableCondition.size, - Sort.by(Sort.Direction.DESC, pageableCondition.criteria ?: "enrollmentYear") - .and(Sort.by(Sort.Direction.ASC, "id")) + resolveSort(pageableCondition.criteria) + ) + val search = searchCondition.search + + // 검색어가 없으면 LIKE '%%'는 한 건도 걸러내지 못하면서 선행 와일드카드 때문에 + // 인덱스 접근만 막는다. 목록 첫 진입이 이 경로이므로 술어 자체를 빼서 + // 정렬 인덱스를 타고 LIMIT에서 끊게 한다. + if (search.isBlank()) { + return payerRepository.findAll(pageRequest) + } + + return payerRepository.findAllByNameContaining(search, pageRequest) + } + + /** + * 납부자 목록의 정렬 기준을 만드는 유일한 지점. + * + * 기본 정렬은 `idx_payer_enrollment_year_name(enrollment_year DESC, name)` 의 순서와 맞춘다. + * InnoDB 보조 인덱스는 뒤에 PK가 붙으므로 `id ASC` 까지 인덱스 순서로 읽을 수 있고, + * 정렬 키가 인덱스와 어긋나면 조건에 걸린 전체 행을 filesort 하게 된다. + * + * criteria는 클라이언트가 넘기는 값이라 화이트리스트로 받는다. 선언형 @Query에는 + * 프로퍼티명이 검증 없이 그대로 붙어서, 없는 이름이 들어오면 쿼리 자체가 깨진다. + */ + private fun resolveSort(criteria: String?): Sort = when (criteria) { + "name" -> Sort.by( + Sort.Order.asc("name"), + Sort.Order.desc("enrollmentYear"), + Sort.Order.asc("id") + ) + + else -> Sort.by( + Sort.Order.desc("enrollmentYear"), + Sort.Order.asc("name"), + Sort.Order.asc("id") ) - return payerRepository.findAllByNameContaining(searchCondition.search, pageRequest) } @Transactional diff --git a/src/main/kotlin/site/billilge/api/backend/global/config/AsyncConfig.kt b/src/main/kotlin/site/billilge/api/backend/global/config/AsyncConfig.kt index 71b0bd9..96887a5 100644 --- a/src/main/kotlin/site/billilge/api/backend/global/config/AsyncConfig.kt +++ b/src/main/kotlin/site/billilge/api/backend/global/config/AsyncConfig.kt @@ -1,9 +1,54 @@ package site.billilge.api.backend.global.config +import io.github.oshai.kotlinlogging.KotlinLogging +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler +import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration +import org.springframework.scheduling.annotation.AsyncConfigurer import org.springframework.scheduling.annotation.EnableAsync +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor +import java.util.concurrent.Executor +import java.util.concurrent.ThreadPoolExecutor + +private val log = KotlinLogging.logger {} @EnableAsync @Configuration -class AsyncConfig { -} \ No newline at end of file +class AsyncConfig : AsyncConfigurer { + /** + * 알림 발송 전용 실행기. + * + * 자동 설정 실행기(applicationTaskExecutor)는 큐가 무제한이라 FCM이 지연되면 태스크가 + * 계속 쌓이고, 종료 대기 설정이 없어 배포 시 큐에 남은 알림이 유실된다. + */ + @Bean + fun notificationTaskExecutor(): ThreadPoolTaskExecutor = ThreadPoolTaskExecutor().apply { + corePoolSize = CORE_POOL_SIZE + maxPoolSize = MAX_POOL_SIZE + setQueueCapacity(QUEUE_CAPACITY) + setThreadNamePrefix("notification-") + + // 큐가 가득 차면 버리는 대신 호출 스레드에서 실행한다 — 유실보다 지연을 택한다 + setRejectedExecutionHandler(ThreadPoolExecutor.CallerRunsPolicy()) + + // 종료 시 큐에 남은 알림을 처리할 시간을 준다 + setWaitForTasksToCompleteOnShutdown(true) + setAwaitTerminationSeconds(AWAIT_TERMINATION_SECONDS) + } + + override fun getAsyncExecutor(): Executor = notificationTaskExecutor() + + override fun getAsyncUncaughtExceptionHandler(): AsyncUncaughtExceptionHandler = + AsyncUncaughtExceptionHandler { ex, method, params -> + log.error(ex) { + "비동기 작업 실패: ${method.declaringClass.simpleName}.${method.name}(${params.joinToString()})" + } + } + + companion object { + private const val CORE_POOL_SIZE = 4 + private const val MAX_POOL_SIZE = 8 + private const val QUEUE_CAPACITY = 500 + private const val AWAIT_TERMINATION_SECONDS = 20 + } +} diff --git a/src/main/kotlin/site/billilge/api/backend/global/config/SchedulingConfig.kt b/src/main/kotlin/site/billilge/api/backend/global/config/SchedulingConfig.kt new file mode 100644 index 0000000..52ccf38 --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/global/config/SchedulingConfig.kt @@ -0,0 +1,14 @@ +package site.billilge.api.backend.global.config + +import org.springframework.context.annotation.Configuration +import org.springframework.scheduling.annotation.EnableScheduling + +/** + * 스케줄러는 단일 스레드에서 순차 실행된다. + * + * 인스턴스를 여러 대로 늘리면 같은 발송 건을 동시에 집어갈 수 있으므로, + * 그때는 조회에 잠금(FOR UPDATE SKIP LOCKED)이나 ShedLock이 필요하다. + */ +@EnableScheduling +@Configuration +class SchedulingConfig diff --git a/src/main/kotlin/site/billilge/api/backend/global/external/fcm/FCMService.kt b/src/main/kotlin/site/billilge/api/backend/global/external/fcm/FCMService.kt index 8e70895..1539c10 100644 --- a/src/main/kotlin/site/billilge/api/backend/global/external/fcm/FCMService.kt +++ b/src/main/kotlin/site/billilge/api/backend/global/external/fcm/FCMService.kt @@ -8,7 +8,13 @@ import site.billilge.api.backend.global.logging.log class FCMService( private val firebaseMessaging: FirebaseMessaging, ) { - fun sendPushNotification(fcmToken: String, title: String, body: String, link: String, studentId: String = "20000000"): Boolean { + fun sendPushNotification( + fcmToken: String, + title: String, + body: String, + link: String, + studentId: String = "20000000" + ): PushResult { val fcmMessage = Message.builder() .putData("title", title) .putData("body", body.replace("\n", " ")) @@ -24,15 +30,44 @@ class FCMService( return try { firebaseMessaging.send(fcmMessage) log.info { "(studentId=$studentId) FCM Message sent." } - true + PushResult.Success } catch (e: FirebaseMessagingException) { - if (e.messagingErrorCode == MessagingErrorCode.UNREGISTERED) { - log.warn { "(studentId=$studentId) FCM token is unregistered. Clearing token." } - false - } else { - log.error { "(studentId=$studentId) FCM send failed: ${e.message}" } - true + resolveFailure(e, studentId) + } catch (e: Exception) { + // 자격 증명 갱신 실패 등 SDK가 FirebaseMessagingException으로 감싸지 않는 오류 + log.error(e) { "(studentId=$studentId) FCM send failed: ${e.message}" } + PushResult.Retryable(e.javaClass.simpleName) + } + } + + private fun resolveFailure(e: FirebaseMessagingException, studentId: String): PushResult { + val errorCode = e.messagingErrorCode + + return when (errorCode) { + MessagingErrorCode.UNREGISTERED, MessagingErrorCode.SENDER_ID_MISMATCH -> { + log.warn { "(studentId=$studentId) FCM token is no longer valid($errorCode). Clearing token." } + PushResult.InvalidToken + } + + MessagingErrorCode.UNAVAILABLE, + MessagingErrorCode.INTERNAL, + MessagingErrorCode.QUOTA_EXCEEDED, + MessagingErrorCode.THIRD_PARTY_AUTH_ERROR -> { + log.error { "(studentId=$studentId) FCM send failed temporarily($errorCode): ${e.message}" } + PushResult.Retryable(errorCode.name) + } + + // 에러 코드가 없는 경우는 전송 계층 오류에 가까우므로 재시도 대상으로 둔다 + null -> { + log.error { "(studentId=$studentId) FCM send failed without error code: ${e.message}" } + PushResult.Retryable(e.javaClass.simpleName) + } + + // INVALID_ARGUMENT는 토큰 문제일 수도, 페이로드 문제일 수도 있어 토큰을 지우지 않는다 + else -> { + log.error { "(studentId=$studentId) FCM send failed permanently($errorCode): ${e.message}" } + PushResult.Permanent(errorCode.name) } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/site/billilge/api/backend/global/external/fcm/PushResult.kt b/src/main/kotlin/site/billilge/api/backend/global/external/fcm/PushResult.kt new file mode 100644 index 0000000..da425a0 --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/global/external/fcm/PushResult.kt @@ -0,0 +1,20 @@ +package site.billilge.api.backend.global.external.fcm + +/** + * FCM 푸시 발송 결과. + * + * 호출부가 "재시도해야 하는 실패"와 "재시도해도 소용없는 실패"를 구분할 수 있도록 + * 실패를 세 종류로 나눈다. + */ +sealed interface PushResult { + data object Success : PushResult + + /** 토큰이 더 이상 유효하지 않음 — 재시도 대신 토큰을 제거해야 한다 */ + data object InvalidToken : PushResult + + /** FCM 일시 장애·네트워크 오류 — 동일한 요청으로 재시도할 수 있다 */ + data class Retryable(val reason: String) : PushResult + + /** 페이로드 오류 등 재시도해도 결과가 같은 실패 */ + data class Permanent(val reason: String) : PushResult +} diff --git a/src/main/kotlin/site/billilge/api/backend/global/external/minio/MinioConfig.kt b/src/main/kotlin/site/billilge/api/backend/global/external/minio/MinioConfig.kt deleted file mode 100644 index c18ce8f..0000000 --- a/src/main/kotlin/site/billilge/api/backend/global/external/minio/MinioConfig.kt +++ /dev/null @@ -1,27 +0,0 @@ -package site.billilge.api.backend.global.external.minio - -import io.minio.MinioClient -import org.springframework.beans.factory.annotation.Value -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration - -@Configuration -class MinioConfig( - @Value("\${minio.endpoint}") - private val endpoint: String, - - @Value("\${minio.access-key}") - private val accessKey: String, - - @Value("\${minio.secret-key}") - private val secretKey: String, -) { - - @Bean - fun minioClient(): MinioClient { - return MinioClient.builder() - .endpoint(endpoint) - .credentials(accessKey, secretKey) - .build() - } -} diff --git a/src/main/kotlin/site/billilge/api/backend/global/external/minio/MinioService.kt b/src/main/kotlin/site/billilge/api/backend/global/external/minio/MinioService.kt deleted file mode 100644 index c8f2bd4..0000000 --- a/src/main/kotlin/site/billilge/api/backend/global/external/minio/MinioService.kt +++ /dev/null @@ -1,73 +0,0 @@ -package site.billilge.api.backend.global.external.minio - -import io.minio.MinioClient -import io.minio.PutObjectArgs -import io.minio.RemoveObjectArgs -import io.minio.StatObjectArgs -import io.minio.errors.ErrorResponseException -import org.springframework.beans.factory.annotation.Value -import org.springframework.stereotype.Service -import org.springframework.web.multipart.MultipartFile -import site.billilge.api.backend.global.exception.ApiException -import site.billilge.api.backend.global.exception.GlobalErrorCode -import site.billilge.api.backend.global.external.FileStorageService -import java.io.IOException -import java.util.* - -@Service -class MinioService( - private val minioClient: MinioClient, - @Value("\${minio.bucket}") - private val bucket: String, - @Value("\${minio.base-url}") - private val baseUrl: String, -) : FileStorageService { - - override fun uploadImageFile(imageFile: MultipartFile, newFileName: String): String? { - val originalName = imageFile.originalFilename ?: return null - - val ext = originalName.substring(originalName.lastIndexOf(".")) - val changedName = newFileName + ext - - try { - minioClient.putObject( - PutObjectArgs.builder() - .bucket(bucket) - .`object`(changedName) - .stream(imageFile.inputStream, imageFile.size, -1) - .contentType(imageFile.contentType) - .build() - ) - } catch (e: IOException) { - throw ApiException(GlobalErrorCode.IMAGE_UPLOAD_FAILED, e) - } - - return "${baseUrl}/${bucket}/${changedName}" - } - - override fun deleteImageFile(fileName: String) { - val imageKey = fileName.replace("${baseUrl}/${bucket}/", "") - - try { - minioClient.statObject( - StatObjectArgs.builder() - .bucket(bucket) - .`object`(imageKey) - .build() - ) - } catch (e: ErrorResponseException) { - throw ApiException(GlobalErrorCode.IMAGE_NOT_FOUND) - } - - try { - minioClient.removeObject( - RemoveObjectArgs.builder() - .bucket(bucket) - .`object`(imageKey) - .build() - ) - } catch (e: IOException) { - throw ApiException(GlobalErrorCode.IMAGE_DELETE_FAILED, e) - } - } -} diff --git a/src/main/kotlin/site/billilge/api/backend/global/external/r2/R2Config.kt b/src/main/kotlin/site/billilge/api/backend/global/external/r2/R2Config.kt new file mode 100644 index 0000000..af00d9b --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/global/external/r2/R2Config.kt @@ -0,0 +1,40 @@ +package site.billilge.api.backend.global.external.r2 + +import org.springframework.beans.factory.annotation.Value +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider +import software.amazon.awssdk.core.checksums.RequestChecksumCalculation +import software.amazon.awssdk.core.checksums.ResponseChecksumValidation +import software.amazon.awssdk.regions.Region +import software.amazon.awssdk.services.s3.S3Client +import java.net.URI + +@Configuration +class R2Config( + @Value("\${r2.endpoint}") + private val endpoint: String, + + @Value("\${r2.access-key}") + private val accessKey: String, + + @Value("\${r2.secret-key}") + private val secretKey: String, +) { + + @Bean + fun r2Client(): S3Client { + return S3Client.builder() + .endpointOverride(URI.create(endpoint)) + .region(Region.of("auto")) + .credentialsProvider( + StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey)) + ) + .forcePathStyle(true) + // R2는 AWS SDK 기본값(모든 요청에 CRC 체크섬 부착)을 완전히 지원하지 않으므로 필요한 경우에만 계산 + .requestChecksumCalculation(RequestChecksumCalculation.WHEN_REQUIRED) + .responseChecksumValidation(ResponseChecksumValidation.WHEN_REQUIRED) + .build() + } +} diff --git a/src/main/kotlin/site/billilge/api/backend/global/external/r2/R2Service.kt b/src/main/kotlin/site/billilge/api/backend/global/external/r2/R2Service.kt new file mode 100644 index 0000000..1619506 --- /dev/null +++ b/src/main/kotlin/site/billilge/api/backend/global/external/r2/R2Service.kt @@ -0,0 +1,83 @@ +package site.billilge.api.backend.global.external.r2 + +import org.springframework.beans.factory.annotation.Value +import org.springframework.stereotype.Service +import org.springframework.web.multipart.MultipartFile +import site.billilge.api.backend.global.exception.ApiException +import site.billilge.api.backend.global.exception.GlobalErrorCode +import site.billilge.api.backend.global.external.FileStorageService +import software.amazon.awssdk.core.exception.SdkException +import software.amazon.awssdk.core.sync.RequestBody +import software.amazon.awssdk.services.s3.S3Client +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest +import software.amazon.awssdk.services.s3.model.HeadObjectRequest +import software.amazon.awssdk.services.s3.model.PutObjectRequest +import software.amazon.awssdk.services.s3.model.S3Exception +import java.io.IOException + +@Service +class R2Service( + private val r2Client: S3Client, + @Value("\${r2.bucket}") + private val bucket: String, + @Value("\${r2.public-url}") + publicUrl: String, +) : FileStorageService { + + // R2 공개 URL(r2.dev 또는 커스텀 도메인)은 버킷에 직접 연결되므로 경로에 버킷명이 들어가지 않는다 + private val publicUrl = publicUrl.trimEnd('/') + + override fun uploadImageFile(imageFile: MultipartFile, newFileName: String): String? { + val originalName = imageFile.originalFilename ?: return null + + val ext = originalName.substring(originalName.lastIndexOf(".")) + val key = newFileName + ext + + val request = PutObjectRequest.builder() + .bucket(bucket) + .key(key) + .contentType(imageFile.contentType) + .build() + + try { + imageFile.inputStream.use { + r2Client.putObject(request, RequestBody.fromInputStream(it, imageFile.size)) + } + } catch (e: IOException) { + throw ApiException(GlobalErrorCode.IMAGE_UPLOAD_FAILED, e) + } catch (e: SdkException) { + throw ApiException(GlobalErrorCode.IMAGE_UPLOAD_FAILED, e) + } + + return "$publicUrl/$key" + } + + override fun deleteImageFile(fileName: String) { + val key = fileName.removePrefix("$publicUrl/") + + try { + r2Client.headObject( + HeadObjectRequest.builder() + .bucket(bucket) + .key(key) + .build() + ) + } catch (e: S3Exception) { + if (e.statusCode() == 404) throw ApiException(GlobalErrorCode.IMAGE_NOT_FOUND) + throw ApiException(GlobalErrorCode.IMAGE_DELETE_FAILED, e) + } catch (e: SdkException) { + throw ApiException(GlobalErrorCode.IMAGE_DELETE_FAILED, e) + } + + try { + r2Client.deleteObject( + DeleteObjectRequest.builder() + .bucket(bucket) + .key(key) + .build() + ) + } catch (e: SdkException) { + throw ApiException(GlobalErrorCode.IMAGE_DELETE_FAILED, e) + } + } +} diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml index b8698da..ee52c14 100644 --- a/src/main/resources/application-dev.yml +++ b/src/main/resources/application-dev.yml @@ -7,6 +7,15 @@ spring: driver-class-name: com.mysql.cj.jdbc.Driver username: ${DB_USERNAME} password: ${DB_PASSWORD} + hikari: + pool-name: BillilgeHikariCP + maximum-pool-size: 15 + minimum-idle: 15 + connection-timeout: 3000 + validation-timeout: 2000 + idle-timeout: 600000 + max-lifetime: 1740000 + keepalive-time: 300000 security: oauth2: @@ -23,10 +32,14 @@ spring: jpa: properties: hibernate: - format_sql: true + # show-sql 과 함께만 의미가 있고, 켜면 쿼리마다 포매팅 비용이 붙는다 + format_sql: false dialect: org.hibernate.dialect.MySQLDialect dialect.storage_engine: innodb - show-sql: true + # show-sql 은 로거를 거치지 않고 System.out 에 직접 쓴다. + # 레벨로 끌 수도, 비동기 appender 로 돌릴 수도 없고 요청 스레드들이 출력 락에서 직렬화된다. + # SQL 을 봐야 할 때는 아래 logging.level 을 debug 로 올린다 (로거 경로라 제어가 된다). + show-sql: false hibernate: ddl-auto: update @@ -37,6 +50,23 @@ spring: resolve-lazily: true +logging: + level: + org.hibernate.SQL: info # debug 로 올리면 실행 SQL 출력 + org.hibernate.orm.jdbc.bind: info # trace 로 올리면 바인딩 파라미터까지 출력 + + +server: + tomcat: + threads: + max: 100 + min-spare: 20 + accept-count: 100 + max-connections: 2000 + connection-timeout: 5000ms + shutdown: graceful + + jwt: secret_key: ${JWT_SECRET_KEY} issuer: ${JWT_ISSUER} @@ -47,12 +77,12 @@ login: cors: allowed-origins: ${CORS_ALLOWED_ORIGINS} -minio: - endpoint: ${MINIO_ENDPOINT} - access-key: ${MINIO_ACCESS_KEY} - secret-key: ${MINIO_SECRET_KEY} - bucket: ${MINIO_BUCKET} - base-url: ${MINIO_BASE_URL} +r2: + endpoint: ${R2_ENDPOINT} + access-key: ${R2_ACCESS_KEY} + secret-key: ${R2_SECRET_KEY} + bucket: ${R2_BUCKET} + public-url: ${R2_PUBLIC_URL} swagger: server: diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml index 30e482e..ac013fe 100644 --- a/src/main/resources/application-prod.yml +++ b/src/main/resources/application-prod.yml @@ -7,6 +7,17 @@ spring: driver-class-name: com.mysql.cj.jdbc.Driver username: ${DB_USERNAME} password: ${DB_PASSWORD} + hikari: + pool-name: BillilgeHikariCP + # 동접 100 기준: 요청당 DB 점유 시간이 짧아(수십 ms) 커넥션은 적게 유지하는 편이 큐잉/컨텍스트 스위칭에 유리 + # 웹 요청 + @Async 알림 처리(기본 태스크 풀 8) 여유분까지 포함해 15 + maximum-pool-size: 15 + minimum-idle: 15 # 풀 크기 고정 (증감 시 커넥션 생성 지연 방지) + connection-timeout: 3000 # 풀 고갈 시 30초 대기 대신 3초 내 fail-fast + validation-timeout: 2000 + idle-timeout: 600000 + max-lifetime: 1740000 # 29분. MySQL wait_timeout보다 짧게 유지 + keepalive-time: 300000 security: oauth2: @@ -36,6 +47,17 @@ spring: resolve-lazily: true +server: + tomcat: + threads: + max: 100 # 동접 100을 동시에 수용. 초과분은 accept-count 큐에서 대기 + min-spare: 20 # 트래픽 유입 시 스레드 생성 지연 완화 + accept-count: 100 + max-connections: 2000 + connection-timeout: 5000ms + shutdown: graceful + + jwt: secret_key: ${JWT_SECRET_KEY} issuer: ${JWT_ISSUER} @@ -46,12 +68,12 @@ login: cors: allowed-origins: ${CORS_ALLOWED_ORIGINS} -minio: - endpoint: ${MINIO_ENDPOINT} - access-key: ${MINIO_ACCESS_KEY} - secret-key: ${MINIO_SECRET_KEY} - bucket: ${MINIO_BUCKET} - base-url: ${MINIO_BASE_URL} +r2: + endpoint: ${R2_ENDPOINT} + access-key: ${R2_ACCESS_KEY} + secret-key: ${R2_SECRET_KEY} + bucket: ${R2_BUCKET} + public-url: ${R2_PUBLIC_URL} swagger: server: diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..284ec42 --- /dev/null +++ b/src/main/resources/logback-spring.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + true + + + 0 + + + 4096 + + + false + + + + + + diff --git a/src/test/kotlin/site/billilge/api/backend/domain/notification/entity/NotificationPushOutboxTest.kt b/src/test/kotlin/site/billilge/api/backend/domain/notification/entity/NotificationPushOutboxTest.kt new file mode 100644 index 0000000..c55f160 --- /dev/null +++ b/src/test/kotlin/site/billilge/api/backend/domain/notification/entity/NotificationPushOutboxTest.kt @@ -0,0 +1,126 @@ +package site.billilge.api.backend.domain.notification.entity + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test +import site.billilge.api.backend.domain.member.entity.Member +import site.billilge.api.backend.domain.notification.enums.NotificationStatus +import site.billilge.api.backend.domain.notification.enums.PushDeliveryStatus +import java.time.LocalDateTime + +class NotificationPushOutboxTest { + @Test + @DisplayName("생성 직후에는 즉시 발송 시도와 겹치지 않도록 폴러 대상 시각이 뒤로 밀려 있다") + fun `첫 폴링 시각은 생성 시각보다 뒤에 있다`() { + val outbox = createOutbox() + + assertTrue(outbox.nextRetryAt.isAfter(outbox.createdAt)) + assertEquals(PushDeliveryStatus.PENDING, outbox.deliveryStatus) + assertEquals(0, outbox.retryCount) + } + + @Test + @DisplayName("재시도 가능한 실패는 정해진 간격만큼 다음 시도를 미룬다") + fun `백오프 간격이 점점 늘어난다`() { + val outbox = createOutbox() + val now = LocalDateTime.now() + + val expectedBackoffSeconds = listOf(30L, 120L, 300L) + + expectedBackoffSeconds.forEachIndexed { index, seconds -> + outbox.recordRetryableFailure("UNAVAILABLE", now) + + assertEquals(now.plusSeconds(seconds), outbox.nextRetryAt) + assertEquals(index + 1, outbox.retryCount) + assertEquals(PushDeliveryStatus.PENDING, outbox.deliveryStatus) + } + } + + @Test + @DisplayName("재시도는 모두 유효 시간(10분) 안에서 이뤄진다") + fun `마지막 재시도 시각이 유효 시간을 넘지 않는다`() { + val outbox = createOutbox() + val now = LocalDateTime.now() + + repeat(3) { outbox.recordRetryableFailure("UNAVAILABLE", now) } + + assertFalse(outbox.isExpired(outbox.nextRetryAt)) + } + + @Test + @DisplayName("재시도 횟수를 모두 쓰면 발송을 포기한다") + fun `최대 재시도 횟수를 넘기면 FAILED가 된다`() { + val outbox = createOutbox() + val now = LocalDateTime.now() + + repeat(3) { outbox.recordRetryableFailure("UNAVAILABLE", now) } + assertEquals(PushDeliveryStatus.PENDING, outbox.deliveryStatus) + + outbox.recordRetryableFailure("UNAVAILABLE", now) + + assertEquals(PushDeliveryStatus.FAILED, outbox.deliveryStatus) + assertEquals("UNAVAILABLE", outbox.lastError) + } + + @Test + @DisplayName("유효 시간이 지나면 재시도 횟수가 남아 있어도 포기한다") + fun `TTL을 넘기면 EXPIRED가 된다`() { + val outbox = createOutbox() + + outbox.recordRetryableFailure("UNAVAILABLE", LocalDateTime.now().plusMinutes(11)) + + assertEquals(PushDeliveryStatus.EXPIRED, outbox.deliveryStatus) + assertEquals(0, outbox.retryCount) + } + + @Test + @DisplayName("다음 시도 시각이 이미 유효 시간을 넘기면 기다리지 않고 바로 포기한다") + fun `유효 시간을 넘길 재시도는 예약하지 않는다`() { + val outbox = createOutbox() + + // 유효 시간 10분을 40초 남긴 시점의 실패 — 다음 간격(30초)은 들어가지만 + outbox.recordRetryableFailure("UNAVAILABLE", LocalDateTime.now().plusMinutes(9).plusSeconds(20)) + assertEquals(PushDeliveryStatus.PENDING, outbox.deliveryStatus) + + // 20초 남은 시점의 실패 — 다음 간격(30초)이면 이미 만료다 + outbox.recordRetryableFailure("UNAVAILABLE", LocalDateTime.now().plusMinutes(9).plusSeconds(40)) + + assertEquals(PushDeliveryStatus.EXPIRED, outbox.deliveryStatus) + assertEquals(1, outbox.retryCount) + } + + @Test + @DisplayName("발송에 성공하면 직전 실패 기록을 지운다") + fun `markSent는 lastError를 비운다`() { + val outbox = createOutbox() + outbox.recordRetryableFailure("UNAVAILABLE", LocalDateTime.now()) + + outbox.markSent() + + assertEquals(PushDeliveryStatus.SENT, outbox.deliveryStatus) + assertEquals(null, outbox.lastError) + } + + @Test + @DisplayName("처리가 끝난 건은 다시 발송 대상이 되지 않는다") + fun `SENT 상태는 isPending이 false다`() { + val outbox = createOutbox() + + outbox.markSent() + + assertFalse(outbox.isPending()) + } + + private fun createOutbox(): NotificationPushOutbox { + val member = Member(name = "김국민", studentId = "20240001") + val notification = Notification( + member = member, + status = NotificationStatus.USER_RENTAL_APPROVED, + formatValues = "우산" + ) + + return NotificationPushOutbox(notification, member) + } +}