Skip to content

[FEATURE] 워터마크 재처리 스케줄러 추가#120

Merged
Jong0128 merged 11 commits into
devfrom
feat/#116-watermark-scheduler
Jul 16, 2026
Merged

[FEATURE] 워터마크 재처리 스케줄러 추가#120
Jong0128 merged 11 commits into
devfrom
feat/#116-watermark-scheduler

Conversation

@Jong0128

@Jong0128 Jong0128 commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator

🚀 Related issue

Closes #116

#️⃣ Summary

  • 비동기 워터마크 처리가 실패했거나 중간에 멈춘(PROCESSING) 파일을 주기적으로 재처리하는 스케줄러를 추가했습니다.

🔧 Changes

  • WatermarkRetryScheduler — 10분 주기로 미완료 워터마크 재처리
  • CommissionDraftFile — 재시도 카운트(watermarkRetryCount) 및 워터마크 상태 전이 메서드 추가
  • findWatermarkRetryTargetIds + claimForRetry — 재처리 대상을 원자적으로 선점(PROCESSING 전이 + 카운트 증가)해 중복 큐잉 방지
  • 한 틱당 처리량 배치 상한(BATCH_SIZE = 20) 적용

📸 Test Evidence

💬 Reviewer Notes

  • 중복 큐잉 방지: 단순 조회 후 재큐잉하면 아직 큐에서 대기 중인 파일을 다음 스케줄 틱이 다시 잡을 수 있습니다. claimForRetry 벌크 UPDATE로 대상을 PROCESSING으로 선점하며 updatedAt을 갱신해 다음 틱의 재선정을 차단했습니다.
  • 무한 재시도 방지: 카운트 증가를 실패 시점이 아니라 선점(claim) 시점으로 옮겨, fail()에 도달하지 못하고 멈춘(hang) 파일도 재시도 한도(MAX_WATERMARK_RETRY = 3)에 걸려 종료되도록 했습니다.

Summary by CodeRabbit

  • 새 기능

    • 워터마크 생성 방식을 로고 기반에서 반복 텍스트 패턴으로 개선했습니다.
    • 워터마크 처리 실패 파일을 자동으로 재시도하며, 10분마다 정체된 작업을 점검합니다.
    • 재시도 횟수는 최대 3회로 제한되며, 초과 시 영구 실패로 처리됩니다.
    • 이미지 오류를 보다 명확한 유형으로 구분해 처리합니다.
  • 버그 수정

    • 처리 중 멈춘 워터마크 작업이 자동으로 재처리되도록 개선했습니다.
    • 읽을 수 없거나 해상도가 초과된 이미지의 오류 처리를 일관화했습니다.

@Jong0128 Jong0128 self-assigned this Jul 11, 2026
@Jong0128
Jong0128 requested a review from fervovita as a code owner July 11, 2026 16:52
@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Jong0128, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 47 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: 4c96714c-d979-41bf-a545-41db14002f10

📥 Commits

Reviewing files that changed from the base of the PR and between e3ff14f and 9b3f0f2.

📒 Files selected for processing (1)
  • src/main/resources/db/migration/V260716013618__add_watermark_retry_count.sql
📝 Walkthrough

Walkthrough

드래프트 파일에 TTF 텍스트 워터마크 생성과 이미지 처리 예외 타입이 추가됐다. 워터마크 실패 횟수와 상태 전이를 저장하며, 실패·정체 파일을 10분마다 조회해 선점 후 비동기로 재처리한다.

Changes

워터마크 처리 파이프라인

Layer / File(s) Summary
이미지 처리 및 비동기 워터마크 생성
src/main/java/ditda/backend/global/image/..., src/main/java/ditda/backend/domain/commission/draft/service/DraftWatermarkService.java, src/test/java/ditda/backend/global/image/WatermarkImageProcessorTest.java
로고 기반 처리가 TTF 텍스트 타일 렌더링으로 변경됐고, 이미지 처리 전용 예외와 비동기 워터마크 생성 흐름이 추가됐다.
워터마크 상태 전이 및 재시도 횟수 저장
src/main/java/ditda/backend/domain/commission/draft/entity/CommissionDraftFile.java, src/main/java/ditda/backend/domain/commission/draft/service/DraftWatermarkTransitionService.java, src/main/resources/db/migration/V260716013618__add_watermark_retry_count.sql
재시도 상한과 카운터를 엔터티 및 데이터베이스에 추가하고, 완료·실패·영구 실패·재시도 선점 전이를 구현했다.
미완료 파일 재처리 스케줄링
src/main/java/ditda/backend/domain/commission/draft/repository/CommissionDraftFileRepository.java, src/main/java/ditda/backend/domain/commission/draft/service/WatermarkRetryService.java, src/main/java/ditda/backend/domain/commission/draft/scheduler/WatermarkRetryScheduler.java
실패 및 30분 이상 정체된 처리 파일을 배치 조회하고, 재시도 횟수를 증가시키며 선점한 파일을 비동기로 재처리하도록 구성했다.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

Suggested reviewers: fervovita

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning 재처리 스케줄러와 무관한 워터마크 렌더링 방식, 이미지 에러 코드, 예외 구조 변경이 포함되어 있습니다. 재처리 관련 변경과 워터마크 렌더링·예외 리팩터링을 분리해 별도 PR로 제출하세요.
Docstring Coverage ⚠️ Warning Docstring coverage is 43.59% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목이 워터마크 재처리 스케줄러 추가라는 핵심 변경을 정확히 요약합니다.
Linked Issues check ✅ Passed FAILED/PROCESSING 파일 조회, 10분 스케줄링, 원자적 선점, 최대 20건/3회 제한과 영구 실패 처리가 모두 반영되었습니다.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/#116-watermark-scheduler

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Base automatically changed from feat/#106-watermark to dev July 12, 2026 03:49

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/main/java/ditda/backend/global/config/WatermarkAsyncConfig.java (1)

14-21: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

워터마크 전용 executor에 큐 제한과 S3 타임아웃을 추가하세요.
DraftWatermarkService가 이 executor에서 S3 다운로드/업로드를 수행하므로, 단일 스레드 + 무제한 큐 상태에서는 S3 지연 시 작업이 계속 적재되고 이후 워터마크 처리도 막힙니다. WatermarkAsyncConfigsetQueueCapacity(...)로 상한을 두고, S3 클라이언트에도 connect/read/api timeout을 명시해 주세요.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/java/ditda/backend/global/config/WatermarkAsyncConfig.java` around
lines 14 - 21, Update the watermark executor configuration in
WatermarkAsyncConfig to set a finite queue capacity while preserving its
single-thread behavior, and configure the S3 client used by
DraftWatermarkService with explicit connect, read, and API timeouts. Reuse the
project’s existing timeout and queue-capacity conventions where available.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@src/main/java/ditda/backend/domain/commission/draft/service/WatermarkRetryService.java`:
- Around line 47-55: WatermarkRetryService.java:47-55의 claimForRetry 결과를 활용해 실제
선점된 파일 ID만 reprocessFile로 큐잉하도록 변경하고, 필요하면 선점 ID 목록 반환 또는 선점 후 재조회 방식을 적용하세요.
CommissionDraftFileRepository.java:48-62의 claimForRetry WHERE 조건은 completed 제외가
아니라 원본 상태가 FAILED이거나 PROCESSING이면서 updatedAt이 stuckBefore보다 이전인 경우만 허용하도록 수정해 이미
선점된 파일의 재선점을 차단하세요.
- Around line 28-58: Update WatermarkRetryService.retryIncompleteFiles and its
repository flow so PROCESSING files that have reached MAX_WATERMARK_RETRY are
also selected and transitioned to FAILED, rather than being excluded
indefinitely. Add a separate bulk state-transition path for these exhausted
stuck records, while preserving the existing retry claim and reprocess flow for
eligible files below the retry limit.

---

Nitpick comments:
In `@src/main/java/ditda/backend/global/config/WatermarkAsyncConfig.java`:
- Around line 14-21: Update the watermark executor configuration in
WatermarkAsyncConfig to set a finite queue capacity while preserving its
single-thread behavior, and configure the S3 client used by
DraftWatermarkService with explicit connect, read, and API timeouts. Reuse the
project’s existing timeout and queue-capacity conventions where available.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: 56eebd21-d7cb-410c-b7b9-38c0f22f8abc

📥 Commits

Reviewing files that changed from the base of the PR and between b55d711 and 5710098.

⛔ Files ignored due to path filters (1)
  • src/main/resources/images/watermark-logo.png is excluded by !**/*.png
📒 Files selected for processing (17)
  • src/main/java/ditda/backend/domain/commission/draft/entity/CommissionDraftFile.java
  • src/main/java/ditda/backend/domain/commission/draft/event/DraftFilesSubmittedEvent.java
  • src/main/java/ditda/backend/domain/commission/draft/facade/DesignerDraftFacade.java
  • src/main/java/ditda/backend/domain/commission/draft/listener/DraftWatermarkListener.java
  • src/main/java/ditda/backend/domain/commission/draft/repository/CommissionDraftFileRepository.java
  • src/main/java/ditda/backend/domain/commission/draft/scheduler/WatermarkRetryScheduler.java
  • src/main/java/ditda/backend/domain/commission/draft/service/DraftWatermarkService.java
  • src/main/java/ditda/backend/domain/commission/draft/service/DraftWatermarkTransitionService.java
  • src/main/java/ditda/backend/domain/commission/draft/service/WatermarkRetryService.java
  • src/main/java/ditda/backend/domain/commission/revision/facade/DesignerRevisionFacade.java
  • src/main/java/ditda/backend/global/config/WatermarkAsyncConfig.java
  • src/main/java/ditda/backend/global/image/WatermarkImageProcessor.java
  • src/main/java/ditda/backend/global/image/dto/WatermarkedImage.java
  • src/main/java/ditda/backend/global/image/exception/ImageErrorCode.java
  • src/main/java/ditda/backend/global/s3/manager/S3FileManager.java
  • src/test/java/ditda/backend/domain/commission/draft/service/DraftWatermarkServiceTest.java
  • src/test/java/ditda/backend/global/image/WatermarkImageProcessorTest.java

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/main/java/ditda/backend/global/image/WatermarkImageProcessor.java (1)

103-103: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

인덱스 색상 모델(Indexed Color) 이미지의 투명도 깨짐을 방지하기 위한 ARGB 변환

reader.read()로 읽어온 원본 이미지가 GIF나 8비트 PNG 등 인덱스 색상 모델(TYPE_BYTE_INDEXED)이거나 커스텀 색상 공간(TYPE_CUSTOM)인 경우, 이후 AlphaComposite으로 워터마크를 그릴 때 투명도가 제대로 적용되지 않거나 색상이 깨지는 현상이 발생할 수 있습니다.
원본 이미지의 포맷에 관계없이 워터마크가 일관된 품질로 렌더링되도록, 제한된 색상 모델을 가진 이미지는 ARGB 타입으로 변환 후 반환하는 것을 권장합니다.

♻️ ARGB 변환 로직 추가
-				return reader.read(0, param);
+				BufferedImage img = reader.read(0, param);
+
+				// 인덱스 색상 모델이거나 커스텀 색상인 경우 투명도 처리를 위해 ARGB로 변환
+				if (img.getType() == BufferedImage.TYPE_BYTE_INDEXED || 
+					img.getType() == BufferedImage.TYPE_BYTE_BINARY || 
+					img.getType() == BufferedImage.TYPE_CUSTOM) {
+					
+					BufferedImage argb = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
+					Graphics2D g = argb.createGraphics();
+					g.drawImage(img, 0, 0, null);
+					g.dispose();
+					return argb;
+				}
+				
+				return img;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/java/ditda/backend/global/image/WatermarkImageProcessor.java` at
line 103, Update the image-loading flow around reader.read(0, param) to convert
images with TYPE_BYTE_INDEXED or TYPE_CUSTOM color models into a TYPE_INT_ARGB
BufferedImage before returning them. Preserve already compatible image types
unchanged, and ensure the converted image retains the original dimensions and
rendered transparency.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/main/java/ditda/backend/global/image/WatermarkImageProcessor.java`:
- Line 103: Update the image-loading flow around reader.read(0, param) to
convert images with TYPE_BYTE_INDEXED or TYPE_CUSTOM color models into a
TYPE_INT_ARGB BufferedImage before returning them. Preserve already compatible
image types unchanged, and ensure the converted image retains the original
dimensions and rendered transparency.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: 04d85a7d-b637-4ea9-ba73-fe669a755f53

📥 Commits

Reviewing files that changed from the base of the PR and between 5710098 and 370ef8e.

⛔ Files ignored due to path filters (1)
  • src/main/resources/fonts/watermark-font.ttf is excluded by !**/*.ttf
📒 Files selected for processing (1)
  • src/main/java/ditda/backend/global/image/WatermarkImageProcessor.java

@Jong0128

Copy link
Copy Markdown
Collaborator Author

@fervovita
KakaoTalk_20260514_162541091_03
KakaoTalk_20260518_002646775_02
KakaoTalk_20260518_002646775_04
KakaoTalk_20260518_002646775_05
sample

기존 이미지 워터마크에서 폰트 (LINESeedSans_Bd) 로 수정했습니다! 이제 진짜 코드 리뷰해주시면 감사하겠습니다!!
많이 늦어져서 정말 죄송합니다 😢

@fervovita fervovita left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

수고하셨습니다!!
아래 코멘트 확인 부탁드려요😄

Comment thread src/main/resources/db/migration/V2__add_watermark_retry_count.sql Outdated
Comment thread src/main/resources/fonts/LINESeedSans_Bd.ttf

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@src/main/resources/db/migration/V260716013618__add_watermark_retry_count.sql`:
- Around line 11-12: Update the commission_draft_files migration to add
watermark_retry_count safely for existing rows: provide a temporary/default
value of 0 or add it nullable, backfill existing NULL values to 0, then enforce
the NOT NULL constraint. Ensure the completed column contains 0 for all
pre-existing records.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: 59ca113e-c6b5-4189-95d7-e400f8d81488

📥 Commits

Reviewing files that changed from the base of the PR and between 370ef8e and e3ff14f.

⛔ Files ignored due to path filters (1)
  • src/main/resources/fonts/LINESeedSans_Bd.ttf is excluded by !**/*.ttf
📒 Files selected for processing (10)
  • src/main/java/ditda/backend/domain/commission/draft/entity/CommissionDraftFile.java
  • src/main/java/ditda/backend/domain/commission/draft/repository/CommissionDraftFileRepository.java
  • src/main/java/ditda/backend/domain/commission/draft/service/DraftWatermarkService.java
  • src/main/java/ditda/backend/domain/commission/draft/service/DraftWatermarkTransitionService.java
  • src/main/java/ditda/backend/domain/commission/draft/service/WatermarkRetryService.java
  • src/main/java/ditda/backend/global/image/WatermarkImageProcessor.java
  • src/main/java/ditda/backend/global/image/exception/ImageErrorCode.java
  • src/main/java/ditda/backend/global/image/exception/ImageProcessingException.java
  • src/main/resources/db/migration/V260716013618__add_watermark_retry_count.sql
  • src/test/java/ditda/backend/global/image/WatermarkImageProcessorTest.java
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/java/ditda/backend/domain/commission/draft/service/WatermarkRetryService.java
  • src/test/java/ditda/backend/global/image/WatermarkImageProcessorTest.java
  • src/main/java/ditda/backend/global/image/WatermarkImageProcessor.java

Comment thread src/main/resources/db/migration/V260716013618__add_watermark_retry_count.sql Outdated
@Jong0128 Jong0128 mentioned this pull request Jul 16, 2026
5 tasks
@fervovita
fervovita self-requested a review July 16, 2026 05:16

@fervovita fervovita left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merge 하셔도 될 것 같습니다!!

@Jong0128
Jong0128 merged commit 311a683 into dev Jul 16, 2026
2 checks passed
@Jong0128
Jong0128 deleted the feat/#116-watermark-scheduler branch July 16, 2026 05:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] 워터마크 재처리 스케줄러 추가

2 participants