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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions docs/api/document-version-deletion.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# DocumentVersion 삭제 API

```http
DELETE /api/v1/workspaces/{workspaceId}/documents/{documentId}/versions/{documentVersionId}
```

로그인한 워크스페이스 멤버 중 해당 DocumentVersion의 업로더만 삭제할 수 있다. Document 생성자라도 다른 회원이 업로드한 버전은 삭제할 수 없다.

## 요청

- `workspaceId`, `documentId`, `documentVersionId`: 양수 Long 경로 변수
- 로그인 세션 쿠키와 유효한 CSRF 헤더 필요
- 요청 본문 없음
- 회원 ID나 S3 저장 키를 클라이언트에서 받지 않는다. 요청자는 로그인한 OidcUser의 issuer·subject로 조회한다.

## 성공 응답

```http
HTTP/1.1 204 No Content
Cache-Control: no-store
```

응답 본문은 없다. 204는 선택한 DocumentVersion과 관련 DB 데이터 삭제 및 S3ObjectDeletionTask 등록이 커밋되었다는 의미다. 실제 S3 파일 삭제 완료를 의미하지 않는다.

## 삭제 범위

- 선택한 DocumentVersion과 그 버전의 모든 DocumentFeedback
- 연결된 DocumentConversionJob과 DocumentUpload
- 원본·PDF의 StoreFile
- 원본·PDF의 저장 키를 S3ObjectDeletionTask에 등록

다른 DocumentVersion과 그 파일·피드백은 유지한다. 마지막 버전을 삭제해도 Document는 유지하며, 번호 발급을 위한 Document.revision은 감소하지 않는다. 같은 버전의 삭제를 다시 요청하면 404이며 S3ObjectDeletionTask를 중복 등록하지 않는다.

PDF 변환 대기·실패 버전도 삭제할 수 있다. PROCESSING 상태는 변환이 끝난 뒤 다시 삭제해야 한다.

## 오류

| 상태 | 조건 |
| --- | --- |
| 400 | 0·음수·숫자가 아닌 값·Long 범위 초과 경로 ID |
| 401 | 로그인하지 않은 요청(유효한 CSRF가 전달된 경우) |
| 403 | CSRF 누락·불일치, 워크스페이스 비멤버 또는 다른 업로더 |
| 404 | 없는 워크스페이스·Document·DocumentVersion, 요청 경로의 소속 관계 불일치 |
| 409 | PDF 변환 중, DocumentUpload·StoreFile 연결 불일치 또는 다른 버전의 파일 참조가 남아 있음 |

CSRF 검사는 인증 검사보다 먼저 실행될 수 있어 미로그인 요청도 CSRF가 없으면 403을 받을 수 있다. DB 삭제와 S3ObjectDeletionTask 등록 중 실패하면 같은 트랜잭션의 DB 변경을 모두 롤백하며 204를 반환하지 않는다.

## 삭제 이후 조회

- 목록과 최신 PDF 조회는 현재 남은 최대 DocumentVersion.versionNumber를 기준으로 한다.
- V3 삭제 후 V1·V2가 남으면 목록과 최신 PDF는 V2를 가리키며, 다음 업로드에는 V4가 발급된다.
- 남은 최신 버전의 PDF가 아직 준비되지 않으면 최신 PDF URL은 409이며 이전 완료 버전으로 대체하지 않는다.
- 모든 버전 삭제 후 목록에는 Document가 남고 revision=0, versionCount=0, conversionStatus=null이다. 히스토리는 빈 배열이며 최신 PDF URL은 409다.
- 삭제한 버전의 PDF·원본 URL 조회는 404다.

## S3 파일 정리

자동 정리를 실행하려면 `S3_OBJECT_DELETION_WORKER_ENABLED=true`로 Spring을 실행해야 한다. 최초 삭제 작업은 DocumentUpload.expiresAt 이후 실행하고, 실패한 파일은 재시도한다. 자세한 설정과 필요한 S3 권한·버전 관리 제약은 `docs/operations/s3-object-deletion.md`를 참고한다.

## 검증

`DocumentVersionDeletionApiTest`에서 로그인·CSRF·경로 검증·권한·204 응답·DB 삭제·작업 등록·변환 중 거부를 확인한다. `DocumentQueryAfterVersionDeletionApiTest`는 실제 DELETE API를 호출한 뒤 문서 목록·히스토리·PDF 조회 결과를 검증한다. 테스트에는 임시 MySQL DB와 모의 S3를 사용하며, 실제 파일 삭제와 브라우저 버튼은 검증하지 않는다.
11 changes: 11 additions & 0 deletions docs/api/document-version-history.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,14 @@ GET /api/v1/workspaces/{workspaceId}/documents/{documentId}/versions/{documentVe
- API 응답과 S3 GET 응답에 no-store를 적용한다. URL 기본 유효기간은 기존 설정과 같은 5분이다.
- 이미 발급된 URL은 유효기간 동안 사용될 수 있다. 새 URL 발급 시에는 매번 멤버십을 확인한다.
- 자동화 테스트에서는 임시 MySQL 스키마와 가짜 인증 정보로 검증한다. 실제 S3에 요청하거나 파일을 다운로드하지 않는다.

## 버전 삭제 이후 최신 버전 조회

- 문서 목록 API `GET /api/v1/workspaces/{workspaceId}/documents`의 `revision`은 현재 남은 `DocumentVersion.versionNumber`의 최댓값이다. 버전이 없으면 0이다.
- `versionCount`는 남은 DocumentVersion 행 수이며, `conversionStatus`는 현재 남은 최대 번호의 버전에 연결된 DocumentConversionJob 상태다. 연결된 작업이 없으면 null이다.
- `GET /api/v1/documents/{documentId}/pdf-url`도 현재 남은 최대 번호의 DocumentVersion을 조회한다. 그 버전의 PDF가 준비되지 않았으면 409이며, 더 낮은 번호의 완료 PDF를 대신 반환하지 않는다.
- V3을 삭제해 V1·V2가 남았다면 목록과 최신 PDF 조회는 V2를 가리킨다. 번호 발급에 사용하는 `Document.revision`은 3으로 유지하여 다음 업로드에는 V4를 발급한다.
- 마지막 버전까지 삭제해도 Document는 목록에 남는다. 응답은 revision=0, versionCount=0, conversionStatus=null이며 버전 히스토리는 빈 배열이다. 최신 PDF URL은 발급하지 않는다(409).
- 삭제한 DocumentVersion의 버전별 PDF·원본 URL 조회는 404다.

삭제 이후 조회 검증은 `DocumentQueryAfterVersionDeletionApiTest`에서 실제 DELETE API를 호출한 뒤 목록·최신 PDF·히스토리·버전별 URL 응답을 확인한다. S3 URL 생성은 모의 객체로 대체하며, 화면 버튼은 후속 커밋에서 연결한다. 삭제 API는 `docs/api/document-version-deletion.md`를 참고한다.
2 changes: 1 addition & 1 deletion docs/frontend/document-history-screen.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
워크스페이스 파일 화면에서 문서 목록을 먼저 표시하고, 화면 너비에 따라 두 열 또는 한 열 카드로 배치한다.

- 카드에 Document.title, 최신 버전 번호, 실제 DocumentVersion 개수, Document 생성 시각 및 최신 PDF 변환 상태를 표시한다.
- GET /api/v1/workspaces/{workspaceId}/documents 응답에 versionCount를 추가한다. revision은 버전 번호이며 versionCount와 다를 수 있다.
- GET /api/v1/workspaces/{workspaceId}/documents 응답에 versionCount를 추가한다. revision은 현재 남은 DocumentVersion의 최대 versionNumber(없으면 0)이며 versionCount와 다를 수 있다. 번호 발급을 위한 Document.revision은 삭제해도 줄이지 않는다.
- versionCount는 변환 작업 유무나 상태와 관계없이 해당 Document의 DocumentVersion 행 수를 센다. 버전이 없으면 0이다.
- 카드의 PDF 보기와 새 버전 업로드는 기존 동작을 유지한다.
- 새 파일 추가는 선택한 기존 문서 대상을 해제하고 업로드 입력으로 이동한다. 업로드 진행 중·완료 처리 재시도 대기 중에는 다른 업로드로 전환하지 않는다.
Expand Down
2 changes: 1 addition & 1 deletion docs/operations/s3-object-deletion.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,4 @@

## 검증 범위

별도 임시 MySQL DB와 모의 `S3Client`를 사용해 삭제 성공·재시도·점유 만료·동시 실행·DB 반영 실패·업로드 URL 만료 전 대기·파일별 부분 실패를 검증한다. 실제 S3 삭제, IAM 권한과 버킷 버전 관리 상태는 자동화 테스트로 확인하지 않는다. 삭제 API와 화면 버튼은 후속 커밋에서 연결한다.
별도 임시 MySQL DB와 모의 `S3Client`를 사용해 삭제 성공·재시도·점유 만료·동시 실행·DB 반영 실패·업로드 URL 만료 전 대기·파일별 부분 실패를 검증한다. 실제 S3 삭제, IAM 권한과 버킷 버전 관리 상태는 자동화 테스트로 확인하지 않는다. 삭제 API는 `DocumentVersionDeletionController`에서 제공한다. 화면 버튼은 후속 커밋에서 연결한다.
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package withoutjjin.withoutjjin.domain.document.controller;

import jakarta.validation.constraints.Positive;
import lombok.RequiredArgsConstructor;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import withoutjjin.withoutjjin.domain.document.service.DocumentVersionDeletionService;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/workspaces/{workspaceId}/documents/{documentId}/versions")
public class DocumentVersionDeletionController {

private final DocumentVersionDeletionService deletionService;

@DeleteMapping("/{documentVersionId}")
public ResponseEntity<Void> deleteVersion(
@PathVariable @Positive Long workspaceId,
@PathVariable @Positive Long documentId,
@PathVariable @Positive Long documentVersionId,
@AuthenticationPrincipal OidcUser oidcUser
) {
deletionService.deleteVersion(workspaceId, documentId, documentVersionId,
oidcUser.getIssuer().toString(), oidcUser.getSubject());
return ResponseEntity.noContent()
.cacheControl(CacheControl.noStore())
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
public record DocumentListResponse(
Long id,
String title,
// 현재 남은 DocumentVersion의 최대 versionNumber이며, 버전이 없으면 0이다.
// 번호 발급에 사용하는 Document.revision과는 삭제 이후 값이 다를 수 있다.
Integer revision,
LocalDateTime createdAt,
// 최신 DocumentVersion 또는 DocumentConversionJob이 없으면 null이다.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ public class Document {
@Column(name = "title", nullable = false)
private String title;

// 파일을 아직 등록하지 않은 문서는 0, 첫 버전을 등록하면 1이다.
// 마지막으로 발급한 DocumentVersion 번호다. 처음에는 0이며 버전 삭제 시에도 줄이지 않는다.
// 현재 남은 최신 버전 번호는 DocumentVersion에서 별도로 조회한다.
@Column(name = "revision", nullable = false)
private Integer revision;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,21 @@ public interface DocumentRepository extends JpaRepository<Document, Long> {
@Query("select doc from Document doc where doc.id = :documentId")
Optional<Document> findByIdForUpdate(@Param("documentId") Long documentId);

// 최신 버전에 작업이 없어도 Document를 누락하지 않고 DTO 필드만 조회한다.
// 남은 최대 버전 번호를 조회한다. Document.revision은 마지막 발급 번호이므로 사용하지 않는다.
@Query("""
select new withoutjjin.withoutjjin.domain.document.dto.DocumentListResponse(
doc.id, doc.title, doc.revision, doc.createdAt, job.status, count(history.id)
doc.id, doc.title, coalesce(latest.versionNumber, 0), doc.createdAt, job.status, count(history.id)
)
from Document doc
left join DocumentVersion history on history.document = doc
left join DocumentVersion latest
on latest.document = doc and latest.versionNumber = doc.revision
on latest.document = doc and latest.versionNumber = (
select max(remaining.versionNumber) from DocumentVersion remaining
where remaining.document = doc
)
left join DocumentConversionJob job on job.documentVersion = latest
where doc.workspace.id = :workspaceId
group by doc.id, doc.title, doc.revision, doc.createdAt, job.status
group by doc.id, doc.title, latest.versionNumber, doc.createdAt, job.status
order by doc.createdAt desc, doc.id desc
""")
List<DocumentListResponse> findAllWithLatestConversionStatusByWorkspaceId(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ public interface DocumentVersionRepository extends JpaRepository<DocumentVersion

boolean existsByStorageKeyAndIdNot(String storageKey, Long documentVersionId);

Optional<DocumentVersion> findFirstByDocumentIdOrderByVersionNumberDesc(Long documentId);

@Query("""
select new withoutjjin.withoutjjin.domain.document.dto.DocumentVersionListResponse(
dv.id, dv.document.id, dv.versionNumber, dv.originalFileName, dv.fileSize,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public List<DocumentListResponse> getDocuments(Long workspaceId, String issuer,
@Transactional(readOnly = true)
public List<DocumentVersionListResponse> getVersions(Long workspaceId, Long documentId,
String issuer, String subject) {
workspaceService.getWorkSpaceForMember(workspaceId, issuer, subject);
workspaceService.getWorkSpaceForMember(workspaceId, issuer, subject);// 해당유저가 조회하는지 확인
if (!documentRepository.existsByIdAndWorkspaceId(documentId, workspaceId)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "워크스페이스에서 문서를 찾을 수 없습니다.");
}
Expand All @@ -55,7 +55,7 @@ public PdfUrlResponse getPdfUrl(Long documentId, String issuer, String subject)
Document document = documentRepository.findById(documentId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "문서를 찾을 수 없습니다."));
workspaceService.getWorkSpaceForMember(document.getWorkspace().getId(), issuer, subject);
DocumentVersion version = documentVersionRepository.findByDocumentIdAndVersionNumber(documentId, document.getRevision())
DocumentVersion version = documentVersionRepository.findFirstByDocumentIdOrderByVersionNumberDesc(documentId)
.orElseThrow(DocumentQueryService::pdfNotReady);
return generatePdfUrl(version);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ void selectsOnlyRequestedWorkspaceDocuments() {
}

@Test
@DisplayName("작업 저장 순서가 아닌 Document.revision에 해당하는 최신 버전의 상태만 반환한다")
void selectsLatestRevisionStatusWithoutDuplicatingDocument() {
@DisplayName("작업 저장 순서가 아닌 남은 최대 버전 번호에 해당하는 상태만 반환한다")
void selectsHighestRemainingVersionStatusWithoutDuplicatingDocument() {
Document document = document(workspace, "버전이 여러 개인 문서", 2, time(0));
// 최신 버전을 먼저 저장하여 작업 ID의 최댓값을 잘못 선택하는 구현도 검증한다.
addVersion(document, 2, DocumentConversionJobStatus.COMPLETED);
Expand Down Expand Up @@ -150,6 +150,46 @@ void countsActualVersionsRatherThanRevision() {
});
}

@Test
@DisplayName("마지막 발급 번호에 해당하는 버전이 없어도 남은 최대 버전 번호와 상태를 반환한다")
void selectsHighestRemainingVersionRatherThanLastIssuedNumber() {
Document document = document(workspace, "V5를 삭제한 문서", 5, time(0));
addVersion(document, 4, DocumentConversionJobStatus.PENDING);
addVersion(document, 2, DocumentConversionJobStatus.COMPLETED);
flushAndClear();

assertThat(findDocuments()).containsExactly(new DocumentListResponse(
document.getId(), document.getTitle(), 4, time(0), DocumentConversionJobStatus.PENDING, 2L));
assertThat(entityManager.find(Document.class, document.getId()).getRevision()).isEqualTo(5);
}

@Test
@DisplayName("과거 발급 번호가 있어도 남은 버전이 없으면 응답 버전 번호와 개수는 0이다")
void returnsZeroForDocumentWhoseVersionsWereAllDeleted() {
Document document = document(workspace, "모든 버전을 삭제한 문서", 5, time(0));
flushAndClear();

assertThat(findDocuments()).containsExactly(new DocumentListResponse(
document.getId(), document.getTitle(), 0, time(0), null, 0L));
assertThat(entityManager.find(Document.class, document.getId()).getRevision()).isEqualTo(5);
}

@Test
@DisplayName("같은 워크스페이스에서도 각 Document의 남은 최신 번호와 상태·개수를 따로 계산한다")
void correlatesLatestVersionWithEachDocument() {
Document first = document(workspace, "첫 Document", 5, time(0));
addVersion(first, 1, DocumentConversionJobStatus.COMPLETED);
addVersion(first, 4, DocumentConversionJobStatus.FAILED);
Document second = document(workspace, "둘째 Document", 9, time(1));
addVersion(second, 8, DocumentConversionJobStatus.COMPLETED);
addVersion(second, 2, DocumentConversionJobStatus.PROCESSING);
flushAndClear();

assertThat(findDocuments()).containsExactly(
new DocumentListResponse(second.getId(), second.getTitle(), 8, time(1), DocumentConversionJobStatus.COMPLETED, 2L),
new DocumentListResponse(first.getId(), first.getTitle(), 4, time(0), DocumentConversionJobStatus.FAILED, 2L));
}

private List<DocumentListResponse> findDocuments() {
return repository.findAllWithLatestConversionStatusByWorkspaceId(workspace.getId());
}
Expand Down
Loading
Loading