Skip to content
Open
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
Expand Up @@ -27,6 +27,7 @@
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
Expand All @@ -53,7 +54,7 @@ private static Set<Country> toCountrySet(@RequestParam(required = false) List<St
@PostMapping(value = "/substations/infos", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Get geographical data for substations with the given ids")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Substations geographical data")})
public ResponseEntity<List<SubstationGeoData>> getSubstations(@Parameter(description = "Network UUID") @RequestParam UUID networkUuid,
public CompletableFuture<ResponseEntity<List<SubstationGeoData>>> getSubstations(@Parameter(description = "Network UUID") @RequestParam UUID networkUuid,
@Parameter(description = "Variant Id") @RequestParam(name = "variantId", required = false) String variantId,
@Parameter(description = "Countries") @RequestParam(name = "country", required = false) List<String> countries,
@RequestBody(required = false) List<String> substationIds) {
Expand All @@ -62,14 +63,14 @@ public ResponseEntity<List<SubstationGeoData>> getSubstations(@Parameter(descrip
if (variantId != null) {
network.getVariantManager().setWorkingVariant(variantId);
}
List<SubstationGeoData> substations = geoDataService.getSubstationsData(network, countrySet, substationIds);
return ResponseEntity.ok().body(substations);
return geoDataService.getSubstationsData(network, countrySet, substationIds).thenApply(
substations -> ResponseEntity.ok().body(substations));
}

@PostMapping(value = "/lines/infos", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Get lines geographical data")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Lines geographical data")})
public ResponseEntity<List<LineGeoData>> getLines(@Parameter(description = "Network UUID")@RequestParam UUID networkUuid,
public CompletableFuture<ResponseEntity<List<LineGeoData>>> getLines(@Parameter(description = "Network UUID")@RequestParam UUID networkUuid,
@Parameter(description = "Variant Id") @RequestParam(name = "variantId", required = false) String variantId,
@Parameter(description = "Countries") @RequestParam(name = "country", required = false) List<String> countries,
@RequestBody(required = false) List<String> lineIds) {
Expand All @@ -78,8 +79,8 @@ public ResponseEntity<List<LineGeoData>> getLines(@Parameter(description = "Netw
if (variantId != null) {
network.getVariantManager().setWorkingVariant(variantId);
}
List<LineGeoData> lines = geoDataService.getLinesData(network, countrySet, lineIds);
return ResponseEntity.ok().body(lines);
return geoDataService.getLinesData(network, countrySet, lineIds).thenApply(
lines -> ResponseEntity.ok().body(lines));
}

@PostMapping(value = "/substations")
Expand Down
60 changes: 24 additions & 36 deletions src/main/java/org/gridsuite/geodata/server/GeoDataService.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Streams;
import com.powsybl.commons.exceptions.UncheckedInterruptedException;
import com.powsybl.iidm.network.*;
import com.powsybl.iidm.network.extensions.Coordinate;
import com.powsybl.iidm.network.extensions.SubstationPosition;
Expand All @@ -29,7 +28,6 @@
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.Map.Entry;
Expand Down Expand Up @@ -546,48 +544,38 @@ private Pair<Substation, Substation> getSubstations(Identifiable<?> identifiable
};
}

@Transactional(readOnly = true)
Copy link
Contributor

Choose a reason for hiding this comment

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

Shouldn't we move this Transactional somewhere else ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I suggest in a separate PR ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

(also in this case it looks like all the computation is just a single repository call to the standard find method so it should be equivalent I think.. not 100% sure from the top of my head though. Also not sure what is the official code to do transactions in a separate thread.. probably it's just the same but I would need to double check..)

public List<SubstationGeoData> getSubstationsData(Network network, Set<Country> countrySet, List<String> substationIds) {
CompletableFuture<List<SubstationGeoData>> substationGeoDataFuture = geoDataExecutionService.supplyAsync(() -> {
if (substationIds != null) {
if (!countrySet.isEmpty()) {
LOGGER.warn("Countries will not be taken into account to filter substation position.");
public CompletableFuture<List<SubstationGeoData>> getSubstationsData(Network network, Set<Country> countrySet, List<String> substationIds) {
return geoDataExecutionService.supplyAsync(() -> {
try {
if (substationIds != null) {
if (!countrySet.isEmpty()) {
LOGGER.warn("Countries will not be taken into account to filter substation position.");
}
return getSubstationsByIds(network, new HashSet<>(substationIds));
} else {
return getSubstationsByCountries(network, countrySet);
}
return getSubstationsByIds(network, new HashSet<>(substationIds));
} else {
return getSubstationsByCountries(network, countrySet);
} catch (Exception e) {
throw new GeoDataException(FAILED_SUBSTATIONS_LOADING, e);
Copy link
Contributor

Choose a reason for hiding this comment

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

Does it behave the same to throw inside or outside the async ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes it's the same. And there are unit tests that verify that from an http client point of view, the thrown exception inside the completablefuture is correctly used by the servlet container asynchronously to return the associated error http reponse to the client

}
});
try {
return substationGeoDataFuture.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new UncheckedInterruptedException(e);
} catch (Exception e) {
throw new GeoDataException(FAILED_SUBSTATIONS_LOADING, e);
}
}

@Transactional(readOnly = true)
public List<LineGeoData> getLinesData(Network network, Set<Country> countrySet, List<String> lineIds) {
CompletableFuture<List<LineGeoData>> lineGeoDataFuture = geoDataExecutionService.supplyAsync(() -> {
if (lineIds != null) {
if (!countrySet.isEmpty()) {
LOGGER.warn("Countries will not be taken into account to filter line position.");
public CompletableFuture<List<LineGeoData>> getLinesData(Network network, Set<Country> countrySet, List<String> lineIds) {
return geoDataExecutionService.supplyAsync(() -> {
try {
if (lineIds != null) {
if (!countrySet.isEmpty()) {
LOGGER.warn("Countries will not be taken into account to filter line position.");
}
return getLinesByIds(network, new HashSet<>(lineIds));
} else {
return getLinesByCountries(network, countrySet);
}
return getLinesByIds(network, new HashSet<>(lineIds));
} else {
return getLinesByCountries(network, countrySet);
} catch (Exception e) {
throw new GeoDataException(FAILED_LINES_LOADING, e);
}
});
try {
return lineGeoDataFuture.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new UncheckedInterruptedException(e);
} catch (Exception e) {
throw new GeoDataException(FAILED_LINES_LOADING, e);
}
}

List<LineGeoData> getLinesByIds(Network network, Set<String> linesIds) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
Expand All @@ -37,7 +38,7 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

/**
Expand Down Expand Up @@ -84,14 +85,28 @@ void test() throws Exception {
given(service.getNetwork(networkUuid, PreloadingStrategy.NONE)).willReturn(testNetwork);
given(service.getNetwork(networkUuid, PreloadingStrategy.COLLECTION)).willReturn(testNetwork);

mvc.perform(post("/" + VERSION + "/substations/infos?networkUuid=" + networkUuid)
// Just to hold the async state that we need to pass immediately back to mockmvc
// as per https://docs.spring.io/spring-framework/reference/testing/mockmvc/hamcrest/async-requests.html
// to mimic servlet 3.0+ AsyncContext not done automatically by TestDispatcherServlet (unlike the real servlet
// container in production)
// Note: if the controller throws before returning the completablefuture, the request is not async and we don't
// need this and we must not call asyncStarted() and asyncDispatch()
MvcResult mvcResult;

mvcResult = mvc.perform(post("/" + VERSION + "/substations/infos?networkUuid=" + networkUuid)
.contentType(APPLICATION_JSON))
.andExpect(request().asyncStarted())
.andReturn();
mvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(0)));

mvc.perform(post("/" + VERSION + "/substations/infos?networkUuid=" + networkUuid + "&variantId=" + VARIANT_ID)
mvcResult = mvc.perform(post("/" + VERSION + "/substations/infos?networkUuid=" + networkUuid + "&variantId=" + VARIANT_ID)
.contentType(APPLICATION_JSON))
.andExpect(request().asyncStarted())
.andReturn();
mvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(0)));
Expand All @@ -101,14 +116,20 @@ void test() throws Exception {
.andExpect(content().string("Variant '" + WRONG_VARIANT_ID + "' not found"))
.andExpect(status().isInternalServerError());

mvc.perform(post("/" + VERSION + "/lines/infos?networkUuid=" + networkUuid)
mvcResult = mvc.perform(post("/" + VERSION + "/lines/infos?networkUuid=" + networkUuid)
.contentType(APPLICATION_JSON))
.andExpect(request().asyncStarted())
.andReturn();
mvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(0)));

mvc.perform(post("/" + VERSION + "/lines/infos?networkUuid=" + networkUuid + "&variantId=" + VARIANT_ID)
mvcResult = mvc.perform(post("/" + VERSION + "/lines/infos?networkUuid=" + networkUuid + "&variantId=" + VARIANT_ID)
.contentType(APPLICATION_JSON))
.andExpect(request().asyncStarted())
.andReturn();
mvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(0)));
Expand Down Expand Up @@ -152,30 +173,42 @@ void test() throws Exception {
.content(toString(GEO_DATA_LINES)))
.andExpect(status().isOk());

mvc.perform(post("/" + VERSION + "/substations/infos?networkUuid=" + networkUuid + "&variantId=" + VARIANT_ID + "&country=" + Country.FR)
mvcResult = mvc.perform(post("/" + VERSION + "/substations/infos?networkUuid=" + networkUuid + "&variantId=" + VARIANT_ID + "&country=" + Country.FR)
.contentType(APPLICATION_JSON)
.content("[\"P1\", \"P2\"]"))
.andExpect(request().asyncStarted())
.andReturn();
mvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(0)));

mvc.perform(post("/" + VERSION + "/substations/infos?networkUuid=" + networkUuid + "&variantId=" + VARIANT_ID)
mvcResult = mvc.perform(post("/" + VERSION + "/substations/infos?networkUuid=" + networkUuid + "&variantId=" + VARIANT_ID)
.contentType(APPLICATION_JSON)
.content("[\"P1\", \"P2\"]"))
.andExpect(request().asyncStarted())
.andReturn();
mvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(0)));

mvc.perform(post("/" + VERSION + "/lines/infos?networkUuid=" + networkUuid + "&variantId=" + VARIANT_ID + "&country=" + Country.FR)
mvcResult = mvc.perform(post("/" + VERSION + "/lines/infos?networkUuid=" + networkUuid + "&variantId=" + VARIANT_ID + "&country=" + Country.FR)
.contentType(APPLICATION_JSON)
.content("[\"NHV1_NHV2_2\", \"NHV1_NHV2_1\"]"))
.andExpect(request().asyncStarted())
.andReturn();
mvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(0)));

mvc.perform(post("/" + VERSION + "/lines/infos?networkUuid=" + networkUuid + "&variantId=" + VARIANT_ID)
mvcResult = mvc.perform(post("/" + VERSION + "/lines/infos?networkUuid=" + networkUuid + "&variantId=" + VARIANT_ID)
.contentType(APPLICATION_JSON)
.content("[\"NHV1_NHV2_2\", \"NHV1_NHV2_1\"]"))
.andExpect(request().asyncStarted())
.andReturn();
mvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(0)));
Expand All @@ -189,8 +222,11 @@ void testGetLinesError() throws Exception {
given(service.getNetwork(networkUuid, PreloadingStrategy.COLLECTION)).willReturn(testNetwork);
given(lineRepository.findAllById(any())).willThrow(new GeoDataException(GeoDataException.Type.PARSING_ERROR, new RuntimeException("Error parsing")));

mvc.perform(post("/" + VERSION + "/lines/infos?networkUuid=" + networkUuid)
MvcResult mvcResult = mvc.perform(post("/" + VERSION + "/lines/infos?networkUuid=" + networkUuid)
.contentType(APPLICATION_JSON))
.andExpect(request().asyncStarted())
.andReturn();
mvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isInternalServerError());
}
}