Skip to content

Commit

Permalink
781: Blue phase complete
Browse files Browse the repository at this point in the history
  • Loading branch information
CristianoZingaretti committed Aug 5, 2024
1 parent 466ebbe commit 84b3000
Show file tree
Hide file tree
Showing 2 changed files with 149 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
import com.amazonaws.services.kms.model.NotFoundException;
import com.fasterxml.jackson.databind.ObjectMapper;
import it.pagopa.pn.commons.utils.dynamodb.async.DynamoDbAsyncTableDecorator;
import it.pagopa.pn.ec.pdfraster.model.entity.AttachmentToConvert;
import it.pagopa.pn.ec.pdfraster.model.entity.PdfConversionEntity;
import it.pagopa.pn.ec.pdfraster.model.entity.RequestConversionEntity;
import it.pagopa.pn.ec.pdfraster.service.DynamoPdfRasterService;
import it.pagopa.pn.ec.repositorymanager.configurationproperties.RepositoryManagerDynamoTableName;
import it.pagopa.pn.ec.rest.v1.dto.PdfConversionDto;
import it.pagopa.pn.ec.rest.v1.dto.RequestConversionDto;
import lombok.CustomLog;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -45,71 +45,84 @@ public DynamoPdfRasterServiceImpl(DynamoDbEnhancedAsyncClient dynamoDbEnhancedCl

@Override
public Mono<RequestConversionDto> insertRequestConversion(RequestConversionDto requestConversionDto) {
return Mono.fromCallable(() -> {
log.logStartingProcess(PDF_RASTER_INSERT_REQUEST_CONVERSION);
RequestConversionEntity requestConversionEntity = objectMapper.convertValue(requestConversionDto, RequestConversionEntity.class);

requestTable.putItem(PutItemEnhancedRequest.builder(RequestConversionEntity.class)
.item(requestConversionEntity)
.build());
return requestConversionEntity;
})
.flatMap(requestConversionEntity -> {
Flux<PdfConversionEntity> pdfConversions = Flux.fromIterable(requestConversionEntity.getAttachments())
.map(attachment -> {
PdfConversionEntity pdfConversion = new PdfConversionEntity();
pdfConversion.setFileKey(attachment.getNewFileKey().replace("safestorage://", ""));
pdfConversion.setRequestId(requestConversionEntity.getRequestId());
pdfConversion.setExpiration(null);
return pdfConversion;
});
return Flux.from(pdfConversions)
.flatMap(pdfConversion -> Mono.fromCallable(() -> conversionTable.putItem(PutItemEnhancedRequest.builder(PdfConversionEntity.class)
.item(pdfConversion)
.build())))
.then(Mono.just(requestConversionEntity));
})
.map(requestConversionEntity -> objectMapper.convertValue(requestConversionEntity, RequestConversionDto.class))
return Mono.fromCallable(() -> convertToEntity(requestConversionDto))
.flatMap(this::saveRequestConversionEntity)
.flatMap(this::savePdfConversions)
.map(this::convertToDto)
.doOnSuccess(result -> log.logEndingProcess(PDF_RASTER_INSERT_REQUEST_CONVERSION))
.doOnError(throwable -> log.logEndingProcess(PDF_RASTER_INSERT_REQUEST_CONVERSION, false, throwable.getMessage()));
}

private RequestConversionEntity convertToEntity(RequestConversionDto dto) {
log.logStartingProcess(PDF_RASTER_INSERT_REQUEST_CONVERSION);
return objectMapper.convertValue(dto, RequestConversionEntity.class);
}

private Mono<RequestConversionEntity> saveRequestConversionEntity(RequestConversionEntity entity) {
return Mono.fromCallable(() -> {
requestTable.putItem(PutItemEnhancedRequest.builder(RequestConversionEntity.class)
.item(entity)
.build());
return entity;
});
}

private Mono<RequestConversionEntity> savePdfConversions(RequestConversionEntity entity) {
String requestId = entity.getRequestId();
return Flux.fromIterable(entity.getAttachments())
.map(attachment -> createPdfConversion(attachment, requestId))
.flatMap(this::savePdfConversion)
.then(Mono.just(entity));
}

private PdfConversionEntity createPdfConversion(AttachmentToConvert attachment, String requestId) {
PdfConversionEntity pdfConversion = new PdfConversionEntity();
pdfConversion.setFileKey(attachment.getNewFileKey().replace("safestorage://", ""));
pdfConversion.setRequestId(requestId);
pdfConversion.setExpiration(null);
return pdfConversion;
}

private Mono<Void> savePdfConversion(PdfConversionEntity pdfConversion) {
return Mono.fromCallable(() -> {
conversionTable.putItem(PutItemEnhancedRequest.builder(PdfConversionEntity.class)
.item(pdfConversion)
.build());
return null;
});
}

private RequestConversionDto convertToDto(RequestConversionEntity entity) {
return objectMapper.convertValue(entity, RequestConversionDto.class);
}


@Override
public Mono<RequestConversionDto> updateRequestConversion(String fileKey, Boolean converted) {

log.logStartingProcess(PDF_RASTER_UPDATE_REQUEST_CONVERSION);

if (converted == null || !converted) {
return Mono.error(new IllegalArgumentException("Invalid value for 'converted': must be true."));
}

return getPdfConversionFromDynamoDb(fileKey)
.map(pdfConversionEntity ->
objectMapper.convertValue(pdfConversionEntity, PdfConversionDto.class)
)
.switchIfEmpty(Mono.error(new NotFoundException("Not found for fileKey: " + fileKey)))
.flatMap(existingRequest -> {

String requestId = existingRequest.getRequestId();
return getRequestConversionFromDynamoDb(requestId);

})
.flatMap(requestConversionEntity -> {
requestConversionEntity.getAttachments().parallelStream()
.filter(attachmentToConvert -> attachmentToConvert.getNewFileKey().equals(fileKey))
.findFirst()
.ifPresent(attachmentToConvert -> attachmentToConvert.setConverted(true));


return Mono.fromFuture(requestTable.putItem(requestConversionEntity))
.thenReturn(requestConversionEntity);
})
.flatMap(pdfConversionEntity -> getRequestConversionFromDynamoDb(pdfConversionEntity.getRequestId())
.flatMap(requestConversionEntity -> updateAttachmentConversion(requestConversionEntity, fileKey, converted))
.map(this::convertToDto)
.doOnSuccess(result -> log.logEndingProcess(PDF_RASTER_UPDATE_REQUEST_CONVERSION))
.doOnError(exception -> log.logEndingProcess(PDF_RASTER_UPDATE_REQUEST_CONVERSION, false, exception.getMessage()))
);
}

.map(requestConversionEntity -> objectMapper.convertValue(requestConversionEntity, RequestConversionDto.class))
.doOnSuccess(result -> log.logEndingProcess(GESTIONE_RETRY_CARTACEO))
.doOnError(exception -> log.logEndingProcess(GESTIONE_RETRY_CARTACEO, false, exception.getMessage()));
private Mono<RequestConversionEntity> updateAttachmentConversion(RequestConversionEntity requestConversionEntity, String fileKey, Boolean converted) {
requestConversionEntity.getAttachments().stream()
.filter(attachment -> attachment.getNewFileKey().equals(fileKey))
.findFirst()
.ifPresent(attachment -> attachment.setConverted(converted));

return Mono.fromFuture(requestTable.putItem(requestConversionEntity))
.thenReturn(requestConversionEntity);
}

private Mono<RequestConversionEntity> getRequestConversionFromDynamoDb(String requestId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;

import java.time.Duration;
import java.util.Collections;
import java.util.Objects;

import static org.awaitility.Awaitility.await;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;


Expand Down Expand Up @@ -53,114 +55,154 @@ public void initializeTables() {
}


private static RequestConversionDto MockRequestConversionDto() {
return new RequestConversionDto().requestId("123456789")

private RequestConversionDto createMockRequestConversionDto() {
return new RequestConversionDto()
.requestId("123456789")
.attachments(Collections.singletonList(
new AttachmentToConvertDto().newFileKey("12345")
));
}



@Test
void insertRequestConversionOk() {

RequestConversionDto requestConversionDto = MockRequestConversionDto();
RequestConversionDto requestConversionDto = createMockRequestConversionDto();

Mono<RequestConversionDto> response = dynamoPdfRasterService.insertRequestConversion(requestConversionDto);

StepVerifier.create(response)
.expectNextMatches(Objects::nonNull)
.expectNextMatches(this::validateNonNullResponse)
.verifyComplete();

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
awaitPropagation();

verifyPdfConversionEntities(requestConversionDto);
}


private boolean validateNonNullResponse(RequestConversionDto responseDto) {
return responseDto != null;
}

private void awaitPropagation() {
await().atMost(Duration.ofSeconds(2))
.until(this::verifyPdfConversionEntitiesExist);
}

private boolean verifyPdfConversionEntitiesExist() {
for (AttachmentToConvertDto attachmentDto : createMockRequestConversionDto().getAttachments()) {
PdfConversionEntity result = pdfConversionEntityDynamoDbTable.getItem(builder ->
builder.key(Key.builder().partitionValue(attachmentDto.getNewFileKey()).build()));
if (result == null) {
return false;
}
}
return true;
}

for (AttachmentToConvertDto keyValue : requestConversionDto.getAttachments()) {
PdfConversionEntity result = pdfConversionEntityDynamoDbTable.getItem(builder -> builder.key(Key.builder().partitionValue(keyValue.getNewFileKey()).build()));
private void verifyPdfConversionEntities(RequestConversionDto requestConversionDto) {
for (AttachmentToConvertDto attachmentDto : requestConversionDto.getAttachments()) {
PdfConversionEntity result = pdfConversionEntityDynamoDbTable.getItem(builder ->
builder.key(Key.builder().partitionValue(attachmentDto.getNewFileKey()).build()));
Assertions.assertNotNull(result);
Assertions.assertEquals(requestConversionDto.getRequestId(), result.getRequestId());
}
}


@Test
void updateRequestConversionOk() {
RequestConversionDto requestConversionDto = createMockRequestConversionDto();

RequestConversionDto requestConversionDto = MockRequestConversionDto();

Mono<RequestConversionDto> response = dynamoPdfRasterService.insertRequestConversion(requestConversionDto);
StepVerifier.create(response).expectNextCount(1).verifyComplete();
Mono<RequestConversionDto> insertResponse = dynamoPdfRasterService.insertRequestConversion(requestConversionDto);
StepVerifier.create(insertResponse)
.expectNextCount(1)
.verifyComplete();

String requestId = requestConversionDto.getRequestId();
markAttachmentsAsConverted(requestConversionDto);

for (AttachmentToConvertDto attachment : requestConversionDto.getAttachments()) {
attachment.setConverted(true);
}
Mono<RequestConversionDto> updateResponse = dynamoPdfRasterService.updateRequestConversion("12345", true);

Mono<RequestConversionDto> responseUpdate = dynamoPdfRasterService.updateRequestConversion("12345", true);

StepVerifier.create(responseUpdate)
.expectNextMatches(updatedDto -> updatedDto.getRequestId().equals(requestId))
StepVerifier.create(updateResponse)
.expectNextMatches(updatedDto -> updatedDto.getRequestId().equals(requestConversionDto.getRequestId()))
.verifyComplete();

RequestConversionEntity updatedEcRequestConversionEntity = requestConversionEntityDynamoDbTable.getItem(
verifyUpdatedRequestConversionEntity(requestConversionDto.getRequestId());
}


private void markAttachmentsAsConverted(RequestConversionDto dto) {
dto.getAttachments().forEach(attachment -> attachment.setConverted(true));
}

private void verifyUpdatedRequestConversionEntity(String requestId) {
RequestConversionEntity updatedEntity = requestConversionEntityDynamoDbTable.getItem(
builder -> builder.key(Key.builder().partitionValue(requestId).build())
);
Assertions.assertNotNull(updatedEcRequestConversionEntity);
Assertions.assertNotNull(updatedEntity);

boolean isConverted = updatedEcRequestConversionEntity.getAttachments().stream()
boolean isConverted = updatedEntity.getAttachments().stream()
.allMatch(AttachmentToConvert::getConverted);
Assertions.assertTrue(isConverted);
}


@Test
void insertRequestConversionKoInternalServerError() {
RequestConversionDto requestConversionDto = MockRequestConversionDto();

RequestConversionDto requestConversionDto = createMockRequestConversionDto();

when(dynamoPdfRasterService.insertRequestConversion(requestConversionDto))
.thenReturn(Mono.error(new Generic500ErrorException("Internal Server Error", "")));
simulateInternalServerError();

Mono<RequestConversionDto> response = dynamoPdfRasterService.insertRequestConversion(requestConversionDto);
StepVerifier.create(response)
.expectErrorMatches(error -> error instanceof Generic500ErrorException && error.getMessage().startsWith("Internal Server Error"))
StepVerifier.create(dynamoPdfRasterService.insertRequestConversion(requestConversionDto))
.expectErrorMatches(error ->
error instanceof Generic500ErrorException && error.getMessage().startsWith("Internal Server Error"))
.verify();
}

private void simulateInternalServerError() {
when(dynamoPdfRasterService.insertRequestConversion(any(RequestConversionDto.class)))
.thenReturn(Mono.error(new Generic500ErrorException("Internal Server Error", "")));
}



@Test
void insertRequestConversionKoConflictError() {

RequestConversionDto requestConversionDto = MockRequestConversionDto();

when(dynamoPdfRasterService.insertRequestConversion(requestConversionDto))
.thenReturn(Mono.error(new ConflictException("Element already exists")));
RequestConversionDto requestConversionDto = createMockRequestConversionDto();

Mono<RequestConversionDto> responseConflict = dynamoPdfRasterService.insertRequestConversion(requestConversionDto);
simulateConflictError();

StepVerifier.create(responseConflict)
StepVerifier.create(dynamoPdfRasterService.insertRequestConversion(requestConversionDto))
.expectError(ConflictException.class)
.verify();
}

private void simulateConflictError() {
when(dynamoPdfRasterService.insertRequestConversion(any(RequestConversionDto.class)))
.thenReturn(Mono.error(new ConflictException("Element already exists")));
}



@Test
void updateRequestConversionInvalidConvertedValue() {
String fileKey = "FileKey";
boolean convertedValue = false;

when(dynamoPdfRasterService.updateRequestConversion("FileKey", false))
.thenReturn(Mono.error(new IllegalArgumentException()));
simulateInvalidConvertedValueError(fileKey, convertedValue);

Mono<RequestConversionDto> responseUpdate = dynamoPdfRasterService.updateRequestConversion("StringFileKey", false);

StepVerifier.create(responseUpdate)
StepVerifier.create(dynamoPdfRasterService.updateRequestConversion(fileKey, convertedValue))
.expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException
&& throwable.getMessage().equals("Invalid value for 'converted': must be true."))
.verify();
}

private void simulateInvalidConvertedValueError(String fileKey, boolean converted) {
when(dynamoPdfRasterService.updateRequestConversion(fileKey, converted))
.thenReturn(Mono.error(new IllegalArgumentException("Invalid value for 'converted': must be true.")));
}


Expand Down

0 comments on commit 84b3000

Please sign in to comment.