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
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package withoutjjin.withoutjjin.domain.document.conversion;

// S3 업로드가 성공한 PDF의 결과 값이다. StoreFile 엔티티를 생성하거나 저장하지 않는다.
public record StoredPdf(String objectKey, long sizeBytes, int pageCount) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package withoutjjin.withoutjjin.domain.document.service;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import withoutjjin.withoutjjin.domain.document.conversion.ConvertedPdf;
import withoutjjin.withoutjjin.domain.document.conversion.StoredPdf;
import withoutjjin.withoutjjin.domain.document.conversion.WordPdfConverter;
import withoutjjin.withoutjjin.domain.document.storage.S3ObjectReader;
import withoutjjin.withoutjjin.domain.document.storage.S3PdfWriter;

@Service
@RequiredArgsConstructor
public class DocumentConversionService {

private final S3ObjectReader s3ObjectReader;
private final WordPdfConverter wordPdfConverter;
private final S3PdfWriter s3PdfWriter;

// 호출한 코드에서 확인한 StoreFile.objectKey를 전달받는다.
// S3 다운로드·변환·업로드를 기다리는 동안 호출자의 DB 트랜잭션도 유지하지 않는다.
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public StoredPdf convertAndStore(Long workspaceId, String originalObjectKey) {
if (workspaceId == null || workspaceId <= 0) {
throw new IllegalArgumentException("워크스페이스 번호는 양수여야 합니다.");
}
if (originalObjectKey == null || originalObjectKey.isBlank()) {
throw new IllegalArgumentException("DOCX의 S3 저장 키가 필요합니다.");
}

byte[] docxContent = s3ObjectReader.downloadDocx(originalObjectKey);
ConvertedPdf convertedPdf = wordPdfConverter.convert(docxContent);
String pdfObjectKey = s3PdfWriter.upload(workspaceId, convertedPdf.content());

return new StoredPdf(pdfObjectKey, convertedPdf.content().length, convertedPdf.pageCount());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,23 @@
public class DocumentStorageKeyGenerator { // 파일키 생성자

public String generate(Long workspaceId) {
validateWorkspaceId(workspaceId);
//ex) workspaces/10/uploads/550e8400-e29b-41d4-a716-446655440000
return "workspaces/" + workspaceId
+ "/uploads/" + UUID.randomUUID();
}

public String generatePdf(Long workspaceId) {
validateWorkspaceId(workspaceId);
return "workspaces/" + workspaceId
+ "/review-pdfs/" + UUID.randomUUID() + ".pdf";
}

private void validateWorkspaceId(Long workspaceId) {
if (workspaceId == null || workspaceId <= 0) {
throw new IllegalArgumentException(
"워크스페이스 번호는 양수여야 합니다."
);
}
//ex) workspaces/10/uploads/550e8400-e29b-41d4-a716-446655440000
return "workspaces/" + workspaceId
+ "/uploads/" + UUID.randomUUID();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,21 @@

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;

import java.io.IOException;

@Component
public class S3ObjectReader {

private static final int MAX_DOCX_BYTES = 20 * 1024 * 1024;

private final S3Client s3Client;
private final String bucket;

Expand All @@ -32,4 +40,32 @@

return s3Client.headObject(request); // 실제 S3 HeadObject 요청 실행
}
}

public byte[] downloadDocx(String objectKey) {
GetObjectRequest request = GetObjectRequest.builder()
.bucket(bucket)
.key(objectKey)
.build();

try (ResponseInputStream<GetObjectResponse> response = s3Client.getObject(request)) {
try {

Check warning on line 51 in src/main/java/withoutjjin/withoutjjin/domain/document/storage/S3ObjectReader.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Extract this nested try block into a separate method.

See more on https://sonarcloud.io/project/issues?id=f-lab-edu_withoutJJIN&issues=AaG6cKn7MOgPm5Xec5mX&open=AaG6cKn7MOgPm5Xec5mX&pullRequest=33
Long contentLength = response.response().contentLength();
if (contentLength != null && contentLength > MAX_DOCX_BYTES) {
throw new IllegalStateException("S3 DOCX 데이터가 20MiB 제한을 초과했습니다.");
}
// Content-Length와 별개로 실제 읽는 크기도 제한한다.
byte[] content = response.readNBytes(MAX_DOCX_BYTES + 1);
if (content.length > MAX_DOCX_BYTES) {
throw new IllegalStateException("S3 DOCX 데이터가 20MiB 제한을 초과했습니다.");
}
return content;
} catch (IOException | RuntimeException exception) {
// close()에서 남은 본문을 계속 읽지 않도록 실패한 다운로드를 중단한다.
response.abort();
throw exception;
}
} catch (IOException exception) {
throw SdkClientException.create("S3 DOCX 데이터를 읽지 못했습니다.", exception);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package withoutjjin.withoutjjin.domain.document.storage;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;

@Component
public class S3PdfWriter {

private static final int MAX_PDF_BYTES = 64 * 1024 * 1024;

private final S3Client s3Client;
private final DocumentStorageKeyGenerator storageKeyGenerator;
private final String bucket;

public S3PdfWriter(
S3Client s3Client,
DocumentStorageKeyGenerator storageKeyGenerator,
@Value("${aws.s3.bucket}") String bucket
) {
if (bucket == null || bucket.isBlank()) {
throw new IllegalStateException("S3 버킷 이름을 설정해야 합니다.");
}
this.s3Client = s3Client;
this.storageKeyGenerator = storageKeyGenerator;
this.bucket = bucket;
}

// WordPdfConverter에서 검증한 PDF 데이터를 전달받는다. PDF 구조를 다시 검사하지 않는다.
public String upload(Long workspaceId, byte[] pdfContent) {
if (pdfContent == null || pdfContent.length == 0 || pdfContent.length > MAX_PDF_BYTES) {
throw new IllegalArgumentException("PDF 데이터는 비어 있지 않고 64MiB 이하여야 합니다.");
}

String objectKey = storageKeyGenerator.generatePdf(workspaceId);
PutObjectRequest request = PutObjectRequest.builder()
.bucket(bucket)
.key(objectKey)
.contentType("application/pdf")
// 우연히 같은 키가 생성되어도 기존 S3 파일을 덮어쓰지 않는다.
.ifNoneMatch("*")
.build();

s3Client.putObject(request, RequestBody.fromBytes(pdfContent));
return objectKey;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package withoutjjin.withoutjjin.domain.document.service;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import withoutjjin.withoutjjin.domain.document.conversion.StoredPdf;
import withoutjjin.withoutjjin.domain.document.conversion.WordPdfConverter;
import withoutjjin.withoutjjin.domain.document.storage.DocumentStorageKeyGenerator;
import withoutjjin.withoutjjin.domain.document.storage.S3ObjectReader;
import withoutjjin.withoutjjin.domain.document.storage.S3PdfWriter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

class DocumentConversionFlowTest {

@Test
@DisplayName("S3의 DOCX를 변환 요청에 담고 PDF 응답을 S3에 업로드한다")
void connectsDownloadConversionAndUpload() throws IOException {
String originalKey = "workspaces/10/uploads/original-docx";
byte[] docx = new ClassPathResource("conversion/korean-document.docx").getContentAsByteArray();
byte[] pdf = pdfWithTwoPages();
S3Client s3Client = mock(S3Client.class);
when(s3Client.getObject(any(GetObjectRequest.class))).thenReturn(new ResponseInputStream<>(
GetObjectResponse.builder().contentLength((long) docx.length).build(),
new ByteArrayInputStream(docx)));
when(s3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class)))
.thenReturn(PutObjectResponse.builder().build());

RestClient.Builder builder = RestClient.builder().baseUrl("http://converter.test");
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
server.expect(requestTo("http://converter.test/forms/libreoffice/convert"))
.andExpect(method(HttpMethod.POST))
.andExpect(content().contentTypeCompatibleWith(MediaType.MULTIPART_FORM_DATA))
.andExpect(request -> assertThat(((MockClientHttpRequest) request).getBodyAsBytes())
.containsSubsequence(docx))
.andRespond(withSuccess(pdf, MediaType.APPLICATION_PDF));

DocumentConversionService service = new DocumentConversionService(
new S3ObjectReader(s3Client, "ftfm-test-bucket"),
new WordPdfConverter(builder.build()),
new S3PdfWriter(s3Client, new DocumentStorageKeyGenerator(), "ftfm-test-bucket"));

StoredPdf result = service.convertAndStore(10L, originalKey);

ArgumentCaptor<GetObjectRequest> getCaptor = ArgumentCaptor.forClass(GetObjectRequest.class);
ArgumentCaptor<PutObjectRequest> putCaptor = ArgumentCaptor.forClass(PutObjectRequest.class);
ArgumentCaptor<RequestBody> bodyCaptor = ArgumentCaptor.forClass(RequestBody.class);
var order = inOrder(s3Client);
order.verify(s3Client).getObject(getCaptor.capture());
order.verify(s3Client).putObject(putCaptor.capture(), bodyCaptor.capture());
order.verifyNoMoreInteractions();
assertThat(getCaptor.getValue().bucket()).isEqualTo("ftfm-test-bucket");
assertThat(getCaptor.getValue().key()).isEqualTo(originalKey);
assertThat(putCaptor.getValue().bucket()).isEqualTo("ftfm-test-bucket");
assertThat(putCaptor.getValue().key()).isEqualTo(result.objectKey()).isNotEqualTo(originalKey);
assertThat(putCaptor.getValue().contentType()).isEqualTo("application/pdf");
try (InputStream uploaded = bodyCaptor.getValue().contentStreamProvider().newStream()) {
assertThat(uploaded.readAllBytes()).containsExactly(pdf);
}
assertThat(result.sizeBytes()).isEqualTo(pdf.length);
assertThat(result.pageCount()).isEqualTo(2);
server.verify();
}

private static byte[] pdfWithTwoPages() throws IOException {
try (PDDocument pdf = new PDDocument(); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
pdf.addPage(new PDPage());
pdf.addPage(new PDPage());
pdf.save(output);
return output.toByteArray();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package withoutjjin.withoutjjin.domain.document.service;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InOrder;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.model.S3Exception;
import withoutjjin.withoutjjin.domain.document.conversion.ConvertedPdf;
import withoutjjin.withoutjjin.domain.document.conversion.StoredPdf;
import withoutjjin.withoutjjin.domain.document.conversion.WordPdfConverter;
import withoutjjin.withoutjjin.domain.document.conversion.WordPdfConversionException;
import withoutjjin.withoutjjin.domain.document.storage.S3ObjectReader;
import withoutjjin.withoutjjin.domain.document.storage.S3PdfWriter;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.*;

class DocumentConversionServiceTest {

private static final String ORIGINAL_KEY = "workspaces/10/uploads/original-docx";
private static final String PDF_KEY = "workspaces/10/review-pdfs/converted.pdf";

private final S3ObjectReader reader = mock(S3ObjectReader.class);
private final WordPdfConverter converter = mock(WordPdfConverter.class);
private final S3PdfWriter writer = mock(S3PdfWriter.class);
private final DocumentConversionService service = new DocumentConversionService(reader, converter, writer);

@Test
@DisplayName("DOCX 다운로드·PDF 변환·PDF 업로드를 순서대로 실행하고 저장 결과를 반환한다")
void convertsAndStoresPdfInOrder() {
byte[] docx = {1, 2};
byte[] pdf = {3, 4, 5};
when(reader.downloadDocx(ORIGINAL_KEY)).thenReturn(docx);
when(converter.convert(docx)).thenReturn(new ConvertedPdf(pdf, 2));
when(writer.upload(10L, pdf)).thenReturn(PDF_KEY);

StoredPdf result = service.convertAndStore(10L, ORIGINAL_KEY);

InOrder order = inOrder(reader, converter, writer);
order.verify(reader).downloadDocx(ORIGINAL_KEY);
order.verify(converter).convert(docx);
order.verify(writer).upload(10L, pdf);
order.verifyNoMoreInteractions();
assertThat(result).isEqualTo(new StoredPdf(PDF_KEY, 3L, 2));
}

@Test
@DisplayName("DOCX 다운로드가 실패하면 PDF 변환과 업로드를 실행하지 않는다")
void stopsBeforeConversionWhenDownloadFails() {
SdkClientException failure = SdkClientException.create("S3 다운로드 실패");
when(reader.downloadDocx(ORIGINAL_KEY)).thenThrow(failure);

assertThatThrownBy(() -> service.convertAndStore(10L, ORIGINAL_KEY)).isSameAs(failure);

verifyNoInteractions(converter, writer);
}

@Test
@DisplayName("PDF 변환이 실패하면 PDF 업로드를 실행하지 않는다")
void stopsBeforeUploadWhenConversionFails() {
byte[] docx = {1, 2};
WordPdfConversionException failure = new WordPdfConversionException("변환 실패");
when(reader.downloadDocx(ORIGINAL_KEY)).thenReturn(docx);
when(converter.convert(docx)).thenThrow(failure);

assertThatThrownBy(() -> service.convertAndStore(10L, ORIGINAL_KEY)).isSameAs(failure);

verifyNoInteractions(writer);
}

@Test
@DisplayName("PDF 업로드가 실패하면 StoredPdf를 반환하지 않고 예외를 전달한다")
void propagatesUploadFailure() {
byte[] docx = {1, 2};
byte[] pdf = {3, 4, 5};
S3Exception failure = (S3Exception) S3Exception.builder()
.statusCode(403).message("PDF 업로드 실패").build();
when(reader.downloadDocx(ORIGINAL_KEY)).thenReturn(docx);
when(converter.convert(docx)).thenReturn(new ConvertedPdf(pdf, 2));
when(writer.upload(10L, pdf)).thenThrow(failure);

assertThatThrownBy(() -> service.convertAndStore(10L, ORIGINAL_KEY)).isSameAs(failure);
}

@ParameterizedTest
@NullSource
@ValueSource(longs = {0, -1})
@DisplayName("워크스페이스 번호가 없거나 양수가 아니면 다운로드를 시작하지 않는다")
void rejectsInvalidWorkspaceId(Long workspaceId) {
assertThatThrownBy(() -> service.convertAndStore(workspaceId, ORIGINAL_KEY))
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("워크스페이스");

verifyNoInteractions(reader, converter, writer);
}

@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {" "})
@DisplayName("DOCX 저장 키가 없으면 다운로드를 시작하지 않는다")
void rejectsMissingOriginalObjectKey(String objectKey) {
assertThatThrownBy(() -> service.convertAndStore(10L, objectKey))
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("저장 키");

verifyNoInteractions(reader, converter, writer);
}
}
Loading
Loading