Repository navigation
[FEAT] 기존 문서 참조 backfill 및 검증 기능 구현 #207
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
0272b14
feat: 크루 문서 식별자 keyset 페이지 조회 추가
sun007021 33f7faa
feat: 문서별 독립 transaction 참조 backfill 처리 구현
sun007021 55e1f61
feat: 문서 참조 backfill orchestration과 결과 집계 구현
sun007021 65bfcc5
test: 문서 참조 backfill 페이지 경계·실패 격리·멱등성 테스트 추가
sun007021 9a6054a
refactor: 실효성 없는 참조 불일치 검증과 지표 제거
sun007021 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
9 changes: 9 additions & 0 deletions
9
src/main/java/com/wooteco/wiki/document/repository/CrewDocumentIdentifierReadModel.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| package com.wooteco.wiki.document.repository; | ||
|
|
||
| import java.util.UUID; | ||
|
|
||
| public record CrewDocumentIdentifierReadModel( | ||
| Long id, | ||
| UUID uuid | ||
| ) { | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 19 additions & 0 deletions
19
src/main/java/com/wooteco/wiki/graph/dto/DocumentReferenceBackfillFailure.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| package com.wooteco.wiki.graph.dto; | ||
|
|
||
| import java.util.UUID; | ||
|
|
||
| public record DocumentReferenceBackfillFailure( | ||
| UUID sourceDocumentUuid, | ||
| String causeType | ||
| ) { | ||
|
|
||
| public static DocumentReferenceBackfillFailure of( | ||
| UUID sourceDocumentUuid, | ||
| Throwable cause | ||
| ) { | ||
| return new DocumentReferenceBackfillFailure( | ||
| sourceDocumentUuid, | ||
| cause.getClass().getSimpleName() | ||
| ); | ||
| } | ||
| } |
23 changes: 23 additions & 0 deletions
23
src/main/java/com/wooteco/wiki/graph/dto/DocumentReferenceBackfillItemResult.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| package com.wooteco.wiki.graph.dto; | ||
|
|
||
| public record DocumentReferenceBackfillItemResult( | ||
| int addedCount, | ||
| int removedCount, | ||
| int excludedSelfCount, | ||
| int excludedMissingCount, | ||
| boolean mismatched | ||
| ) { | ||
|
|
||
| public static DocumentReferenceBackfillItemResult of( | ||
| DocumentReferenceSyncResult syncResult, | ||
| boolean mismatched | ||
| ) { | ||
| return new DocumentReferenceBackfillItemResult( | ||
| syncResult.addedCount(), | ||
| syncResult.removedCount(), | ||
| syncResult.excludedSelfCount(), | ||
| syncResult.excludedMissingCount(), | ||
| mismatched | ||
| ); | ||
| } | ||
| } |
53 changes: 53 additions & 0 deletions
53
src/main/java/com/wooteco/wiki/graph/dto/DocumentReferenceBackfillResult.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| package com.wooteco.wiki.graph.dto; | ||
|
|
||
| import java.util.List; | ||
| import java.util.function.ToIntFunction; | ||
|
|
||
| public record DocumentReferenceBackfillResult( | ||
| int processedCount, | ||
| int succeededCount, | ||
| int failedCount, | ||
| int addedCount, | ||
| int removedCount, | ||
| int excludedSelfCount, | ||
| int excludedMissingCount, | ||
| int mismatchCount, | ||
| List<DocumentReferenceBackfillFailure> failures | ||
| ) { | ||
|
|
||
| public DocumentReferenceBackfillResult { | ||
| failures = List.copyOf(failures); | ||
| } | ||
|
|
||
| public static DocumentReferenceBackfillResult of( | ||
| List<DocumentReferenceBackfillItemResult> itemResults, | ||
| List<DocumentReferenceBackfillFailure> failures | ||
| ) { | ||
| return new DocumentReferenceBackfillResult( | ||
| itemResults.size() + failures.size(), | ||
| itemResults.size(), | ||
| failures.size(), | ||
| sum(itemResults, DocumentReferenceBackfillItemResult::addedCount), | ||
| sum(itemResults, DocumentReferenceBackfillItemResult::removedCount), | ||
| sum(itemResults, DocumentReferenceBackfillItemResult::excludedSelfCount), | ||
| sum(itemResults, DocumentReferenceBackfillItemResult::excludedMissingCount), | ||
| countMismatched(itemResults), | ||
| failures | ||
| ); | ||
| } | ||
|
|
||
| private static int sum( | ||
| List<DocumentReferenceBackfillItemResult> itemResults, | ||
| ToIntFunction<DocumentReferenceBackfillItemResult> countExtractor | ||
| ) { | ||
| return itemResults.stream() | ||
| .mapToInt(countExtractor) | ||
| .sum(); | ||
| } | ||
|
|
||
| private static int countMismatched(List<DocumentReferenceBackfillItemResult> itemResults) { | ||
| return (int) itemResults.stream() | ||
| .filter(DocumentReferenceBackfillItemResult::mismatched) | ||
| .count(); | ||
| } | ||
| } |
29 changes: 29 additions & 0 deletions
29
src/main/java/com/wooteco/wiki/graph/service/DocumentReferenceBackfillAccumulator.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| package com.wooteco.wiki.graph.service; | ||
|
|
||
| import com.wooteco.wiki.graph.dto.DocumentReferenceBackfillFailure; | ||
| import com.wooteco.wiki.graph.dto.DocumentReferenceBackfillItemResult; | ||
| import com.wooteco.wiki.graph.dto.DocumentReferenceBackfillResult; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.UUID; | ||
|
|
||
| class DocumentReferenceBackfillAccumulator { | ||
|
|
||
| private final List<DocumentReferenceBackfillItemResult> itemResults = new ArrayList<>(); | ||
| private final List<DocumentReferenceBackfillFailure> failures = new ArrayList<>(); | ||
|
|
||
| void addSuccess(DocumentReferenceBackfillItemResult itemResult) { | ||
| itemResults.add(itemResult); | ||
| } | ||
|
|
||
| void addFailure( | ||
| UUID sourceDocumentUuid, | ||
| Throwable cause | ||
| ) { | ||
| failures.add(DocumentReferenceBackfillFailure.of(sourceDocumentUuid, cause)); | ||
| } | ||
|
|
||
| DocumentReferenceBackfillResult toResult() { | ||
| return DocumentReferenceBackfillResult.of(itemResults, failures); | ||
| } | ||
| } |
64 changes: 64 additions & 0 deletions
64
src/main/java/com/wooteco/wiki/graph/service/DocumentReferenceBackfillItemService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| package com.wooteco.wiki.graph.service; | ||
|
|
||
| import com.wooteco.wiki.document.domain.CrewDocument; | ||
| import com.wooteco.wiki.document.repository.CrewDocumentRepository; | ||
| import com.wooteco.wiki.global.exception.ErrorCode; | ||
| import com.wooteco.wiki.global.exception.WikiException; | ||
| import com.wooteco.wiki.graph.domain.DocumentReference; | ||
| import com.wooteco.wiki.graph.dto.DocumentReferenceBackfillItemResult; | ||
| import com.wooteco.wiki.graph.dto.DocumentReferenceSyncResult; | ||
| import com.wooteco.wiki.graph.repository.DocumentReferenceRepository; | ||
| import java.util.HashSet; | ||
| import java.util.List; | ||
| import java.util.Set; | ||
| import java.util.UUID; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.annotation.Propagation; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
|
|
||
| @RequiredArgsConstructor | ||
| @Service | ||
| public class DocumentReferenceBackfillItemService { | ||
|
|
||
| private final CrewDocumentRepository crewDocumentRepository; | ||
| private final DocumentReferenceSyncService documentReferenceSyncService; | ||
| private final DocumentReferenceRepository documentReferenceRepository; | ||
|
|
||
| // 문서 하나의 실패가 다른 문서 처리를 막지 않도록 문서마다 독립 transaction에서 동기화한다. | ||
| @Transactional(propagation = Propagation.REQUIRES_NEW) | ||
| public DocumentReferenceBackfillItemResult synchronize(UUID sourceDocumentUuid) { | ||
| CrewDocument sourceDocument = crewDocumentRepository.findByUuidForUpdate(sourceDocumentUuid) | ||
| .orElseThrow(() -> new WikiException(ErrorCode.DOCUMENT_NOT_FOUND)); | ||
| DocumentReferenceSyncResult syncResult = documentReferenceSyncService.synchronize(sourceDocument); | ||
| boolean mismatched = isMismatched(sourceDocument, syncResult.expectedTargetDocumentUuids()); | ||
| return DocumentReferenceBackfillItemResult.of(syncResult, mismatched); | ||
| } | ||
|
|
||
| // 저장 결과를 다시 읽어 현재 본문에서 기대한 target 집합과 같은지 검증한다. | ||
| private boolean isMismatched( | ||
| CrewDocument sourceDocument, | ||
| Set<UUID> expectedTargetDocumentUuids | ||
| ) { | ||
| Set<UUID> savedTargetDocumentUuids = findSavedTargetDocumentUuids(sourceDocument); | ||
| return !savedTargetDocumentUuids.equals(expectedTargetDocumentUuids); | ||
| } | ||
|
|
||
| private Set<UUID> findSavedTargetDocumentUuids(CrewDocument sourceDocument) { | ||
| List<DocumentReference> savedReferences = documentReferenceRepository.findAllBySourceDocument(sourceDocument); | ||
| Set<UUID> savedTargetDocumentUuids = new HashSet<>(); | ||
| for (DocumentReference savedReference : savedReferences) { | ||
| addTargetDocumentUuid(savedTargetDocumentUuids, savedReference); | ||
| } | ||
| return savedTargetDocumentUuids; | ||
| } | ||
|
|
||
| private void addTargetDocumentUuid( | ||
| Set<UUID> savedTargetDocumentUuids, | ||
| DocumentReference savedReference | ||
| ) { | ||
| UUID targetDocumentUuid = savedReference.getTargetDocument() | ||
| .getUuid(); | ||
| savedTargetDocumentUuids.add(targetDocumentUuid); | ||
| } | ||
| } | ||
86 changes: 86 additions & 0 deletions
86
src/main/java/com/wooteco/wiki/graph/service/DocumentReferenceBackfillService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| package com.wooteco.wiki.graph.service; | ||
|
|
||
| import com.wooteco.wiki.document.repository.CrewDocumentIdentifierReadModel; | ||
| import com.wooteco.wiki.document.repository.CrewDocumentRepository; | ||
| import com.wooteco.wiki.global.exception.ErrorCode; | ||
| import com.wooteco.wiki.global.exception.WikiException; | ||
| import com.wooteco.wiki.graph.dto.DocumentReferenceBackfillResult; | ||
| import java.util.List; | ||
| import java.util.UUID; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.data.domain.PageRequest; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| @Slf4j | ||
| @RequiredArgsConstructor | ||
| @Service | ||
| public class DocumentReferenceBackfillService { | ||
|
|
||
| private static final int DEFAULT_PAGE_SIZE = 100; | ||
| private static final long FIRST_DOCUMENT_ID_CURSOR = 0L; | ||
|
|
||
| private final CrewDocumentRepository crewDocumentRepository; | ||
| private final DocumentReferenceBackfillItemService documentReferenceBackfillItemService; | ||
|
|
||
| public DocumentReferenceBackfillResult backfill() { | ||
| return backfill(DEFAULT_PAGE_SIZE); | ||
| } | ||
|
|
||
| // 문서별 transaction proxy가 적용되도록 orchestration은 transaction 없이 item service를 호출한다. | ||
| public DocumentReferenceBackfillResult backfill(int pageSize) { | ||
| validatePageSize(pageSize); | ||
| DocumentReferenceBackfillAccumulator accumulator = new DocumentReferenceBackfillAccumulator(); | ||
| long lastDocumentId = FIRST_DOCUMENT_ID_CURSOR; | ||
| List<CrewDocumentIdentifierReadModel> identifiers = findNextIdentifiers(lastDocumentId, pageSize); | ||
| while (!identifiers.isEmpty()) { | ||
| accumulatePage(accumulator, identifiers); | ||
| lastDocumentId = findLastDocumentId(identifiers); | ||
| identifiers = findNextIdentifiers(lastDocumentId, pageSize); | ||
| } | ||
| return accumulator.toResult(); | ||
| } | ||
|
|
||
| private void validatePageSize(int pageSize) { | ||
| if (pageSize <= 0) { | ||
| throw new WikiException(ErrorCode.PAGE_BAD_REQUEST); | ||
| } | ||
| } | ||
|
|
||
| private List<CrewDocumentIdentifierReadModel> findNextIdentifiers( | ||
| long lastDocumentId, | ||
| int pageSize | ||
| ) { | ||
| return crewDocumentRepository.findIdentifiersAfterId(lastDocumentId, PageRequest.ofSize(pageSize)); | ||
| } | ||
|
|
||
| private void accumulatePage( | ||
| DocumentReferenceBackfillAccumulator accumulator, | ||
| List<CrewDocumentIdentifierReadModel> identifiers | ||
| ) { | ||
| for (CrewDocumentIdentifierReadModel identifier : identifiers) { | ||
| accumulateOne(accumulator, identifier.uuid()); | ||
| } | ||
| } | ||
|
|
||
| private void accumulateOne( | ||
| DocumentReferenceBackfillAccumulator accumulator, | ||
| UUID sourceDocumentUuid | ||
| ) { | ||
| try { | ||
| accumulator.addSuccess(documentReferenceBackfillItemService.synchronize(sourceDocumentUuid)); | ||
| } catch (RuntimeException exception) { | ||
| log.warn( | ||
| "문서 참조 backfill 처리에 실패했습니다. sourceDocumentUuid={}, causeType={}", | ||
| sourceDocumentUuid, | ||
| exception.getClass().getSimpleName() | ||
| ); | ||
| accumulator.addFailure(sourceDocumentUuid, exception); | ||
| } | ||
| } | ||
|
|
||
| private long findLastDocumentId(List<CrewDocumentIdentifierReadModel> identifiers) { | ||
| CrewDocumentIdentifierReadModel lastIdentifier = identifiers.get(identifiers.size() - 1); | ||
| return lastIdentifier.id(); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
현재는 참조 불일치가 발생해도 성공으로 커밋됩니다.
불일치 시 해당 문서의 트랜잭션만 롤백하고 실패로 집계하면 좋을 것 같습니다. 관련 테스트도 추가해주세요!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
확인해보니 지적하신 것보다 더 근본적인 문제가 있었습니다. 결론부터 말씀드리면 불일치가 발생할 수 있는 경로 자체가 없어서, 롤백을 붙여도 실행되지 않는 방어 코드가 됩니다. 그래서 검증 로직과
mismatchCount지표를 제거하는 쪽으로 반영했습니다.왜 항상 일치하는가
DocumentReferenceSyncService의 diff 계산이 이렇습니다.referencesToRemove=existing중 target이expected에 없는 것referencesToAdd=expected중existing에 없는 것따라서 동기화 후 집합 =
(existing ∩ expected) ∪ (expected \ existing)= 정확히expected입니다.그런데 제
isMismatched는 이걸 다시 읽어서syncResult.expectedTargetDocumentUuids(), 즉 같은expected와 비교하고 있었습니다. 정의상 항상 같습니다.나머지 경로도 막혀 있습니다.
deleteAll/saveAll이 실패하면 불일치가 아니라 예외가 나서 이미 해당 문서 transaction이 롤백됩니다.uk_document_reference_source_target제약이 막습니다.findByUuidForUpdate의 X-lock으로 직렬화됩니다.즉
mismatchCount: 0은 "검증 통과"가 아니라 "측정한 적 없음" 이었습니다. 이 지표를 남긴 채 머지하면 나중에 운영자가 0을 보고 검증됐다고 오독할 위험이 있어서, 롤백을 붙이는 것보다 지표를 걷어내는 쪽이 안전하다고 판단했습니다.그럼 검증은 무엇으로 하는가
재실행 자체가 커밋 후 검증입니다.
2차 backfill은 새 transaction에서 DB의
existing을 다시 읽어 본문에서 계산한expected와 diff합니다. 따라서이 성립합니다. 같은 transaction 안에서 자기가 방금 쓴 값을 되읽던 기존 방식과 달리, 커밋된 실제 DB 상태를 별도 transaction에서 확인하는 것이라 훨씬 강한 검증입니다.
backfill_success_bySecondExecution이 이미 이걸 검증하고 있고, 운영 절차도 "backfill을 두 번 실행해 2차의 added/removed가 0인지 확인"으로 정리하면 됩니다.요청하신 불일치 테스트를 작성하려다 작성이 불가능하다는 걸 발견한 게 이 판단의 출발점이었습니다. 짚어주셔서 감사합니다. 덕분에 의미 없는 지표를 머지 전에 걷어냈습니다.
다르게 보시는 부분 있으면 말씀해주세요.